code
stringlengths
1
2.08M
language
stringclasses
1 value
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Defines the "virtual" dialog, dialog content and dialog button * definition classes. */ /** * The definition of a dialog window. * <div class="notapi"> * This class is not really part of the API. It just illustrates the properties * that developers can use to define and create dialogs. * </div> * @name CKEDITOR.dialog.definition * @constructor * @example * // There is no constructor for this class, the user just has to define an * // object with the appropriate properties. * * CKEDITOR.dialog.add( 'testOnly', function( editor ) * { * return { * title : 'Test Dialog', * resizable : CKEDITOR.DIALOG_RESIZE_BOTH, * minWidth : 500, * minHeight : 400, * contents : [ * { * id : 'tab1', * label : 'First Tab', * title : 'First Tab Title', * accessKey : 'Q', * elements : [ * { * type : 'text', * label : 'Test Text 1', * id : 'testText1', * 'default' : 'hello world!' * } * ] * } * ] * }; * }); */ /** * The dialog title, displayed in the dialog's header. Required. * @name CKEDITOR.dialog.definition.prototype.title * @field * @type String * @example */ /** * How the dialog can be resized, must be one of the four contents defined below. * <br /><br /> * <strong>CKEDITOR.DIALOG_RESIZE_NONE</strong><br /> * <strong>CKEDITOR.DIALOG_RESIZE_WIDTH</strong><br /> * <strong>CKEDITOR.DIALOG_RESIZE_HEIGHT</strong><br /> * <strong>CKEDITOR.DIALOG_RESIZE_BOTH</strong><br /> * @name CKEDITOR.dialog.definition.prototype.resizable * @field * @type Number * @default CKEDITOR.DIALOG_RESIZE_NONE * @example */ /** * The minimum width of the dialog, in pixels. * @name CKEDITOR.dialog.definition.prototype.minWidth * @field * @type Number * @default 600 * @example */ /** * The minimum height of the dialog, in pixels. * @name CKEDITOR.dialog.definition.prototype.minHeight * @field * @type Number * @default 400 * @example */ /** * The initial width of the dialog, in pixels. * @name CKEDITOR.dialog.definition.prototype.width * @field * @type Number * @default @CKEDITOR.dialog.definition.prototype.minWidth * @since 3.5.3 * @example */ /** * The initial height of the dialog, in pixels. * @name CKEDITOR.dialog.definition.prototype.height * @field * @type Number * @default @CKEDITOR.dialog.definition.prototype.minHeight * @since 3.5.3 * @example */ /** * The buttons in the dialog, defined as an array of * {@link CKEDITOR.dialog.definition.button} objects. * @name CKEDITOR.dialog.definition.prototype.buttons * @field * @type Array * @default [ CKEDITOR.dialog.okButton, CKEDITOR.dialog.cancelButton ] * @example */ /** * The contents in the dialog, defined as an array of * {@link CKEDITOR.dialog.definition.content} objects. Required. * @name CKEDITOR.dialog.definition.prototype.contents * @field * @type Array * @example */ /** * The function to execute when OK is pressed. * @name CKEDITOR.dialog.definition.prototype.onOk * @field * @type Function * @example */ /** * The function to execute when Cancel is pressed. * @name CKEDITOR.dialog.definition.prototype.onCancel * @field * @type Function * @example */ /** * The function to execute when the dialog is displayed for the first time. * @name CKEDITOR.dialog.definition.prototype.onLoad * @field * @type Function * @example */ /** * The function to execute when the dialog is loaded (executed every time the dialog is opened). * @name CKEDITOR.dialog.definition.prototype.onShow * @field * @type Function * @example */ /** * <div class="notapi">This class is not really part of the API. It just illustrates the properties * that developers can use to define and create dialog content pages.</div> * @name CKEDITOR.dialog.definition.content * @constructor * @example * // There is no constructor for this class, the user just has to define an * // object with the appropriate properties. */ /** * The id of the content page. * @name CKEDITOR.dialog.definition.content.prototype.id * @field * @type String * @example */ /** * The tab label of the content page. * @name CKEDITOR.dialog.definition.content.prototype.label * @field * @type String * @example */ /** * The popup message of the tab label. * @name CKEDITOR.dialog.definition.content.prototype.title * @field * @type String * @example */ /** * The CTRL hotkey for switching to the tab. * @name CKEDITOR.dialog.definition.content.prototype.accessKey * @field * @type String * @example * contentDefinition.accessKey = 'Q'; // Switch to this page when CTRL-Q is pressed. */ /** * The UI elements contained in this content page, defined as an array of * {@link CKEDITOR.dialog.definition.uiElement} objects. * @name CKEDITOR.dialog.definition.content.prototype.elements * @field * @type Array * @example */ /** * The definition of user interface element (textarea, radio etc). * <div class="notapi">This class is not really part of the API. It just illustrates the properties * that developers can use to define and create dialog UI elements.</div> * @name CKEDITOR.dialog.definition.uiElement * @constructor * @see CKEDITOR.ui.dialog.uiElement * @example * // There is no constructor for this class, the user just has to define an * // object with the appropriate properties. */ /** * The id of the UI element. * @name CKEDITOR.dialog.definition.uiElement.prototype.id * @field * @type String * @example */ /** * The type of the UI element. Required. * @name CKEDITOR.dialog.definition.uiElement.prototype.type * @field * @type String * @example */ /** * The popup label of the UI element. * @name CKEDITOR.dialog.definition.uiElement.prototype.title * @field * @type String * @example */ /** * CSS class names to append to the UI element. * @name CKEDITOR.dialog.definition.uiElement.prototype.className * @field * @type String * @example */ /** * Inline CSS classes to append to the UI element. * @name CKEDITOR.dialog.definition.uiElement.prototype.style * @field * @type String * @example */ /** * Horizontal alignment (in container) of the UI element. * @name CKEDITOR.dialog.definition.uiElement.prototype.align * @field * @type String * @example */ /** * Function to execute the first time the UI element is displayed. * @name CKEDITOR.dialog.definition.uiElement.prototype.onLoad * @field * @type Function * @example */ /** * Function to execute whenever the UI element's parent dialog is displayed. * @name CKEDITOR.dialog.definition.uiElement.prototype.onShow * @field * @type Function * @example */ /** * Function to execute whenever the UI element's parent dialog is closed. * @name CKEDITOR.dialog.definition.uiElement.prototype.onHide * @field * @type Function * @example */ /** * Function to execute whenever the UI element's parent dialog's {@link CKEDITOR.dialog.definition.setupContent} method is executed. * It usually takes care of the respective UI element as a standalone element. * @name CKEDITOR.dialog.definition.uiElement.prototype.setup * @field * @type Function * @example */ /** * Function to execute whenever the UI element's parent dialog's {@link CKEDITOR.dialog.definition.commitContent} method is executed. * It usually takes care of the respective UI element as a standalone element. * @name CKEDITOR.dialog.definition.uiElement.prototype.commit * @field * @type Function * @example */ // ----- hbox ----- /** * Horizontal layout box for dialog UI elements, auto-expends to available width of container. * <div class="notapi"> * This class is not really part of the API. It just illustrates the properties * that developers can use to define and create horizontal layouts. * <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.hbox} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}. * </div> * @name CKEDITOR.dialog.definition.hbox * @extends CKEDITOR.dialog.definition.uiElement * @constructor * @example * // There is no constructor for this class, the user just has to define an * // object with the appropriate properties. * * // Example: * { * <b>type : 'hbox',</b> * widths : [ '25%', '25%', '50%' ], * children : * [ * { * type : 'text', * id : 'id1', * width : '40px', * }, * { * type : 'text', * id : 'id2', * width : '40px', * }, * { * type : 'text', * id : 'id3' * } * ] * } */ /** * Array of {@link CKEDITOR.ui.dialog.uiElement} objects inside this container. * @name CKEDITOR.dialog.definition.hbox.prototype.children * @field * @type Array * @example */ /** * (Optional) The widths of child cells. * @name CKEDITOR.dialog.definition.hbox.prototype.widths * @field * @type Array * @example */ /** * (Optional) The height of the layout. * @name CKEDITOR.dialog.definition.hbox.prototype.height * @field * @type Number * @example */ /** * The CSS styles to apply to this element. * @name CKEDITOR.dialog.definition.hbox.prototype.styles * @field * @type String * @example */ /** * (Optional) The padding width inside child cells. Example: 0, 1. * @name CKEDITOR.dialog.definition.hbox.prototype.padding * @field * @type Number * @example */ /** * (Optional) The alignment of the whole layout. Example: center, top. * @name CKEDITOR.dialog.definition.hbox.prototype.align * @field * @type String * @example */ // ----- vbox ----- /** * Vertical layout box for dialog UI elements. * <div class="notapi"> * This class is not really part of the API. It just illustrates the properties * that developers can use to define and create vertical layouts. * <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.vbox} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}. * </div> * <style type="text/css">.details .detailList {display:none;} </style> * @name CKEDITOR.dialog.definition.vbox * @extends CKEDITOR.dialog.definition.uiElement * @constructor * @example * // There is no constructor for this class, the user just has to define an * // object with the appropriate properties. * * // Example: * { * <b>type : 'vbox',</b> * align : 'right', * width : '200px', * children : * [ * { * type : 'text', * id : 'age', * label : 'Age' * }, * { * type : 'text', * id : 'sex', * label : 'Sex' * }, * { * type : 'text', * id : 'nationality', * label : 'Nationality' * } * ] * } */ /** * Array of {@link CKEDITOR.ui.dialog.uiElement} objects inside this container. * @name CKEDITOR.dialog.definition.vbox.prototype.children * @field * @type Array * @example */ /** * (Optional) The width of the layout. * @name CKEDITOR.dialog.definition.vbox.prototype.width * @field * @type Array * @example */ /** * (Optional) The heights of individual cells. * @name CKEDITOR.dialog.definition.vbox.prototype.heights * @field * @type Number * @example */ /** * The CSS styles to apply to this element. * @name CKEDITOR.dialog.definition.vbox.prototype.styles * @field * @type String * @example */ /** * (Optional) The padding width inside child cells. Example: 0, 1. * @name CKEDITOR.dialog.definition.vbox.prototype.padding * @field * @type Number * @example */ /** * (Optional) The alignment of the whole layout. Example: center, top. * @name CKEDITOR.dialog.definition.vbox.prototype.align * @field * @type String * @example */ /** * (Optional) Whether the layout should expand vertically to fill its container. * @name CKEDITOR.dialog.definition.vbox.prototype.expand * @field * @type Boolean * @example */ // ----- labeled element ------ /** * The definition of labeled user interface element (textarea, textInput etc). * <div class="notapi">This class is not really part of the API. It just illustrates the properties * that developers can use to define and create dialog UI elements.</div> * @name CKEDITOR.dialog.definition.labeledElement * @extends CKEDITOR.dialog.definition.uiElement * @constructor * @see CKEDITOR.ui.dialog.labeledElement * @example * // There is no constructor for this class, the user just has to define an * // object with the appropriate properties. */ /** * The label of the UI element. * @name CKEDITOR.dialog.definition.labeledElement.prototype.label * @type String * @field * @example * { * type : 'text', * label : 'My Label ' * } */ /** * (Optional) Specify the layout of the label. Set to 'horizontal' for horizontal layout. * The default layout is vertical. * @name CKEDITOR.dialog.definition.labeledElement.prototype.labelLayout * @type String * @field * @example * { * type : 'text', * label : 'My Label ', * <strong> labelLayout : 'horizontal',</strong> * } */ /** * (Optional) Applies only to horizontal layouts: a two elements array of lengths to specify the widths of the * label and the content element. See also {@link CKEDITOR.dialog.definition.labeledElement#labelLayout}. * @name CKEDITOR.dialog.definition.labeledElement.prototype.widths * @type Array * @field * @example * { * type : 'text', * label : 'My Label ', * labelLayout : 'horizontal', * <strong> widths : [100, 200],</strong> * } */ /** * Specify the inline style of the uiElement label. * @name CKEDITOR.dialog.definition.labeledElement.prototype.labelStyle * @type String * @field * @example * { * type : 'text', * label : 'My Label ', * <strong> labelStyle : 'color: red',</strong> * } */ /** * Specify the inline style of the input element. * @name CKEDITOR.dialog.definition.labeledElement.prototype.inputStyle * @type String * @since 3.6.1 * @field * @example * { * type : 'text', * label : 'My Label ', * <strong> inputStyle : 'text-align:center',</strong> * } */ /** * Specify the inline style of the input element container . * @name CKEDITOR.dialog.definition.labeledElement.prototype.controlStyle * @type String * @since 3.6.1 * @field * @example * { * type : 'text', * label : 'My Label ', * <strong> controlStyle : 'width:3em',</strong> * } */ // ----- button ------ /** * The definition of a button. * <div class="notapi"> * This class is not really part of the API. It just illustrates the properties * that developers can use to define and create buttons. * <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.button} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}. * </div> * For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}. * @name CKEDITOR.dialog.definition.button * @extends CKEDITOR.dialog.definition.uiElement * @constructor * @example * // There is no constructor for this class, the user just has to define an * // object with the appropriate properties. * * // Example: * { * <b>type : 'button',</b> * id : 'buttonId', * label : 'Click me', * title : 'My title', * onClick : function() { * // this = CKEDITOR.ui.dialog.button * alert( 'Clicked: ' + this.id ); * } * } */ /** * Whether the button is disabled. * @name CKEDITOR.dialog.definition.button.prototype.disabled * @type Boolean * @field * @example */ /** * The label of the UI element. * @name CKEDITOR.dialog.definition.button.prototype.label * @type String * @field * @example */ // ----- checkbox ------ /** * The definition of a checkbox element. * <div class="notapi"> * This class is not really part of the API. It just illustrates the properties * that developers can use to define and create groups of checkbox buttons. * <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.checkbox} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}. * </div> * For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}. * @name CKEDITOR.dialog.definition.checkbox * @extends CKEDITOR.dialog.definition.uiElement * @constructor * @example * // There is no constructor for this class, the user just has to define an * // object with the appropriate properties. * * // Example: * { * <b>type : 'checkbox',</b> * id : 'agree', * label : 'I agree', * 'default' : 'checked', * onClick : function() { * // this = CKEDITOR.ui.dialog.checkbox * alert( 'Checked: ' + this.getValue() ); * } * } */ /** * (Optional) The validation function. * @name CKEDITOR.dialog.definition.checkbox.prototype.validate * @field * @type Function * @example */ /** * The label of the UI element. * @name CKEDITOR.dialog.definition.checkbox.prototype.label * @type String * @field * @example */ /** * The default state. * @name CKEDITOR.dialog.definition.checkbox.prototype.default * @type String * @field * @default * '' (unchecked) * @example */ // ----- file ----- /** * The definition of a file upload input. * <div class="notapi"> * This class is not really part of the API. It just illustrates the properties * that developers can use to define and create file upload elements. * <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.file} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}. * </div> * For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}. * @name CKEDITOR.dialog.definition.file * @extends CKEDITOR.dialog.definition.labeledElement * @constructor * @example * // There is no constructor for this class, the user just has to define an * // object with the appropriate properties. * * // Example: * { * <b>type : 'file'</b>, * id : 'upload', * label : 'Select file from your computer', * size : 38 * }, * { * type : 'fileButton', * id : 'fileId', * label : 'Upload file', * 'for' : [ 'tab1', 'upload' ] * filebrowser : { * onSelect : function( fileUrl, data ) { * alert( 'Successfully uploaded: ' + fileUrl ); * } * } * } */ /** * (Optional) The validation function. * @name CKEDITOR.dialog.definition.file.prototype.validate * @field * @type Function * @example */ /** * (Optional) The action attribute of the form element associated with this file upload input. * If empty, CKEditor will use path to server connector for currently opened folder. * @name CKEDITOR.dialog.definition.file.prototype.action * @type String * @field * @example */ /** * The size of the UI element. * @name CKEDITOR.dialog.definition.file.prototype.size * @type Number * @field * @example */ // ----- fileButton ----- /** * The definition of a button for submitting the file in a file upload input. * <div class="notapi"> * This class is not really part of the API. It just illustrates the properties * that developers can use to define and create a button for submitting the file in a file upload input. * <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.fileButton} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}. * </div> * For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}. * @name CKEDITOR.dialog.definition.fileButton * @extends CKEDITOR.dialog.definition.uiElement * @constructor * @example * // There is no constructor for this class, the user just has to define an * // object with the appropriate properties. * * // Example: * { * type : 'file', * id : 'upload', * label : 'Select file from your computer', * size : 38 * }, * { * <b>type : 'fileButton'</b>, * id : 'fileId', * label : 'Upload file', * 'for' : [ 'tab1', 'upload' ] * filebrowser : { * onSelect : function( fileUrl, data ) { * alert( 'Successfully uploaded: ' + fileUrl ); * } * } * } */ /** * (Optional) The validation function. * @name CKEDITOR.dialog.definition.fileButton.prototype.validate * @field * @type Function * @example */ /** * The label of the UI element. * @name CKEDITOR.dialog.definition.fileButton.prototype.label * @type String * @field * @example */ /** * The instruction for CKEditor how to deal with file upload. * By default, the file and fileButton elements will not work "as expected" if this attribute is not set. * @name CKEDITOR.dialog.definition.fileButton.prototype.filebrowser * @type String|Object * @field * @example * // Update field with id 'txtUrl' in the 'tab1' tab when file is uploaded. * filebrowser : 'tab1:txtUrl' * * // Call custom onSelect function when file is successfully uploaded. * filebrowser : { * onSelect : function( fileUrl, data ) { * alert( 'Successfully uploaded: ' + fileUrl ); * } * } */ /** * An array that contains pageId and elementId of the file upload input element for which this button is created. * @name CKEDITOR.dialog.definition.fileButton.prototype.for * @type String * @field * @example * [ pageId, elementId ] */ // ----- html ----- /** * The definition of a raw HTML element. * <div class="notapi"> * This class is not really part of the API. It just illustrates the properties * that developers can use to define and create elements made from raw HTML code. * <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.html} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}. * </div> * For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}.<br /> * To access HTML elements use {@link CKEDITOR.dom.document#getById} * @name CKEDITOR.dialog.definition.html * @extends CKEDITOR.dialog.definition.uiElement * @constructor * @example * // There is no constructor for this class, the user just has to define an * // object with the appropriate properties. * * // Example 1: * { * <b>type : 'html',</b> * html : '&lt;h3>This is some sample HTML content.&lt;/h3>' * } * @example * // Example 2: * // Complete sample with document.getById() call when the "Ok" button is clicked. * var dialogDefinition = * { * title : 'Sample dialog', * minWidth : 300, * minHeight : 200, * onOk : function() { * // "this" is now a CKEDITOR.dialog object. * var document = this.getElement().getDocument(); * // document = CKEDITOR.dom.document * var element = <b>document.getById( 'myDiv' );</b> * if ( element ) * alert( element.getHtml() ); * }, * contents : [ * { * id : 'tab1', * label : '', * title : '', * elements : * [ * { * <b>type : 'html',</b> * html : '<b>&lt;div id="myDiv">Sample &lt;b>text&lt;/b>.&lt;/div></b>&lt;div id="otherId">Another div.&lt;/div>' * }, * ] * } * ], * buttons : [ CKEDITOR.dialog.cancelButton, CKEDITOR.dialog.okButton ] * }; */ /** * (Required) HTML code of this element. * @name CKEDITOR.dialog.definition.html.prototype.html * @type String * @field * @example */ // ----- radio ------ /** * The definition of a radio group. * <div class="notapi"> * This class is not really part of the API. It just illustrates the properties * that developers can use to define and create groups of radio buttons. * <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.radio} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}. * </div> * For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}. * @name CKEDITOR.dialog.definition.radio * @extends CKEDITOR.dialog.definition.labeledElement * @constructor * @example * // There is no constructor for this class, the user just has to define an * // object with the appropriate properties. * * // Example: * { * <b>type : 'radio',</b> * id : 'country', * label : 'Which country is bigger', * items : [ [ 'France', 'FR' ], [ 'Germany', 'DE' ] ] , * style : 'color:green', * 'default' : 'DE', * onClick : function() { * // this = CKEDITOR.ui.dialog.radio * alert( 'Current value: ' + this.getValue() ); * } * } */ /** * The default value. * @name CKEDITOR.dialog.definition.radio.prototype.default * @type String * @field * @example */ /** * (Optional) The validation function. * @name CKEDITOR.dialog.definition.radio.prototype.validate * @field * @type Function * @example */ /** * An array of options. Each option is a 1- or 2-item array of format [ 'Description', 'Value' ]. If 'Value' is missing, then the value would be assumed to be the same as the description. * @name CKEDITOR.dialog.definition.radio.prototype.items * @field * @type Array * @example */ // ----- selectElement ------ /** * The definition of a select element. * <div class="notapi"> * This class is not really part of the API. It just illustrates the properties * that developers can use to define and create select elements. * <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.select} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}. * </div> * For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}. * @name CKEDITOR.dialog.definition.select * @extends CKEDITOR.dialog.definition.labeledElement * @constructor * @example * // There is no constructor for this class, the user just has to define an * // object with the appropriate properties. * * // Example: * { * <b>type : 'select',</b> * id : 'sport', * label : 'Select your favourite sport', * items : [ [ 'Basketball' ], [ 'Baseball' ], [ 'Hockey' ], [ 'Football' ] ], * 'default' : 'Football', * onChange : function( api ) { * // this = CKEDITOR.ui.dialog.select * alert( 'Current value: ' + this.getValue() ); * } * } */ /** * The default value. * @name CKEDITOR.dialog.definition.select.prototype.default * @type String * @field * @example */ /** * (Optional) The validation function. * @name CKEDITOR.dialog.definition.select.prototype.validate * @field * @type Function * @example */ /** * An array of options. Each option is a 1- or 2-item array of format [ 'Description', 'Value' ]. If 'Value' is missing, then the value would be assumed to be the same as the description. * @name CKEDITOR.dialog.definition.select.prototype.items * @field * @type Array * @example */ /** * (Optional) Set this to true if you'd like to have a multiple-choice select box. * @name CKEDITOR.dialog.definition.select.prototype.multiple * @type Boolean * @field * @example * @default false */ /** * (Optional) The number of items to display in the select box. * @name CKEDITOR.dialog.definition.select.prototype.size * @type Number * @field * @example */ // ----- textInput ----- /** * The definition of a text field (single line). * <div class="notapi"> * This class is not really part of the API. It just illustrates the properties * that developers can use to define and create text fields. * <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.textInput} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}. * </div> * For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}. * @name CKEDITOR.dialog.definition.textInput * @extends CKEDITOR.dialog.definition.labeledElement * @constructor * @example * // There is no constructor for this class, the user just has to define an * // object with the appropriate properties. * * { * <b>type : 'text',</b> * id : 'name', * label : 'Your name', * 'default' : '', * validate : function() { * if ( !this.getValue() ) * { * api.openMsgDialog( '', 'Name cannot be empty.' ); * return false; * } * } * } */ /** * The default value. * @name CKEDITOR.dialog.definition.textInput.prototype.default * @type String * @field * @example */ /** * (Optional) The maximum length. * @name CKEDITOR.dialog.definition.textInput.prototype.maxLength * @type Number * @field * @example */ /** * (Optional) The size of the input field. * @name CKEDITOR.dialog.definition.textInput.prototype.size * @type Number * @field * @example */ /** * (Optional) The validation function. * @name CKEDITOR.dialog.definition.textInput.prototype.validate * @field * @type Function * @example */ // ----- textarea ------ /** * The definition of a text field (multiple lines). * <div class="notapi"> * This class is not really part of the API. It just illustrates the properties * that developers can use to define and create textarea. * <br /><br />Once the dialog is opened, the created element becomes a {@link CKEDITOR.ui.dialog.textarea} object and can be accessed with {@link CKEDITOR.dialog#getContentElement}. * </div> * For a complete example of dialog definition, please check {@link CKEDITOR.dialog.add}. * @name CKEDITOR.dialog.definition.textarea * @extends CKEDITOR.dialog.definition.labeledElement * @constructor * @example * // There is no constructor for this class, the user just has to define an * // object with the appropriate properties. * * // Example: * { * <b>type : 'textarea',</b> * id : 'message', * label : 'Your comment', * 'default' : '', * validate : function() { * if ( this.getValue().length < 5 ) * { * api.openMsgDialog( 'The comment is too short.' ); * return false; * } * } * } */ /** * The number of rows. * @name CKEDITOR.dialog.definition.textarea.prototype.rows * @type Number * @field * @example */ /** * The number of columns. * @name CKEDITOR.dialog.definition.textarea.prototype.cols * @type Number * @field * @example */ /** * (Optional) The validation function. * @name CKEDITOR.dialog.definition.textarea.prototype.validate * @field * @type Function * @example */ /** * The default value. * @name CKEDITOR.dialog.definition.textarea.prototype.default * @type String * @field * @example */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview The floating dialog plugin. */ /** * No resize for this dialog. * @constant */ CKEDITOR.DIALOG_RESIZE_NONE = 0; /** * Only allow horizontal resizing for this dialog, disable vertical resizing. * @constant */ CKEDITOR.DIALOG_RESIZE_WIDTH = 1; /** * Only allow vertical resizing for this dialog, disable horizontal resizing. * @constant */ CKEDITOR.DIALOG_RESIZE_HEIGHT = 2; /* * Allow the dialog to be resized in both directions. * @constant */ CKEDITOR.DIALOG_RESIZE_BOTH = 3; (function() { var cssLength = CKEDITOR.tools.cssLength; function isTabVisible( tabId ) { return !!this._.tabs[ tabId ][ 0 ].$.offsetHeight; } function getPreviousVisibleTab() { var tabId = this._.currentTabId, length = this._.tabIdList.length, tabIndex = CKEDITOR.tools.indexOf( this._.tabIdList, tabId ) + length; for ( var i = tabIndex - 1 ; i > tabIndex - length ; i-- ) { if ( isTabVisible.call( this, this._.tabIdList[ i % length ] ) ) return this._.tabIdList[ i % length ]; } return null; } function getNextVisibleTab() { var tabId = this._.currentTabId, length = this._.tabIdList.length, tabIndex = CKEDITOR.tools.indexOf( this._.tabIdList, tabId ); for ( var i = tabIndex + 1 ; i < tabIndex + length ; i++ ) { if ( isTabVisible.call( this, this._.tabIdList[ i % length ] ) ) return this._.tabIdList[ i % length ]; } return null; } function clearOrRecoverTextInputValue( container, isRecover ) { var inputs = container.$.getElementsByTagName( 'input' ); for ( var i = 0, length = inputs.length; i < length ; i++ ) { var item = new CKEDITOR.dom.element( inputs[ i ] ); if ( item.getAttribute( 'type' ).toLowerCase() == 'text' ) { if ( isRecover ) { item.setAttribute( 'value', item.getCustomData( 'fake_value' ) || '' ); item.removeCustomData( 'fake_value' ); } else { item.setCustomData( 'fake_value', item.getAttribute( 'value' ) ); item.setAttribute( 'value', '' ); } } } } // Handle dialog element validation state UI changes. function handleFieldValidated( isValid, msg ) { var input = this.getInputElement(); if ( input ) { isValid ? input.removeAttribute( 'aria-invalid' ) : input.setAttribute( 'aria-invalid', true ); } if ( !isValid ) { if ( this.select ) this.select(); else this.focus(); } msg && alert( msg ); this.fire( 'validated', { valid : isValid, msg : msg } ); } function resetField() { var input = this.getInputElement(); input && input.removeAttribute( 'aria-invalid' ); } /** * This is the base class for runtime dialog objects. An instance of this * class represents a single named dialog for a single editor instance. * @param {Object} editor The editor which created the dialog. * @param {String} dialogName The dialog's registered name. * @constructor * @example * var dialogObj = new CKEDITOR.dialog( editor, 'smiley' ); */ CKEDITOR.dialog = function( editor, dialogName ) { // Load the dialog definition. var definition = CKEDITOR.dialog._.dialogDefinitions[ dialogName ], defaultDefinition = CKEDITOR.tools.clone( defaultDialogDefinition ), buttonsOrder = editor.config.dialog_buttonsOrder || 'OS', dir = editor.lang.dir; if ( ( buttonsOrder == 'OS' && CKEDITOR.env.mac ) || // The buttons in MacOS Apps are in reverse order (#4750) ( buttonsOrder == 'rtl' && dir == 'ltr' ) || ( buttonsOrder == 'ltr' && dir == 'rtl' ) ) defaultDefinition.buttons.reverse(); // Completes the definition with the default values. definition = CKEDITOR.tools.extend( definition( editor ), defaultDefinition ); // Clone a functionally independent copy for this dialog. definition = CKEDITOR.tools.clone( definition ); // Create a complex definition object, extending it with the API // functions. definition = new definitionObject( this, definition ); var doc = CKEDITOR.document; var themeBuilt = editor.theme.buildDialog( editor ); // Initialize some basic parameters. this._ = { editor : editor, element : themeBuilt.element, name : dialogName, contentSize : { width : 0, height : 0 }, size : { width : 0, height : 0 }, contents : {}, buttons : {}, accessKeyMap : {}, // Initialize the tab and page map. tabs : {}, tabIdList : [], currentTabId : null, currentTabIndex : null, pageCount : 0, lastTab : null, tabBarMode : false, // Initialize the tab order array for input widgets. focusList : [], currentFocusIndex : 0, hasFocus : false }; this.parts = themeBuilt.parts; CKEDITOR.tools.setTimeout( function() { editor.fire( 'ariaWidget', this.parts.contents ); }, 0, this ); // Set the startup styles for the dialog, avoiding it enlarging the // page size on the dialog creation. var startStyles = { position : CKEDITOR.env.ie6Compat ? 'absolute' : 'fixed', top : 0, visibility : 'hidden' }; startStyles[ dir == 'rtl' ? 'right' : 'left' ] = 0; this.parts.dialog.setStyles( startStyles ); // Call the CKEDITOR.event constructor to initialize this instance. CKEDITOR.event.call( this ); // Fire the "dialogDefinition" event, making it possible to customize // the dialog definition. this.definition = definition = CKEDITOR.fire( 'dialogDefinition', { name : dialogName, definition : definition } , editor ).definition; var tabsToRemove = {}; // Cache tabs that should be removed. if ( !( 'removeDialogTabs' in editor._ ) && editor.config.removeDialogTabs ) { var removeContents = editor.config.removeDialogTabs.split( ';' ); for ( i = 0; i < removeContents.length; i++ ) { var parts = removeContents[ i ].split( ':' ); if ( parts.length == 2 ) { var removeDialogName = parts[ 0 ]; if ( !tabsToRemove[ removeDialogName ] ) tabsToRemove[ removeDialogName ] = []; tabsToRemove[ removeDialogName ].push( parts[ 1 ] ); } } editor._.removeDialogTabs = tabsToRemove; } // Remove tabs of this dialog. if ( editor._.removeDialogTabs && ( tabsToRemove = editor._.removeDialogTabs[ dialogName ] ) ) { for ( i = 0; i < tabsToRemove.length; i++ ) definition.removeContents( tabsToRemove[ i ] ); } // Initialize load, show, hide, ok and cancel events. if ( definition.onLoad ) this.on( 'load', definition.onLoad ); if ( definition.onShow ) this.on( 'show', definition.onShow ); if ( definition.onHide ) this.on( 'hide', definition.onHide ); if ( definition.onOk ) { this.on( 'ok', function( evt ) { // Dialog confirm might probably introduce content changes (#5415). editor.fire( 'saveSnapshot' ); setTimeout( function () { editor.fire( 'saveSnapshot' ); }, 0 ); if ( definition.onOk.call( this, evt ) === false ) evt.data.hide = false; }); } if ( definition.onCancel ) { this.on( 'cancel', function( evt ) { if ( definition.onCancel.call( this, evt ) === false ) evt.data.hide = false; }); } var me = this; // Iterates over all items inside all content in the dialog, calling a // function for each of them. var iterContents = function( func ) { var contents = me._.contents, stop = false; for ( var i in contents ) { for ( var j in contents[i] ) { stop = func.call( this, contents[i][j] ); if ( stop ) return; } } }; this.on( 'ok', function( evt ) { iterContents( function( item ) { if ( item.validate ) { var retval = item.validate( this ), invalid = typeof ( retval ) == 'string' || retval === false; if ( invalid ) { evt.data.hide = false; evt.stop(); } handleFieldValidated.call( item, !invalid, typeof retval == 'string' ? retval : undefined ); return invalid; } }); }, this, null, 0 ); this.on( 'cancel', function( evt ) { iterContents( function( item ) { if ( item.isChanged() ) { if ( !confirm( editor.lang.common.confirmCancel ) ) evt.data.hide = false; return true; } }); }, this, null, 0 ); this.parts.close.on( 'click', function( evt ) { if ( this.fire( 'cancel', { hide : true } ).hide !== false ) this.hide(); evt.data.preventDefault(); }, this ); // Sort focus list according to tab order definitions. function setupFocus() { var focusList = me._.focusList; focusList.sort( function( a, b ) { // Mimics browser tab order logics; if ( a.tabIndex != b.tabIndex ) return b.tabIndex - a.tabIndex; // Sort is not stable in some browsers, // fall-back the comparator to 'focusIndex'; else return a.focusIndex - b.focusIndex; }); var size = focusList.length; for ( var i = 0; i < size; i++ ) focusList[ i ].focusIndex = i; } function changeFocus( forward ) { var focusList = me._.focusList, offset = forward ? 1 : -1; if ( focusList.length < 1 ) return; var current = me._.currentFocusIndex; // Trigger the 'blur' event of any input element before anything, // since certain UI updates may depend on it. try { focusList[ current ].getInputElement().$.blur(); } catch( e ){} var startIndex = ( current + offset + focusList.length ) % focusList.length, currentIndex = startIndex; while ( !focusList[ currentIndex ].isFocusable() ) { currentIndex = ( currentIndex + offset + focusList.length ) % focusList.length; if ( currentIndex == startIndex ) break; } focusList[ currentIndex ].focus(); // Select whole field content. if ( focusList[ currentIndex ].type == 'text' ) focusList[ currentIndex ].select(); } this.changeFocus = changeFocus; var processed; function focusKeydownHandler( evt ) { // If I'm not the top dialog, ignore. if ( me != CKEDITOR.dialog._.currentTop ) return; var keystroke = evt.data.getKeystroke(), rtl = editor.lang.dir == 'rtl'; processed = 0; if ( keystroke == 9 || keystroke == CKEDITOR.SHIFT + 9 ) { var shiftPressed = ( keystroke == CKEDITOR.SHIFT + 9 ); // Handling Tab and Shift-Tab. if ( me._.tabBarMode ) { // Change tabs. var nextId = shiftPressed ? getPreviousVisibleTab.call( me ) : getNextVisibleTab.call( me ); me.selectPage( nextId ); me._.tabs[ nextId ][ 0 ].focus(); } else { // Change the focus of inputs. changeFocus( !shiftPressed ); } processed = 1; } else if ( keystroke == CKEDITOR.ALT + 121 && !me._.tabBarMode && me.getPageCount() > 1 ) { // Alt-F10 puts focus into the current tab item in the tab bar. me._.tabBarMode = true; me._.tabs[ me._.currentTabId ][ 0 ].focus(); processed = 1; } else if ( ( keystroke == 37 || keystroke == 39 ) && me._.tabBarMode ) { // Arrow keys - used for changing tabs. nextId = ( keystroke == ( rtl ? 39 : 37 ) ? getPreviousVisibleTab.call( me ) : getNextVisibleTab.call( me ) ); me.selectPage( nextId ); me._.tabs[ nextId ][ 0 ].focus(); processed = 1; } else if ( ( keystroke == 13 || keystroke == 32 ) && me._.tabBarMode ) { this.selectPage( this._.currentTabId ); this._.tabBarMode = false; this._.currentFocusIndex = -1; changeFocus( true ); processed = 1; } if ( processed ) { evt.stop(); evt.data.preventDefault(); } } function focusKeyPressHandler( evt ) { processed && evt.data.preventDefault(); } var dialogElement = this._.element; // Add the dialog keyboard handlers. this.on( 'show', function() { dialogElement.on( 'keydown', focusKeydownHandler, this, null, 0 ); // Some browsers instead, don't cancel key events in the keydown, but in the // keypress. So we must do a longer trip in those cases. (#4531) if ( CKEDITOR.env.opera || ( CKEDITOR.env.gecko && CKEDITOR.env.mac ) ) dialogElement.on( 'keypress', focusKeyPressHandler, this ); } ); this.on( 'hide', function() { dialogElement.removeListener( 'keydown', focusKeydownHandler ); if ( CKEDITOR.env.opera || ( CKEDITOR.env.gecko && CKEDITOR.env.mac ) ) dialogElement.removeListener( 'keypress', focusKeyPressHandler ); // Reset fields state when closing dialog. iterContents( function( item ) { resetField.apply( item ); } ); } ); this.on( 'iframeAdded', function( evt ) { var doc = new CKEDITOR.dom.document( evt.data.iframe.$.contentWindow.document ); doc.on( 'keydown', focusKeydownHandler, this, null, 0 ); } ); // Auto-focus logic in dialog. this.on( 'show', function() { // Setup tabIndex on showing the dialog instead of on loading // to allow dynamic tab order happen in dialog definition. setupFocus(); if ( editor.config.dialog_startupFocusTab && me._.pageCount > 1 ) { me._.tabBarMode = true; me._.tabs[ me._.currentTabId ][ 0 ].focus(); } else if ( !this._.hasFocus ) { this._.currentFocusIndex = -1; // Decide where to put the initial focus. if ( definition.onFocus ) { var initialFocus = definition.onFocus.call( this ); // Focus the field that the user specified. initialFocus && initialFocus.focus(); } // Focus the first field in layout order. else changeFocus( true ); /* * IE BUG: If the initial focus went into a non-text element (e.g. button), * then IE would still leave the caret inside the editing area. */ if ( this._.editor.mode == 'wysiwyg' && CKEDITOR.env.ie ) { var $selection = editor.document.$.selection, $range = $selection.createRange(); if ( $range ) { if ( $range.parentElement && $range.parentElement().ownerDocument == editor.document.$ || $range.item && $range.item( 0 ).ownerDocument == editor.document.$ ) { var $myRange = document.body.createTextRange(); $myRange.moveToElementText( this.getElement().getFirst().$ ); $myRange.collapse( true ); $myRange.select(); } } } } }, this, null, 0xffffffff ); // IE6 BUG: Text fields and text areas are only half-rendered the first time the dialog appears in IE6 (#2661). // This is still needed after [2708] and [2709] because text fields in hidden TR tags are still broken. if ( CKEDITOR.env.ie6Compat ) { this.on( 'load', function( evt ) { var outer = this.getElement(), inner = outer.getFirst(); inner.remove(); inner.appendTo( outer ); }, this ); } initDragAndDrop( this ); initResizeHandles( this ); // Insert the title. ( new CKEDITOR.dom.text( definition.title, CKEDITOR.document ) ).appendTo( this.parts.title ); // Insert the tabs and contents. for ( var i = 0 ; i < definition.contents.length ; i++ ) { var page = definition.contents[i]; page && this.addPage( page ); } this.parts[ 'tabs' ].on( 'click', function( evt ) { var target = evt.data.getTarget(); // If we aren't inside a tab, bail out. if ( target.hasClass( 'cke_dialog_tab' ) ) { // Get the ID of the tab, without the 'cke_' prefix and the unique number suffix. var id = target.$.id; this.selectPage( id.substring( 4, id.lastIndexOf( '_' ) ) ); if ( this._.tabBarMode ) { this._.tabBarMode = false; this._.currentFocusIndex = -1; changeFocus( true ); } evt.data.preventDefault(); } }, this ); // Insert buttons. var buttonsHtml = [], buttons = CKEDITOR.dialog._.uiElementBuilders.hbox.build( this, { type : 'hbox', className : 'cke_dialog_footer_buttons', widths : [], children : definition.buttons }, buttonsHtml ).getChild(); this.parts.footer.setHtml( buttonsHtml.join( '' ) ); for ( i = 0 ; i < buttons.length ; i++ ) this._.buttons[ buttons[i].id ] = buttons[i]; }; // Focusable interface. Use it via dialog.addFocusable. function Focusable( dialog, element, index ) { this.element = element; this.focusIndex = index; // TODO: support tabIndex for focusables. this.tabIndex = 0; this.isFocusable = function() { return !element.getAttribute( 'disabled' ) && element.isVisible(); }; this.focus = function() { dialog._.currentFocusIndex = this.focusIndex; this.element.focus(); }; // Bind events element.on( 'keydown', function( e ) { if ( e.data.getKeystroke() in { 32:1, 13:1 } ) this.fire( 'click' ); } ); element.on( 'focus', function() { this.fire( 'mouseover' ); } ); element.on( 'blur', function() { this.fire( 'mouseout' ); } ); } CKEDITOR.dialog.prototype = { destroy : function() { this.hide(); this._.element.remove(); }, /** * Resizes the dialog. * @param {Number} width The width of the dialog in pixels. * @param {Number} height The height of the dialog in pixels. * @function * @example * dialogObj.resize( 800, 640 ); */ resize : (function() { return function( width, height ) { if ( this._.contentSize && this._.contentSize.width == width && this._.contentSize.height == height ) return; CKEDITOR.dialog.fire( 'resize', { dialog : this, skin : this._.editor.skinName, width : width, height : height }, this._.editor ); this.fire( 'resize', { skin : this._.editor.skinName, width : width, height : height }, this._.editor ); // Update dialog position when dimension get changed in RTL. if ( this._.editor.lang.dir == 'rtl' && this._.position ) this._.position.x = CKEDITOR.document.getWindow().getViewPaneSize().width - this._.contentSize.width - parseInt( this._.element.getFirst().getStyle( 'right' ), 10 ); this._.contentSize = { width : width, height : height }; }; })(), /** * Gets the current size of the dialog in pixels. * @returns {Object} An object with "width" and "height" properties. * @example * var width = dialogObj.getSize().width; */ getSize : function() { var element = this._.element.getFirst(); return { width : element.$.offsetWidth || 0, height : element.$.offsetHeight || 0}; }, /** * Moves the dialog to an (x, y) coordinate relative to the window. * @function * @param {Number} x The target x-coordinate. * @param {Number} y The target y-coordinate. * @param {Boolean} save Flag indicate whether the dialog position should be remembered on next open up. * @example * dialogObj.move( 10, 40 ); */ move : (function() { var isFixed; return function( x, y, save ) { // The dialog may be fixed positioned or absolute positioned. Ask the // browser what is the current situation first. var element = this._.element.getFirst(), rtl = this._.editor.lang.dir == 'rtl'; if ( isFixed === undefined ) isFixed = element.getComputedStyle( 'position' ) == 'fixed'; if ( isFixed && this._.position && this._.position.x == x && this._.position.y == y ) return; // Save the current position. this._.position = { x : x, y : y }; // If not fixed positioned, add scroll position to the coordinates. if ( !isFixed ) { var scrollPosition = CKEDITOR.document.getWindow().getScrollPosition(); x += scrollPosition.x; y += scrollPosition.y; } // Translate coordinate for RTL. if ( rtl ) { var dialogSize = this.getSize(), viewPaneSize = CKEDITOR.document.getWindow().getViewPaneSize(); x = viewPaneSize.width - dialogSize.width - x; } var styles = { 'top' : ( y > 0 ? y : 0 ) + 'px' }; styles[ rtl ? 'right' : 'left' ] = ( x > 0 ? x : 0 ) + 'px'; element.setStyles( styles ); save && ( this._.moved = 1 ); }; })(), /** * Gets the dialog's position in the window. * @returns {Object} An object with "x" and "y" properties. * @example * var dialogX = dialogObj.getPosition().x; */ getPosition : function(){ return CKEDITOR.tools.extend( {}, this._.position ); }, /** * Shows the dialog box. * @example * dialogObj.show(); */ show : function() { // Insert the dialog's element to the root document. var element = this._.element; var definition = this.definition; if ( !( element.getParent() && element.getParent().equals( CKEDITOR.document.getBody() ) ) ) element.appendTo( CKEDITOR.document.getBody() ); else element.setStyle( 'display', 'block' ); // FIREFOX BUG: Fix vanishing caret for Firefox 2 or Gecko 1.8. if ( CKEDITOR.env.gecko && CKEDITOR.env.version < 10900 ) { var dialogElement = this.parts.dialog; dialogElement.setStyle( 'position', 'absolute' ); setTimeout( function() { dialogElement.setStyle( 'position', 'fixed' ); }, 0 ); } // First, set the dialog to an appropriate size. this.resize( this._.contentSize && this._.contentSize.width || definition.width || definition.minWidth, this._.contentSize && this._.contentSize.height || definition.height || definition.minHeight ); // Reset all inputs back to their default value. this.reset(); // Select the first tab by default. this.selectPage( this.definition.contents[0].id ); // Set z-index. if ( CKEDITOR.dialog._.currentZIndex === null ) CKEDITOR.dialog._.currentZIndex = this._.editor.config.baseFloatZIndex; this._.element.getFirst().setStyle( 'z-index', CKEDITOR.dialog._.currentZIndex += 10 ); // Maintain the dialog ordering and dialog cover. // Also register key handlers if first dialog. if ( CKEDITOR.dialog._.currentTop === null ) { CKEDITOR.dialog._.currentTop = this; this._.parentDialog = null; showCover( this._.editor ); element.on( 'keydown', accessKeyDownHandler ); element.on( CKEDITOR.env.opera ? 'keypress' : 'keyup', accessKeyUpHandler ); // Prevent some keys from bubbling up. (#4269) for ( var event in { keyup :1, keydown :1, keypress :1 } ) element.on( event, preventKeyBubbling ); } else { this._.parentDialog = CKEDITOR.dialog._.currentTop; var parentElement = this._.parentDialog.getElement().getFirst(); parentElement.$.style.zIndex -= Math.floor( this._.editor.config.baseFloatZIndex / 2 ); CKEDITOR.dialog._.currentTop = this; } // Register the Esc hotkeys. registerAccessKey( this, this, '\x1b', null, function() { this.getButton( 'cancel' ) && this.getButton( 'cancel' ).click(); } ); // Reset the hasFocus state. this._.hasFocus = false; CKEDITOR.tools.setTimeout( function() { this.layout(); this.parts.dialog.setStyle( 'visibility', '' ); // Execute onLoad for the first show. this.fireOnce( 'load', {} ); CKEDITOR.ui.fire( 'ready', this ); this.fire( 'show', {} ); this._.editor.fire( 'dialogShow', this ); // Save the initial values of the dialog. this.foreach( function( contentObj ) { contentObj.setInitValue && contentObj.setInitValue(); } ); }, 100, this ); }, /** * Rearrange the dialog to its previous position or the middle of the window. * @since 3.5 */ layout : function() { var viewSize = CKEDITOR.document.getWindow().getViewPaneSize(), dialogSize = this.getSize(); this.move( this._.moved ? this._.position.x : ( viewSize.width - dialogSize.width ) / 2, this._.moved ? this._.position.y : ( viewSize.height - dialogSize.height ) / 2 ); }, /** * Executes a function for each UI element. * @param {Function} fn Function to execute for each UI element. * @returns {CKEDITOR.dialog} The current dialog object. */ foreach : function( fn ) { for ( var i in this._.contents ) { for ( var j in this._.contents[i] ) fn.call( this, this._.contents[i][j] ); } return this; }, /** * Resets all input values in the dialog. * @example * dialogObj.reset(); * @returns {CKEDITOR.dialog} The current dialog object. */ reset : (function() { var fn = function( widget ){ if ( widget.reset ) widget.reset( 1 ); }; return function(){ this.foreach( fn ); return this; }; })(), /** * Calls the {@link CKEDITOR.dialog.definition.uiElement#setup} method of each of the UI elements, with the arguments passed through it. * It is usually being called when the dialog is opened, to put the initial value inside the field. * @example * dialogObj.setupContent(); * @example * var timestamp = ( new Date() ).valueOf(); * dialogObj.setupContent( timestamp ); */ setupContent : function() { var args = arguments; this.foreach( function( widget ) { if ( widget.setup ) widget.setup.apply( widget, args ); }); }, /** * Calls the {@link CKEDITOR.dialog.definition.uiElement#commit} method of each of the UI elements, with the arguments passed through it. * It is usually being called when the user confirms the dialog, to process the values. * @example * dialogObj.commitContent(); * @example * var timestamp = ( new Date() ).valueOf(); * dialogObj.commitContent( timestamp ); */ commitContent : function() { var args = arguments; this.foreach( function( widget ) { // Make sure IE triggers "change" event on last focused input before closing the dialog. (#7915) if ( CKEDITOR.env.ie && this._.currentFocusIndex == widget.focusIndex ) widget.getInputElement().$.blur(); if ( widget.commit ) widget.commit.apply( widget, args ); }); }, /** * Hides the dialog box. * @example * dialogObj.hide(); */ hide : function() { if ( !this.parts.dialog.isVisible() ) return; this.fire( 'hide', {} ); this._.editor.fire( 'dialogHide', this ); var element = this._.element; element.setStyle( 'display', 'none' ); this.parts.dialog.setStyle( 'visibility', 'hidden' ); // Unregister all access keys associated with this dialog. unregisterAccessKey( this ); // Close any child(top) dialogs first. while( CKEDITOR.dialog._.currentTop != this ) CKEDITOR.dialog._.currentTop.hide(); // Maintain dialog ordering and remove cover if needed. if ( !this._.parentDialog ) hideCover(); else { var parentElement = this._.parentDialog.getElement().getFirst(); parentElement.setStyle( 'z-index', parseInt( parentElement.$.style.zIndex, 10 ) + Math.floor( this._.editor.config.baseFloatZIndex / 2 ) ); } CKEDITOR.dialog._.currentTop = this._.parentDialog; // Deduct or clear the z-index. if ( !this._.parentDialog ) { CKEDITOR.dialog._.currentZIndex = null; // Remove access key handlers. element.removeListener( 'keydown', accessKeyDownHandler ); element.removeListener( CKEDITOR.env.opera ? 'keypress' : 'keyup', accessKeyUpHandler ); // Remove bubbling-prevention handler. (#4269) for ( var event in { keyup :1, keydown :1, keypress :1 } ) element.removeListener( event, preventKeyBubbling ); var editor = this._.editor; editor.focus(); if ( editor.mode == 'wysiwyg' && CKEDITOR.env.ie ) { var selection = editor.getSelection(); selection && selection.unlock( true ); } } else CKEDITOR.dialog._.currentZIndex -= 10; delete this._.parentDialog; // Reset the initial values of the dialog. this.foreach( function( contentObj ) { contentObj.resetInitValue && contentObj.resetInitValue(); } ); }, /** * Adds a tabbed page into the dialog. * @param {Object} contents Content definition. * @example */ addPage : function( contents ) { var pageHtml = [], titleHtml = contents.label ? ' title="' + CKEDITOR.tools.htmlEncode( contents.label ) + '"' : '', elements = contents.elements, vbox = CKEDITOR.dialog._.uiElementBuilders.vbox.build( this, { type : 'vbox', className : 'cke_dialog_page_contents', children : contents.elements, expand : !!contents.expand, padding : contents.padding, style : contents.style || 'width: 100%;height:100%' }, pageHtml ); // Create the HTML for the tab and the content block. var page = CKEDITOR.dom.element.createFromHtml( pageHtml.join( '' ) ); page.setAttribute( 'role', 'tabpanel' ); var env = CKEDITOR.env; var tabId = 'cke_' + contents.id + '_' + CKEDITOR.tools.getNextNumber(), tab = CKEDITOR.dom.element.createFromHtml( [ '<a class="cke_dialog_tab"', ( this._.pageCount > 0 ? ' cke_last' : 'cke_first' ), titleHtml, ( !!contents.hidden ? ' style="display:none"' : '' ), ' id="', tabId, '"', env.gecko && env.version >= 10900 && !env.hc ? '' : ' href="javascript:void(0)"', ' tabIndex="-1"', ' hidefocus="true"', ' role="tab">', contents.label, '</a>' ].join( '' ) ); page.setAttribute( 'aria-labelledby', tabId ); // Take records for the tabs and elements created. this._.tabs[ contents.id ] = [ tab, page ]; this._.tabIdList.push( contents.id ); !contents.hidden && this._.pageCount++; this._.lastTab = tab; this.updateStyle(); var contentMap = this._.contents[ contents.id ] = {}, cursor, children = vbox.getChild(); while ( ( cursor = children.shift() ) ) { contentMap[ cursor.id ] = cursor; if ( typeof( cursor.getChild ) == 'function' ) children.push.apply( children, cursor.getChild() ); } // Attach the DOM nodes. page.setAttribute( 'name', contents.id ); page.appendTo( this.parts.contents ); tab.unselectable(); this.parts.tabs.append( tab ); // Add access key handlers if access key is defined. if ( contents.accessKey ) { registerAccessKey( this, this, 'CTRL+' + contents.accessKey, tabAccessKeyDown, tabAccessKeyUp ); this._.accessKeyMap[ 'CTRL+' + contents.accessKey ] = contents.id; } }, /** * Activates a tab page in the dialog by its id. * @param {String} id The id of the dialog tab to be activated. * @example * dialogObj.selectPage( 'tab_1' ); */ selectPage : function( id ) { if ( this._.currentTabId == id ) return; // Returning true means that the event has been canceled if ( this.fire( 'selectPage', { page : id, currentPage : this._.currentTabId } ) === true ) return; // Hide the non-selected tabs and pages. for ( var i in this._.tabs ) { var tab = this._.tabs[i][0], page = this._.tabs[i][1]; if ( i != id ) { tab.removeClass( 'cke_dialog_tab_selected' ); page.hide(); } page.setAttribute( 'aria-hidden', i != id ); } var selected = this._.tabs[ id ]; selected[ 0 ].addClass( 'cke_dialog_tab_selected' ); // [IE] an invisible input[type='text'] will enlarge it's width // if it's value is long when it shows, so we clear it's value // before it shows and then recover it (#5649) if ( CKEDITOR.env.ie6Compat || CKEDITOR.env.ie7Compat ) { clearOrRecoverTextInputValue( selected[ 1 ] ); selected[ 1 ].show(); setTimeout( function() { clearOrRecoverTextInputValue( selected[ 1 ], 1 ); }, 0 ); } else selected[ 1 ].show(); this._.currentTabId = id; this._.currentTabIndex = CKEDITOR.tools.indexOf( this._.tabIdList, id ); }, // Dialog state-specific style updates. updateStyle : function() { // If only a single page shown, a different style is used in the central pane. this.parts.dialog[ ( this._.pageCount === 1 ? 'add' : 'remove' ) + 'Class' ]( 'cke_single_page' ); }, /** * Hides a page's tab away from the dialog. * @param {String} id The page's Id. * @example * dialog.hidePage( 'tab_3' ); */ hidePage : function( id ) { var tab = this._.tabs[id] && this._.tabs[id][0]; if ( !tab || this._.pageCount == 1 || !tab.isVisible() ) return; // Switch to other tab first when we're hiding the active tab. else if ( id == this._.currentTabId ) this.selectPage( getPreviousVisibleTab.call( this ) ); tab.hide(); this._.pageCount--; this.updateStyle(); }, /** * Unhides a page's tab. * @param {String} id The page's Id. * @example * dialog.showPage( 'tab_2' ); */ showPage : function( id ) { var tab = this._.tabs[id] && this._.tabs[id][0]; if ( !tab ) return; tab.show(); this._.pageCount++; this.updateStyle(); }, /** * Gets the root DOM element of the dialog. * @returns {CKEDITOR.dom.element} The &lt;span&gt; element containing this dialog. * @example * var dialogElement = dialogObj.getElement().getFirst(); * dialogElement.setStyle( 'padding', '5px' ); */ getElement : function() { return this._.element; }, /** * Gets the name of the dialog. * @returns {String} The name of this dialog. * @example * var dialogName = dialogObj.getName(); */ getName : function() { return this._.name; }, /** * Gets a dialog UI element object from a dialog page. * @param {String} pageId id of dialog page. * @param {String} elementId id of UI element. * @example * dialogObj.getContentElement( 'tabId', 'elementId' ).setValue( 'Example' ); * @returns {CKEDITOR.ui.dialog.uiElement} The dialog UI element. */ getContentElement : function( pageId, elementId ) { var page = this._.contents[ pageId ]; return page && page[ elementId ]; }, /** * Gets the value of a dialog UI element. * @param {String} pageId id of dialog page. * @param {String} elementId id of UI element. * @example * alert( dialogObj.getValueOf( 'tabId', 'elementId' ) ); * @returns {Object} The value of the UI element. */ getValueOf : function( pageId, elementId ) { return this.getContentElement( pageId, elementId ).getValue(); }, /** * Sets the value of a dialog UI element. * @param {String} pageId id of the dialog page. * @param {String} elementId id of the UI element. * @param {Object} value The new value of the UI element. * @example * dialogObj.setValueOf( 'tabId', 'elementId', 'Example' ); */ setValueOf : function( pageId, elementId, value ) { return this.getContentElement( pageId, elementId ).setValue( value ); }, /** * Gets the UI element of a button in the dialog's button row. * @param {String} id The id of the button. * @example * @returns {CKEDITOR.ui.dialog.button} The button object. */ getButton : function( id ) { return this._.buttons[ id ]; }, /** * Simulates a click to a dialog button in the dialog's button row. * @param {String} id The id of the button. * @example * @returns The return value of the dialog's "click" event. */ click : function( id ) { return this._.buttons[ id ].click(); }, /** * Disables a dialog button. * @param {String} id The id of the button. * @example */ disableButton : function( id ) { return this._.buttons[ id ].disable(); }, /** * Enables a dialog button. * @param {String} id The id of the button. * @example */ enableButton : function( id ) { return this._.buttons[ id ].enable(); }, /** * Gets the number of pages in the dialog. * @returns {Number} Page count. */ getPageCount : function() { return this._.pageCount; }, /** * Gets the editor instance which opened this dialog. * @returns {CKEDITOR.editor} Parent editor instances. */ getParentEditor : function() { return this._.editor; }, /** * Gets the element that was selected when opening the dialog, if any. * @returns {CKEDITOR.dom.element} The element that was selected, or null. */ getSelectedElement : function() { return this.getParentEditor().getSelection().getSelectedElement(); }, /** * Adds element to dialog's focusable list. * * @param {CKEDITOR.dom.element} element * @param {Number} [index] */ addFocusable: function( element, index ) { if ( typeof index == 'undefined' ) { index = this._.focusList.length; this._.focusList.push( new Focusable( this, element, index ) ); } else { this._.focusList.splice( index, 0, new Focusable( this, element, index ) ); for ( var i = index + 1 ; i < this._.focusList.length ; i++ ) this._.focusList[ i ].focusIndex++; } } }; CKEDITOR.tools.extend( CKEDITOR.dialog, /** * @lends CKEDITOR.dialog */ { /** * Registers a dialog. * @param {String} name The dialog's name. * @param {Function|String} dialogDefinition * A function returning the dialog's definition, or the URL to the .js file holding the function. * The function should accept an argument "editor" which is the current editor instance, and * return an object conforming to {@link CKEDITOR.dialog.definition}. * @see CKEDITOR.dialog.definition * @example * // Full sample plugin, which does not only register a dialog window but also adds an item to the context menu. * // To open the dialog window, choose "Open dialog" in the context menu. * CKEDITOR.plugins.add( 'myplugin', * { * init: function( editor ) * { * editor.addCommand( 'mydialog',new CKEDITOR.dialogCommand( 'mydialog' ) ); * * if ( editor.contextMenu ) * { * editor.addMenuGroup( 'mygroup', 10 ); * editor.addMenuItem( 'My Dialog', * { * label : 'Open dialog', * command : 'mydialog', * group : 'mygroup' * }); * editor.contextMenu.addListener( function( element ) * { * return { 'My Dialog' : CKEDITOR.TRISTATE_OFF }; * }); * } * * <strong>CKEDITOR.dialog.add</strong>( 'mydialog', function( api ) * { * // CKEDITOR.dialog.definition * var <strong>dialogDefinition</strong> = * { * title : 'Sample dialog', * minWidth : 390, * minHeight : 130, * contents : [ * { * id : 'tab1', * label : 'Label', * title : 'Title', * expand : true, * padding : 0, * elements : * [ * { * type : 'html', * html : '&lt;p&gt;This is some sample HTML content.&lt;/p&gt;' * }, * { * type : 'textarea', * id : 'textareaId', * rows : 4, * cols : 40 * } * ] * } * ], * buttons : [ CKEDITOR.dialog.okButton, CKEDITOR.dialog.cancelButton ], * onOk : function() { * // "this" is now a CKEDITOR.dialog object. * // Accessing dialog elements: * var textareaObj = this.<strong>getContentElement</strong>( 'tab1', 'textareaId' ); * alert( "You have entered: " + textareaObj.getValue() ); * } * }; * * return dialogDefinition; * } ); * } * } ); * * CKEDITOR.replace( 'editor1', { extraPlugins : 'myplugin' } ); */ add : function( name, dialogDefinition ) { // Avoid path registration from multiple instances override definition. if ( !this._.dialogDefinitions[name] || typeof dialogDefinition == 'function' ) this._.dialogDefinitions[name] = dialogDefinition; }, exists : function( name ) { return !!this._.dialogDefinitions[ name ]; }, getCurrent : function() { return CKEDITOR.dialog._.currentTop; }, /** * The default OK button for dialogs. Fires the "ok" event and closes the dialog if the event succeeds. * @static * @field * @example * @type Function */ okButton : (function() { var retval = function( editor, override ) { override = override || {}; return CKEDITOR.tools.extend( { id : 'ok', type : 'button', label : editor.lang.common.ok, 'class' : 'cke_dialog_ui_button_ok', onClick : function( evt ) { var dialog = evt.data.dialog; if ( dialog.fire( 'ok', { hide : true } ).hide !== false ) dialog.hide(); } }, override, true ); }; retval.type = 'button'; retval.override = function( override ) { return CKEDITOR.tools.extend( function( editor ){ return retval( editor, override ); }, { type : 'button' }, true ); }; return retval; })(), /** * The default cancel button for dialogs. Fires the "cancel" event and closes the dialog if no UI element value changed. * @static * @field * @example * @type Function */ cancelButton : (function() { var retval = function( editor, override ) { override = override || {}; return CKEDITOR.tools.extend( { id : 'cancel', type : 'button', label : editor.lang.common.cancel, 'class' : 'cke_dialog_ui_button_cancel', onClick : function( evt ) { var dialog = evt.data.dialog; if ( dialog.fire( 'cancel', { hide : true } ).hide !== false ) dialog.hide(); } }, override, true ); }; retval.type = 'button'; retval.override = function( override ) { return CKEDITOR.tools.extend( function( editor ){ return retval( editor, override ); }, { type : 'button' }, true ); }; return retval; })(), /** * Registers a dialog UI element. * @param {String} typeName The name of the UI element. * @param {Function} builder The function to build the UI element. * @example */ addUIElement : function( typeName, builder ) { this._.uiElementBuilders[ typeName ] = builder; } }); CKEDITOR.dialog._ = { uiElementBuilders : {}, dialogDefinitions : {}, currentTop : null, currentZIndex : null }; // "Inherit" (copy actually) from CKEDITOR.event. CKEDITOR.event.implementOn( CKEDITOR.dialog ); CKEDITOR.event.implementOn( CKEDITOR.dialog.prototype, true ); var defaultDialogDefinition = { resizable : CKEDITOR.DIALOG_RESIZE_BOTH, minWidth : 600, minHeight : 400, buttons : [ CKEDITOR.dialog.okButton, CKEDITOR.dialog.cancelButton ] }; // Tool function used to return an item from an array based on its id // property. var getById = function( array, id, recurse ) { for ( var i = 0, item ; ( item = array[ i ] ) ; i++ ) { if ( item.id == id ) return item; if ( recurse && item[ recurse ] ) { var retval = getById( item[ recurse ], id, recurse ) ; if ( retval ) return retval; } } return null; }; // Tool function used to add an item into an array. var addById = function( array, newItem, nextSiblingId, recurse, nullIfNotFound ) { if ( nextSiblingId ) { for ( var i = 0, item ; ( item = array[ i ] ) ; i++ ) { if ( item.id == nextSiblingId ) { array.splice( i, 0, newItem ); return newItem; } if ( recurse && item[ recurse ] ) { var retval = addById( item[ recurse ], newItem, nextSiblingId, recurse, true ); if ( retval ) return retval; } } if ( nullIfNotFound ) return null; } array.push( newItem ); return newItem; }; // Tool function used to remove an item from an array based on its id. var removeById = function( array, id, recurse ) { for ( var i = 0, item ; ( item = array[ i ] ) ; i++ ) { if ( item.id == id ) return array.splice( i, 1 ); if ( recurse && item[ recurse ] ) { var retval = removeById( item[ recurse ], id, recurse ); if ( retval ) return retval; } } return null; }; /** * This class is not really part of the API. It is the "definition" property value * passed to "dialogDefinition" event handlers. * @constructor * @name CKEDITOR.dialog.definitionObject * @extends CKEDITOR.dialog.definition * @example * CKEDITOR.on( 'dialogDefinition', function( evt ) * { * var definition = evt.data.definition; * var content = definition.getContents( 'page1' ); * ... * } ); */ var definitionObject = function( dialog, dialogDefinition ) { // TODO : Check if needed. this.dialog = dialog; // Transform the contents entries in contentObjects. var contents = dialogDefinition.contents; for ( var i = 0, content ; ( content = contents[i] ) ; i++ ) contents[ i ] = content && new contentObject( dialog, content ); CKEDITOR.tools.extend( this, dialogDefinition ); }; definitionObject.prototype = /** @lends CKEDITOR.dialog.definitionObject.prototype */ { /** * Gets a content definition. * @param {String} id The id of the content definition. * @returns {CKEDITOR.dialog.definition.content} The content definition * matching id. */ getContents : function( id ) { return getById( this.contents, id ); }, /** * Gets a button definition. * @param {String} id The id of the button definition. * @returns {CKEDITOR.dialog.definition.button} The button definition * matching id. */ getButton : function( id ) { return getById( this.buttons, id ); }, /** * Adds a content definition object under this dialog definition. * @param {CKEDITOR.dialog.definition.content} contentDefinition The * content definition. * @param {String} [nextSiblingId] The id of an existing content * definition which the new content definition will be inserted * before. Omit if the new content definition is to be inserted as * the last item. * @returns {CKEDITOR.dialog.definition.content} The inserted content * definition. */ addContents : function( contentDefinition, nextSiblingId ) { return addById( this.contents, contentDefinition, nextSiblingId ); }, /** * Adds a button definition object under this dialog definition. * @param {CKEDITOR.dialog.definition.button} buttonDefinition The * button definition. * @param {String} [nextSiblingId] The id of an existing button * definition which the new button definition will be inserted * before. Omit if the new button definition is to be inserted as * the last item. * @returns {CKEDITOR.dialog.definition.button} The inserted button * definition. */ addButton : function( buttonDefinition, nextSiblingId ) { return addById( this.buttons, buttonDefinition, nextSiblingId ); }, /** * Removes a content definition from this dialog definition. * @param {String} id The id of the content definition to be removed. * @returns {CKEDITOR.dialog.definition.content} The removed content * definition. */ removeContents : function( id ) { removeById( this.contents, id ); }, /** * Removes a button definition from the dialog definition. * @param {String} id The id of the button definition to be removed. * @returns {CKEDITOR.dialog.definition.button} The removed button * definition. */ removeButton : function( id ) { removeById( this.buttons, id ); } }; /** * This class is not really part of the API. It is the template of the * objects representing content pages inside the * CKEDITOR.dialog.definitionObject. * @constructor * @name CKEDITOR.dialog.definition.contentObject * @example * CKEDITOR.on( 'dialogDefinition', function( evt ) * { * var definition = evt.data.definition; * var content = definition.getContents( 'page1' ); * content.remove( 'textInput1' ); * ... * } ); */ function contentObject( dialog, contentDefinition ) { this._ = { dialog : dialog }; CKEDITOR.tools.extend( this, contentDefinition ); } contentObject.prototype = /** @lends CKEDITOR.dialog.definition.contentObject.prototype */ { /** * Gets a UI element definition under the content definition. * @param {String} id The id of the UI element definition. * @returns {CKEDITOR.dialog.definition.uiElement} */ get : function( id ) { return getById( this.elements, id, 'children' ); }, /** * Adds a UI element definition to the content definition. * @param {CKEDITOR.dialog.definition.uiElement} elementDefinition The * UI elemnet definition to be added. * @param {String} nextSiblingId The id of an existing UI element * definition which the new UI element definition will be inserted * before. Omit if the new button definition is to be inserted as * the last item. * @returns {CKEDITOR.dialog.definition.uiElement} The element * definition inserted. */ add : function( elementDefinition, nextSiblingId ) { return addById( this.elements, elementDefinition, nextSiblingId, 'children' ); }, /** * Removes a UI element definition from the content definition. * @param {String} id The id of the UI element definition to be * removed. * @returns {CKEDITOR.dialog.definition.uiElement} The element * definition removed. * @example */ remove : function( id ) { removeById( this.elements, id, 'children' ); } }; function initDragAndDrop( dialog ) { var lastCoords = null, abstractDialogCoords = null, element = dialog.getElement().getFirst(), editor = dialog.getParentEditor(), magnetDistance = editor.config.dialog_magnetDistance, margins = editor.skin.margins || [ 0, 0, 0, 0 ]; if ( typeof magnetDistance == 'undefined' ) magnetDistance = 20; function mouseMoveHandler( evt ) { var dialogSize = dialog.getSize(), viewPaneSize = CKEDITOR.document.getWindow().getViewPaneSize(), x = evt.data.$.screenX, y = evt.data.$.screenY, dx = x - lastCoords.x, dy = y - lastCoords.y, realX, realY; lastCoords = { x : x, y : y }; abstractDialogCoords.x += dx; abstractDialogCoords.y += dy; if ( abstractDialogCoords.x + margins[3] < magnetDistance ) realX = - margins[3]; else if ( abstractDialogCoords.x - margins[1] > viewPaneSize.width - dialogSize.width - magnetDistance ) realX = viewPaneSize.width - dialogSize.width + ( editor.lang.dir == 'rtl' ? 0 : margins[1] ); else realX = abstractDialogCoords.x; if ( abstractDialogCoords.y + margins[0] < magnetDistance ) realY = - margins[0]; else if ( abstractDialogCoords.y - margins[2] > viewPaneSize.height - dialogSize.height - magnetDistance ) realY = viewPaneSize.height - dialogSize.height + margins[2]; else realY = abstractDialogCoords.y; dialog.move( realX, realY, 1 ); evt.data.preventDefault(); } function mouseUpHandler( evt ) { CKEDITOR.document.removeListener( 'mousemove', mouseMoveHandler ); CKEDITOR.document.removeListener( 'mouseup', mouseUpHandler ); if ( CKEDITOR.env.ie6Compat ) { var coverDoc = currentCover.getChild( 0 ).getFrameDocument(); coverDoc.removeListener( 'mousemove', mouseMoveHandler ); coverDoc.removeListener( 'mouseup', mouseUpHandler ); } } dialog.parts.title.on( 'mousedown', function( evt ) { lastCoords = { x : evt.data.$.screenX, y : evt.data.$.screenY }; CKEDITOR.document.on( 'mousemove', mouseMoveHandler ); CKEDITOR.document.on( 'mouseup', mouseUpHandler ); abstractDialogCoords = dialog.getPosition(); if ( CKEDITOR.env.ie6Compat ) { var coverDoc = currentCover.getChild( 0 ).getFrameDocument(); coverDoc.on( 'mousemove', mouseMoveHandler ); coverDoc.on( 'mouseup', mouseUpHandler ); } evt.data.preventDefault(); }, dialog ); } function initResizeHandles( dialog ) { var def = dialog.definition, resizable = def.resizable; if ( resizable == CKEDITOR.DIALOG_RESIZE_NONE ) return; var editor = dialog.getParentEditor(); var wrapperWidth, wrapperHeight, viewSize, origin, startSize, dialogCover; var mouseDownFn = CKEDITOR.tools.addFunction( function( $event ) { startSize = dialog.getSize(); var content = dialog.parts.contents, iframeDialog = content.$.getElementsByTagName( 'iframe' ).length; // Shim to help capturing "mousemove" over iframe. if ( iframeDialog ) { dialogCover = CKEDITOR.dom.element.createFromHtml( '<div class="cke_dialog_resize_cover" style="height: 100%; position: absolute; width: 100%;"></div>' ); content.append( dialogCover ); } // Calculate the offset between content and chrome size. wrapperHeight = startSize.height - dialog.parts.contents.getSize( 'height', ! ( CKEDITOR.env.gecko || CKEDITOR.env.opera || CKEDITOR.env.ie && CKEDITOR.env.quirks ) ); wrapperWidth = startSize.width - dialog.parts.contents.getSize( 'width', 1 ); origin = { x : $event.screenX, y : $event.screenY }; viewSize = CKEDITOR.document.getWindow().getViewPaneSize(); CKEDITOR.document.on( 'mousemove', mouseMoveHandler ); CKEDITOR.document.on( 'mouseup', mouseUpHandler ); if ( CKEDITOR.env.ie6Compat ) { var coverDoc = currentCover.getChild( 0 ).getFrameDocument(); coverDoc.on( 'mousemove', mouseMoveHandler ); coverDoc.on( 'mouseup', mouseUpHandler ); } $event.preventDefault && $event.preventDefault(); }); // Prepend the grip to the dialog. dialog.on( 'load', function() { var direction = ''; if ( resizable == CKEDITOR.DIALOG_RESIZE_WIDTH ) direction = ' cke_resizer_horizontal'; else if ( resizable == CKEDITOR.DIALOG_RESIZE_HEIGHT ) direction = ' cke_resizer_vertical'; var resizer = CKEDITOR.dom.element.createFromHtml( '<div' + ' class="cke_resizer' + direction + ' cke_resizer_' + editor.lang.dir + '"' + ' title="' + CKEDITOR.tools.htmlEncode( editor.lang.resize ) + '"' + ' onmousedown="CKEDITOR.tools.callFunction(' + mouseDownFn + ', event )"></div>' ); dialog.parts.footer.append( resizer, 1 ); }); editor.on( 'destroy', function() { CKEDITOR.tools.removeFunction( mouseDownFn ); } ); function mouseMoveHandler( evt ) { var rtl = editor.lang.dir == 'rtl', dx = ( evt.data.$.screenX - origin.x ) * ( rtl ? -1 : 1 ), dy = evt.data.$.screenY - origin.y, width = startSize.width, height = startSize.height, internalWidth = width + dx * ( dialog._.moved ? 1 : 2 ), internalHeight = height + dy * ( dialog._.moved ? 1 : 2 ), element = dialog._.element.getFirst(), right = rtl && element.getComputedStyle( 'right' ), position = dialog.getPosition(); if ( position.y + internalHeight > viewSize.height ) internalHeight = viewSize.height - position.y; if ( ( rtl ? right : position.x ) + internalWidth > viewSize.width ) internalWidth = viewSize.width - ( rtl ? right : position.x ); // Make sure the dialog will not be resized to the wrong side when it's in the leftmost position for RTL. if ( ( resizable == CKEDITOR.DIALOG_RESIZE_WIDTH || resizable == CKEDITOR.DIALOG_RESIZE_BOTH ) ) width = Math.max( def.minWidth || 0, internalWidth - wrapperWidth ); if ( resizable == CKEDITOR.DIALOG_RESIZE_HEIGHT || resizable == CKEDITOR.DIALOG_RESIZE_BOTH ) height = Math.max( def.minHeight || 0, internalHeight - wrapperHeight ); dialog.resize( width, height ); if ( !dialog._.moved ) dialog.layout(); evt.data.preventDefault(); } function mouseUpHandler() { CKEDITOR.document.removeListener( 'mouseup', mouseUpHandler ); CKEDITOR.document.removeListener( 'mousemove', mouseMoveHandler ); if ( dialogCover ) { dialogCover.remove(); dialogCover = null; } if ( CKEDITOR.env.ie6Compat ) { var coverDoc = currentCover.getChild( 0 ).getFrameDocument(); coverDoc.removeListener( 'mouseup', mouseUpHandler ); coverDoc.removeListener( 'mousemove', mouseMoveHandler ); } } } var resizeCover; // Caching resuable covers and allowing only one cover // on screen. var covers = {}, currentCover; function cancelEvent( ev ) { ev.data.preventDefault(1); } function showCover( editor ) { var win = CKEDITOR.document.getWindow(); var config = editor.config, backgroundColorStyle = config.dialog_backgroundCoverColor || 'white', backgroundCoverOpacity = config.dialog_backgroundCoverOpacity, baseFloatZIndex = config.baseFloatZIndex, coverKey = CKEDITOR.tools.genKey( backgroundColorStyle, backgroundCoverOpacity, baseFloatZIndex ), coverElement = covers[ coverKey ]; if ( !coverElement ) { var html = [ '<div tabIndex="-1" style="position: ', ( CKEDITOR.env.ie6Compat ? 'absolute' : 'fixed' ), '; z-index: ', baseFloatZIndex, '; top: 0px; left: 0px; ', ( !CKEDITOR.env.ie6Compat ? 'background-color: ' + backgroundColorStyle : '' ), '" class="cke_dialog_background_cover">' ]; if ( CKEDITOR.env.ie6Compat ) { // Support for custom document.domain in IE. var isCustomDomain = CKEDITOR.env.isCustomDomain(), iframeHtml = '<html><body style=\\\'background-color:' + backgroundColorStyle + ';\\\'></body></html>'; html.push( '<iframe' + ' hidefocus="true"' + ' frameborder="0"' + ' id="cke_dialog_background_iframe"' + ' src="javascript:' ); html.push( 'void((function(){' + 'document.open();' + ( isCustomDomain ? 'document.domain=\'' + document.domain + '\';' : '' ) + 'document.write( \'' + iframeHtml + '\' );' + 'document.close();' + '})())' ); html.push( '"' + ' style="' + 'position:absolute;' + 'left:0;' + 'top:0;' + 'width:100%;' + 'height: 100%;' + 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)">' + '</iframe>' ); } html.push( '</div>' ); coverElement = CKEDITOR.dom.element.createFromHtml( html.join( '' ) ); coverElement.setOpacity( backgroundCoverOpacity != undefined ? backgroundCoverOpacity : 0.5 ); coverElement.on( 'keydown', cancelEvent ); coverElement.on( 'keypress', cancelEvent ); coverElement.on( 'keyup', cancelEvent ); coverElement.appendTo( CKEDITOR.document.getBody() ); covers[ coverKey ] = coverElement; } else coverElement. show(); currentCover = coverElement; var resizeFunc = function() { var size = win.getViewPaneSize(); coverElement.setStyles( { width : size.width + 'px', height : size.height + 'px' } ); }; var scrollFunc = function() { var pos = win.getScrollPosition(), cursor = CKEDITOR.dialog._.currentTop; coverElement.setStyles( { left : pos.x + 'px', top : pos.y + 'px' }); if ( cursor ) { do { var dialogPos = cursor.getPosition(); cursor.move( dialogPos.x, dialogPos.y ); } while ( ( cursor = cursor._.parentDialog ) ); } }; resizeCover = resizeFunc; win.on( 'resize', resizeFunc ); resizeFunc(); // Using Safari/Mac, focus must be kept where it is (#7027) if ( !( CKEDITOR.env.mac && CKEDITOR.env.webkit ) ) coverElement.focus(); if ( CKEDITOR.env.ie6Compat ) { // IE BUG: win.$.onscroll assignment doesn't work.. it must be window.onscroll. // So we need to invent a really funny way to make it work. var myScrollHandler = function() { scrollFunc(); arguments.callee.prevScrollHandler.apply( this, arguments ); }; win.$.setTimeout( function() { myScrollHandler.prevScrollHandler = window.onscroll || function(){}; window.onscroll = myScrollHandler; }, 0 ); scrollFunc(); } } function hideCover() { if ( !currentCover ) return; var win = CKEDITOR.document.getWindow(); currentCover.hide(); win.removeListener( 'resize', resizeCover ); if ( CKEDITOR.env.ie6Compat ) { win.$.setTimeout( function() { var prevScrollHandler = window.onscroll && window.onscroll.prevScrollHandler; window.onscroll = prevScrollHandler || null; }, 0 ); } resizeCover = null; } function removeCovers() { for ( var coverId in covers ) covers[ coverId ].remove(); covers = {}; } var accessKeyProcessors = {}; var accessKeyDownHandler = function( evt ) { var ctrl = evt.data.$.ctrlKey || evt.data.$.metaKey, alt = evt.data.$.altKey, shift = evt.data.$.shiftKey, key = String.fromCharCode( evt.data.$.keyCode ), keyProcessor = accessKeyProcessors[( ctrl ? 'CTRL+' : '' ) + ( alt ? 'ALT+' : '') + ( shift ? 'SHIFT+' : '' ) + key]; if ( !keyProcessor || !keyProcessor.length ) return; keyProcessor = keyProcessor[keyProcessor.length - 1]; keyProcessor.keydown && keyProcessor.keydown.call( keyProcessor.uiElement, keyProcessor.dialog, keyProcessor.key ); evt.data.preventDefault(); }; var accessKeyUpHandler = function( evt ) { var ctrl = evt.data.$.ctrlKey || evt.data.$.metaKey, alt = evt.data.$.altKey, shift = evt.data.$.shiftKey, key = String.fromCharCode( evt.data.$.keyCode ), keyProcessor = accessKeyProcessors[( ctrl ? 'CTRL+' : '' ) + ( alt ? 'ALT+' : '') + ( shift ? 'SHIFT+' : '' ) + key]; if ( !keyProcessor || !keyProcessor.length ) return; keyProcessor = keyProcessor[keyProcessor.length - 1]; if ( keyProcessor.keyup ) { keyProcessor.keyup.call( keyProcessor.uiElement, keyProcessor.dialog, keyProcessor.key ); evt.data.preventDefault(); } }; var registerAccessKey = function( uiElement, dialog, key, downFunc, upFunc ) { var procList = accessKeyProcessors[key] || ( accessKeyProcessors[key] = [] ); procList.push( { uiElement : uiElement, dialog : dialog, key : key, keyup : upFunc || uiElement.accessKeyUp, keydown : downFunc || uiElement.accessKeyDown } ); }; var unregisterAccessKey = function( obj ) { for ( var i in accessKeyProcessors ) { var list = accessKeyProcessors[i]; for ( var j = list.length - 1 ; j >= 0 ; j-- ) { if ( list[j].dialog == obj || list[j].uiElement == obj ) list.splice( j, 1 ); } if ( list.length === 0 ) delete accessKeyProcessors[i]; } }; var tabAccessKeyUp = function( dialog, key ) { if ( dialog._.accessKeyMap[key] ) dialog.selectPage( dialog._.accessKeyMap[key] ); }; var tabAccessKeyDown = function( dialog, key ) { }; // ESC, ENTER var preventKeyBubblingKeys = { 27 :1, 13 :1 }; var preventKeyBubbling = function( e ) { if ( e.data.getKeystroke() in preventKeyBubblingKeys ) e.data.stopPropagation(); }; (function() { CKEDITOR.ui.dialog = { /** * The base class of all dialog UI elements. * @constructor * @param {CKEDITOR.dialog} dialog Parent dialog object. * @param {CKEDITOR.dialog.definition.uiElement} elementDefinition Element * definition. Accepted fields: * <ul> * <li><strong>id</strong> (Required) The id of the UI element. See {@link * CKEDITOR.dialog#getContentElement}</li> * <li><strong>type</strong> (Required) The type of the UI element. The * value to this field specifies which UI element class will be used to * generate the final widget.</li> * <li><strong>title</strong> (Optional) The popup tooltip for the UI * element.</li> * <li><strong>hidden</strong> (Optional) A flag that tells if the element * should be initially visible.</li> * <li><strong>className</strong> (Optional) Additional CSS class names * to add to the UI element. Separated by space.</li> * <li><strong>style</strong> (Optional) Additional CSS inline styles * to add to the UI element. A semicolon (;) is required after the last * style declaration.</li> * <li><strong>accessKey</strong> (Optional) The alphanumeric access key * for this element. Access keys are automatically prefixed by CTRL.</li> * <li><strong>on*</strong> (Optional) Any UI element definition field that * starts with <em>on</em> followed immediately by a capital letter and * probably more letters is an event handler. Event handlers may be further * divided into registered event handlers and DOM event handlers. Please * refer to {@link CKEDITOR.ui.dialog.uiElement#registerEvents} and * {@link CKEDITOR.ui.dialog.uiElement#eventProcessors} for more * information.</li> * </ul> * @param {Array} htmlList * List of HTML code to be added to the dialog's content area. * @param {Function|String} nodeNameArg * A function returning a string, or a simple string for the node name for * the root DOM node. Default is 'div'. * @param {Function|Object} stylesArg * A function returning an object, or a simple object for CSS styles applied * to the DOM node. Default is empty object. * @param {Function|Object} attributesArg * A fucntion returning an object, or a simple object for attributes applied * to the DOM node. Default is empty object. * @param {Function|String} contentsArg * A function returning a string, or a simple string for the HTML code inside * the root DOM node. Default is empty string. * @example */ uiElement : function( dialog, elementDefinition, htmlList, nodeNameArg, stylesArg, attributesArg, contentsArg ) { if ( arguments.length < 4 ) return; var nodeName = ( nodeNameArg.call ? nodeNameArg( elementDefinition ) : nodeNameArg ) || 'div', html = [ '<', nodeName, ' ' ], styles = ( stylesArg && stylesArg.call ? stylesArg( elementDefinition ) : stylesArg ) || {}, attributes = ( attributesArg && attributesArg.call ? attributesArg( elementDefinition ) : attributesArg ) || {}, innerHTML = ( contentsArg && contentsArg.call ? contentsArg.call( this, dialog, elementDefinition ) : contentsArg ) || '', domId = this.domId = attributes.id || CKEDITOR.tools.getNextId() + '_uiElement', id = this.id = elementDefinition.id, i; // Set the id, a unique id is required for getElement() to work. attributes.id = domId; // Set the type and definition CSS class names. var classes = {}; if ( elementDefinition.type ) classes[ 'cke_dialog_ui_' + elementDefinition.type ] = 1; if ( elementDefinition.className ) classes[ elementDefinition.className ] = 1; if ( elementDefinition.disabled ) classes[ 'cke_disabled' ] = 1; var attributeClasses = ( attributes['class'] && attributes['class'].split ) ? attributes['class'].split( ' ' ) : []; for ( i = 0 ; i < attributeClasses.length ; i++ ) { if ( attributeClasses[i] ) classes[ attributeClasses[i] ] = 1; } var finalClasses = []; for ( i in classes ) finalClasses.push( i ); attributes['class'] = finalClasses.join( ' ' ); // Set the popup tooltop. if ( elementDefinition.title ) attributes.title = elementDefinition.title; // Write the inline CSS styles. var styleStr = ( elementDefinition.style || '' ).split( ';' ); // Element alignment support. if ( elementDefinition.align ) { var align = elementDefinition.align; styles[ 'margin-left' ] = align == 'left' ? 0 : 'auto'; styles[ 'margin-right' ] = align == 'right' ? 0 : 'auto'; } for ( i in styles ) styleStr.push( i + ':' + styles[i] ); if ( elementDefinition.hidden ) styleStr.push( 'display:none' ); for ( i = styleStr.length - 1 ; i >= 0 ; i-- ) { if ( styleStr[i] === '' ) styleStr.splice( i, 1 ); } if ( styleStr.length > 0 ) attributes.style = ( attributes.style ? ( attributes.style + '; ' ) : '' ) + styleStr.join( '; ' ); // Write the attributes. for ( i in attributes ) html.push( i + '="' + CKEDITOR.tools.htmlEncode( attributes[i] ) + '" '); // Write the content HTML. html.push( '>', innerHTML, '</', nodeName, '>' ); // Add contents to the parent HTML array. htmlList.push( html.join( '' ) ); ( this._ || ( this._ = {} ) ).dialog = dialog; // Override isChanged if it is defined in element definition. if ( typeof( elementDefinition.isChanged ) == 'boolean' ) this.isChanged = function(){ return elementDefinition.isChanged; }; if ( typeof( elementDefinition.isChanged ) == 'function' ) this.isChanged = elementDefinition.isChanged; // Overload 'get(set)Value' on definition. if ( typeof( elementDefinition.setValue ) == 'function' ) { this.setValue = CKEDITOR.tools.override( this.setValue, function( org ) { return function( val ){ org.call( this, elementDefinition.setValue.call( this, val ) ); }; } ); } if ( typeof( elementDefinition.getValue ) == 'function' ) { this.getValue = CKEDITOR.tools.override( this.getValue, function( org ) { return function(){ return elementDefinition.getValue.call( this, org.call( this ) ); }; } ); } // Add events. CKEDITOR.event.implementOn( this ); this.registerEvents( elementDefinition ); if ( this.accessKeyUp && this.accessKeyDown && elementDefinition.accessKey ) registerAccessKey( this, dialog, 'CTRL+' + elementDefinition.accessKey ); var me = this; dialog.on( 'load', function() { var input = me.getInputElement(); if ( input ) { var focusClass = me.type in { 'checkbox' : 1, 'ratio' : 1 } && CKEDITOR.env.ie && CKEDITOR.env.version < 8 ? 'cke_dialog_ui_focused' : ''; input.on( 'focus', function() { dialog._.tabBarMode = false; dialog._.hasFocus = true; me.fire( 'focus' ); focusClass && this.addClass( focusClass ); }); input.on( 'blur', function() { me.fire( 'blur' ); focusClass && this.removeClass( focusClass ); }); } } ); // Register the object as a tab focus if it can be included. if ( this.keyboardFocusable ) { this.tabIndex = elementDefinition.tabIndex || 0; this.focusIndex = dialog._.focusList.push( this ) - 1; this.on( 'focus', function() { dialog._.currentFocusIndex = me.focusIndex; } ); } // Completes this object with everything we have in the // definition. CKEDITOR.tools.extend( this, elementDefinition ); }, /** * Horizontal layout box for dialog UI elements, auto-expends to available width of container. * @constructor * @extends CKEDITOR.ui.dialog.uiElement * @param {CKEDITOR.dialog} dialog * Parent dialog object. * @param {Array} childObjList * Array of {@link CKEDITOR.ui.dialog.uiElement} objects inside this * container. * @param {Array} childHtmlList * Array of HTML code that correspond to the HTML output of all the * objects in childObjList. * @param {Array} htmlList * Array of HTML code that this element will output to. * @param {CKEDITOR.dialog.definition.uiElement} elementDefinition * The element definition. Accepted fields: * <ul> * <li><strong>widths</strong> (Optional) The widths of child cells.</li> * <li><strong>height</strong> (Optional) The height of the layout.</li> * <li><strong>padding</strong> (Optional) The padding width inside child * cells.</li> * <li><strong>align</strong> (Optional) The alignment of the whole layout * </li> * </ul> * @example */ hbox : function( dialog, childObjList, childHtmlList, htmlList, elementDefinition ) { if ( arguments.length < 4 ) return; this._ || ( this._ = {} ); var children = this._.children = childObjList, widths = elementDefinition && elementDefinition.widths || null, height = elementDefinition && elementDefinition.height || null, styles = {}, i; /** @ignore */ var innerHTML = function() { var html = [ '<tbody><tr class="cke_dialog_ui_hbox">' ]; for ( i = 0 ; i < childHtmlList.length ; i++ ) { var className = 'cke_dialog_ui_hbox_child', styles = []; if ( i === 0 ) className = 'cke_dialog_ui_hbox_first'; if ( i == childHtmlList.length - 1 ) className = 'cke_dialog_ui_hbox_last'; html.push( '<td class="', className, '" role="presentation" ' ); if ( widths ) { if ( widths[i] ) styles.push( 'width:' + cssLength( widths[i] ) ); } else styles.push( 'width:' + Math.floor( 100 / childHtmlList.length ) + '%' ); if ( height ) styles.push( 'height:' + cssLength( height ) ); if ( elementDefinition && elementDefinition.padding != undefined ) styles.push( 'padding:' + cssLength( elementDefinition.padding ) ); // In IE Quirks alignment has to be done on table cells. (#7324) if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && children[ i ].align ) styles.push( 'text-align:' + children[ i ].align ); if ( styles.length > 0 ) html.push( 'style="' + styles.join('; ') + '" ' ); html.push( '>', childHtmlList[i], '</td>' ); } html.push( '</tr></tbody>' ); return html.join( '' ); }; var attribs = { role : 'presentation' }; elementDefinition && elementDefinition.align && ( attribs.align = elementDefinition.align ); CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition || { type : 'hbox' }, htmlList, 'table', styles, attribs, innerHTML ); }, /** * Vertical layout box for dialog UI elements. * @constructor * @extends CKEDITOR.ui.dialog.hbox * @param {CKEDITOR.dialog} dialog * Parent dialog object. * @param {Array} childObjList * Array of {@link CKEDITOR.ui.dialog.uiElement} objects inside this * container. * @param {Array} childHtmlList * Array of HTML code that correspond to the HTML output of all the * objects in childObjList. * @param {Array} htmlList * Array of HTML code that this element will output to. * @param {CKEDITOR.dialog.definition.uiElement} elementDefinition * The element definition. Accepted fields: * <ul> * <li><strong>width</strong> (Optional) The width of the layout.</li> * <li><strong>heights</strong> (Optional) The heights of individual cells. * </li> * <li><strong>align</strong> (Optional) The alignment of the layout.</li> * <li><strong>padding</strong> (Optional) The padding width inside child * cells.</li> * <li><strong>expand</strong> (Optional) Whether the layout should expand * vertically to fill its container.</li> * </ul> * @example */ vbox : function( dialog, childObjList, childHtmlList, htmlList, elementDefinition ) { if ( arguments.length < 3 ) return; this._ || ( this._ = {} ); var children = this._.children = childObjList, width = elementDefinition && elementDefinition.width || null, heights = elementDefinition && elementDefinition.heights || null; /** @ignore */ var innerHTML = function() { var html = [ '<table role="presentation" cellspacing="0" border="0" ' ]; html.push( 'style="' ); if ( elementDefinition && elementDefinition.expand ) html.push( 'height:100%;' ); html.push( 'width:' + cssLength( width || '100%' ), ';' ); html.push( '"' ); html.push( 'align="', CKEDITOR.tools.htmlEncode( ( elementDefinition && elementDefinition.align ) || ( dialog.getParentEditor().lang.dir == 'ltr' ? 'left' : 'right' ) ), '" ' ); html.push( '><tbody>' ); for ( var i = 0 ; i < childHtmlList.length ; i++ ) { var styles = []; html.push( '<tr><td role="presentation" ' ); if ( width ) styles.push( 'width:' + cssLength( width || '100%' ) ); if ( heights ) styles.push( 'height:' + cssLength( heights[i] ) ); else if ( elementDefinition && elementDefinition.expand ) styles.push( 'height:' + Math.floor( 100 / childHtmlList.length ) + '%' ); if ( elementDefinition && elementDefinition.padding != undefined ) styles.push( 'padding:' + cssLength( elementDefinition.padding ) ); // In IE Quirks alignment has to be done on table cells. (#7324) if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && children[ i ].align ) styles.push( 'text-align:' + children[ i ].align ); if ( styles.length > 0 ) html.push( 'style="', styles.join( '; ' ), '" ' ); html.push( ' class="cke_dialog_ui_vbox_child">', childHtmlList[i], '</td></tr>' ); } html.push( '</tbody></table>' ); return html.join( '' ); }; CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition || { type : 'vbox' }, htmlList, 'div', null, { role : 'presentation' }, innerHTML ); } }; })(); CKEDITOR.ui.dialog.uiElement.prototype = { /** * Gets the root DOM element of this dialog UI object. * @returns {CKEDITOR.dom.element} Root DOM element of UI object. * @example * uiElement.getElement().hide(); */ getElement : function() { return CKEDITOR.document.getById( this.domId ); }, /** * Gets the DOM element that the user inputs values. * This function is used by setValue(), getValue() and focus(). It should * be overrided in child classes where the input element isn't the root * element. * @returns {CKEDITOR.dom.element} The element where the user input values. * @example * var rawValue = textInput.getInputElement().$.value; */ getInputElement : function() { return this.getElement(); }, /** * Gets the parent dialog object containing this UI element. * @returns {CKEDITOR.dialog} Parent dialog object. * @example * var dialog = uiElement.getDialog(); */ getDialog : function() { return this._.dialog; }, /** * Sets the value of this dialog UI object. * @param {Object} value The new value. * @param {Boolean} noChangeEvent Internal commit, to supress 'change' event on this element. * @returns {CKEDITOR.dialog.uiElement} The current UI element. * @example * uiElement.setValue( 'Dingo' ); */ setValue : function( value, noChangeEvent ) { this.getInputElement().setValue( value ); !noChangeEvent && this.fire( 'change', { value : value } ); return this; }, /** * Gets the current value of this dialog UI object. * @returns {Object} The current value. * @example * var myValue = uiElement.getValue(); */ getValue : function() { return this.getInputElement().getValue(); }, /** * Tells whether the UI object's value has changed. * @returns {Boolean} true if changed, false if not changed. * @example * if ( uiElement.isChanged() ) * &nbsp;&nbsp;confirm( 'Value changed! Continue?' ); */ isChanged : function() { // Override in input classes. return false; }, /** * Selects the parent tab of this element. Usually called by focus() or overridden focus() methods. * @returns {CKEDITOR.dialog.uiElement} The current UI element. * @example * focus : function() * { * this.selectParentTab(); * // do something else. * } */ selectParentTab : function() { var element = this.getInputElement(), cursor = element, tabId; while ( ( cursor = cursor.getParent() ) && cursor.$.className.search( 'cke_dialog_page_contents' ) == -1 ) { /*jsl:pass*/ } // Some widgets don't have parent tabs (e.g. OK and Cancel buttons). if ( !cursor ) return this; tabId = cursor.getAttribute( 'name' ); // Avoid duplicate select. if ( this._.dialog._.currentTabId != tabId ) this._.dialog.selectPage( tabId ); return this; }, /** * Puts the focus to the UI object. Switches tabs if the UI object isn't in the active tab page. * @returns {CKEDITOR.dialog.uiElement} The current UI element. * @example * uiElement.focus(); */ focus : function() { this.selectParentTab().getInputElement().focus(); return this; }, /** * Registers the on* event handlers defined in the element definition. * The default behavior of this function is: * <ol> * <li> * If the on* event is defined in the class's eventProcesors list, * then the registration is delegated to the corresponding function * in the eventProcessors list. * </li> * <li> * If the on* event is not defined in the eventProcessors list, then * register the event handler under the corresponding DOM event of * the UI element's input DOM element (as defined by the return value * of {@link CKEDITOR.ui.dialog.uiElement#getInputElement}). * </li> * </ol> * This function is only called at UI element instantiation, but can * be overridded in child classes if they require more flexibility. * @param {CKEDITOR.dialog.definition.uiElement} definition The UI element * definition. * @returns {CKEDITOR.dialog.uiElement} The current UI element. * @example */ registerEvents : function( definition ) { var regex = /^on([A-Z]\w+)/, match; var registerDomEvent = function( uiElement, dialog, eventName, func ) { dialog.on( 'load', function() { uiElement.getInputElement().on( eventName, func, uiElement ); }); }; for ( var i in definition ) { if ( !( match = i.match( regex ) ) ) continue; if ( this.eventProcessors[i] ) this.eventProcessors[i].call( this, this._.dialog, definition[i] ); else registerDomEvent( this, this._.dialog, match[1].toLowerCase(), definition[i] ); } return this; }, /** * The event processor list used by * {@link CKEDITOR.ui.dialog.uiElement#getInputElement} at UI element * instantiation. The default list defines three on* events: * <ol> * <li>onLoad - Called when the element's parent dialog opens for the * first time</li> * <li>onShow - Called whenever the element's parent dialog opens.</li> * <li>onHide - Called whenever the element's parent dialog closes.</li> * </ol> * @field * @type Object * @example * // This connects the 'click' event in CKEDITOR.ui.dialog.button to onClick * // handlers in the UI element's definitions. * CKEDITOR.ui.dialog.button.eventProcessors = CKEDITOR.tools.extend( {}, * &nbsp;&nbsp;CKEDITOR.ui.dialog.uiElement.prototype.eventProcessors, * &nbsp;&nbsp;{ onClick : function( dialog, func ) { this.on( 'click', func ); } }, * &nbsp;&nbsp;true ); */ eventProcessors : { onLoad : function( dialog, func ) { dialog.on( 'load', func, this ); }, onShow : function( dialog, func ) { dialog.on( 'show', func, this ); }, onHide : function( dialog, func ) { dialog.on( 'hide', func, this ); } }, /** * The default handler for a UI element's access key down event, which * tries to put focus to the UI element.<br /> * Can be overridded in child classes for more sophisticaed behavior. * @param {CKEDITOR.dialog} dialog The parent dialog object. * @param {String} key The key combination pressed. Since access keys * are defined to always include the CTRL key, its value should always * include a 'CTRL+' prefix. * @example */ accessKeyDown : function( dialog, key ) { this.focus(); }, /** * The default handler for a UI element's access key up event, which * does nothing.<br /> * Can be overridded in child classes for more sophisticated behavior. * @param {CKEDITOR.dialog} dialog The parent dialog object. * @param {String} key The key combination pressed. Since access keys * are defined to always include the CTRL key, its value should always * include a 'CTRL+' prefix. * @example */ accessKeyUp : function( dialog, key ) { }, /** * Disables a UI element. * @example */ disable : function() { var element = this.getElement(), input = this.getInputElement(); input.setAttribute( 'disabled', 'true' ); element.addClass( 'cke_disabled' ); }, /** * Enables a UI element. * @example */ enable : function() { var element = this.getElement(), input = this.getInputElement(); input.removeAttribute( 'disabled' ); element.removeClass( 'cke_disabled' ); }, /** * Determines whether an UI element is enabled or not. * @returns {Boolean} Whether the UI element is enabled. * @example */ isEnabled : function() { return !this.getElement().hasClass( 'cke_disabled' ); }, /** * Determines whether an UI element is visible or not. * @returns {Boolean} Whether the UI element is visible. * @example */ isVisible : function() { return this.getInputElement().isVisible(); }, /** * Determines whether an UI element is focus-able or not. * Focus-able is defined as being both visible and enabled. * @returns {Boolean} Whether the UI element can be focused. * @example */ isFocusable : function() { if ( !this.isEnabled() || !this.isVisible() ) return false; return true; } }; CKEDITOR.ui.dialog.hbox.prototype = CKEDITOR.tools.extend( new CKEDITOR.ui.dialog.uiElement, /** * @lends CKEDITOR.ui.dialog.hbox.prototype */ { /** * Gets a child UI element inside this container. * @param {Array|Number} indices An array or a single number to indicate the child's * position in the container's descendant tree. Omit to get all the children in an array. * @returns {Array|CKEDITOR.ui.dialog.uiElement} Array of all UI elements in the container * if no argument given, or the specified UI element if indices is given. * @example * var checkbox = hbox.getChild( [0,1] ); * checkbox.setValue( true ); */ getChild : function( indices ) { // If no arguments, return a clone of the children array. if ( arguments.length < 1 ) return this._.children.concat(); // If indices isn't array, make it one. if ( !indices.splice ) indices = [ indices ]; // Retrieve the child element according to tree position. if ( indices.length < 2 ) return this._.children[ indices[0] ]; else return ( this._.children[ indices[0] ] && this._.children[ indices[0] ].getChild ) ? this._.children[ indices[0] ].getChild( indices.slice( 1, indices.length ) ) : null; } }, true ); CKEDITOR.ui.dialog.vbox.prototype = new CKEDITOR.ui.dialog.hbox(); (function() { var commonBuilder = { build : function( dialog, elementDefinition, output ) { var children = elementDefinition.children, child, childHtmlList = [], childObjList = []; for ( var i = 0 ; ( i < children.length && ( child = children[i] ) ) ; i++ ) { var childHtml = []; childHtmlList.push( childHtml ); childObjList.push( CKEDITOR.dialog._.uiElementBuilders[ child.type ].build( dialog, child, childHtml ) ); } return new CKEDITOR.ui.dialog[elementDefinition.type]( dialog, childObjList, childHtmlList, output, elementDefinition ); } }; CKEDITOR.dialog.addUIElement( 'hbox', commonBuilder ); CKEDITOR.dialog.addUIElement( 'vbox', commonBuilder ); })(); /** * Generic dialog command. It opens a specific dialog when executed. * @constructor * @augments CKEDITOR.commandDefinition * @param {string} dialogName The name of the dialog to open when executing * this command. * @example * // Register the "link" command, which opens the "link" dialog. * editor.addCommand( 'link', <b>new CKEDITOR.dialogCommand( 'link' )</b> ); */ CKEDITOR.dialogCommand = function( dialogName ) { this.dialogName = dialogName; }; CKEDITOR.dialogCommand.prototype = { /** @ignore */ exec : function( editor ) { // Special treatment for Opera. (#8031) CKEDITOR.env.opera ? CKEDITOR.tools.setTimeout( function() { editor.openDialog( this.dialogName ) }, 0, this ) : editor.openDialog( this.dialogName ); }, // Dialog commands just open a dialog ui, thus require no undo logic, // undo support should dedicate to specific dialog implementation. canUndo: false, editorFocus : CKEDITOR.env.ie || CKEDITOR.env.webkit }; (function() { var notEmptyRegex = /^([a]|[^a])+$/, integerRegex = /^\d*$/, numberRegex = /^\d*(?:\.\d+)?$/, htmlLengthRegex = /^(((\d*(\.\d+))|(\d*))(px|\%)?)?$/, cssLengthRegex = /^(((\d*(\.\d+))|(\d*))(px|em|ex|in|cm|mm|pt|pc|\%)?)?$/i, inlineStyleRegex = /^(\s*[\w-]+\s*:\s*[^:;]+(?:;|$))*$/; CKEDITOR.VALIDATE_OR = 1; CKEDITOR.VALIDATE_AND = 2; CKEDITOR.dialog.validate = { functions : function() { var args = arguments; return function() { /** * It's important for validate functions to be able to accept the value * as argument in addition to this.getValue(), so that it is possible to * combine validate functions together to make more sophisticated * validators. */ var value = this && this.getValue ? this.getValue() : args[ 0 ]; var msg = undefined, relation = CKEDITOR.VALIDATE_AND, functions = [], i; for ( i = 0 ; i < args.length ; i++ ) { if ( typeof( args[i] ) == 'function' ) functions.push( args[i] ); else break; } if ( i < args.length && typeof( args[i] ) == 'string' ) { msg = args[i]; i++; } if ( i < args.length && typeof( args[i]) == 'number' ) relation = args[i]; var passed = ( relation == CKEDITOR.VALIDATE_AND ? true : false ); for ( i = 0 ; i < functions.length ; i++ ) { if ( relation == CKEDITOR.VALIDATE_AND ) passed = passed && functions[i]( value ); else passed = passed || functions[i]( value ); } return !passed ? msg : true; }; }, regex : function( regex, msg ) { /* * Can be greatly shortened by deriving from functions validator if code size * turns out to be more important than performance. */ return function() { var value = this && this.getValue ? this.getValue() : arguments[0]; return !regex.test( value ) ? msg : true; }; }, notEmpty : function( msg ) { return this.regex( notEmptyRegex, msg ); }, integer : function( msg ) { return this.regex( integerRegex, msg ); }, 'number' : function( msg ) { return this.regex( numberRegex, msg ); }, 'cssLength' : function( msg ) { return this.functions( function( val ){ return cssLengthRegex.test( CKEDITOR.tools.trim( val ) ); }, msg ); }, 'htmlLength' : function( msg ) { return this.functions( function( val ){ return htmlLengthRegex.test( CKEDITOR.tools.trim( val ) ); }, msg ); }, 'inlineStyle' : function( msg ) { return this.functions( function( val ){ return inlineStyleRegex.test( CKEDITOR.tools.trim( val ) ); }, msg ); }, equals : function( value, msg ) { return this.functions( function( val ){ return val == value; }, msg ); }, notEqual : function( value, msg ) { return this.functions( function( val ){ return val != value; }, msg ); } }; CKEDITOR.on( 'instanceDestroyed', function( evt ) { // Remove dialog cover on last instance destroy. if ( CKEDITOR.tools.isEmpty( CKEDITOR.instances ) ) { var currentTopDialog; while ( ( currentTopDialog = CKEDITOR.dialog._.currentTop ) ) currentTopDialog.hide(); removeCovers(); } var dialogs = evt.editor._.storedDialogs; for ( var name in dialogs ) dialogs[ name ].destroy(); }); })(); // Extend the CKEDITOR.editor class with dialog specific functions. CKEDITOR.tools.extend( CKEDITOR.editor.prototype, /** @lends CKEDITOR.editor.prototype */ { /** * Loads and opens a registered dialog. * @param {String} dialogName The registered name of the dialog. * @param {Function} callback The function to be invoked after dialog instance created. * @see CKEDITOR.dialog.add * @example * CKEDITOR.instances.editor1.openDialog( 'smiley' ); * @returns {CKEDITOR.dialog} The dialog object corresponding to the dialog displayed. null if the dialog name is not registered. */ openDialog : function( dialogName, callback ) { if ( this.mode == 'wysiwyg' && CKEDITOR.env.ie ) { var selection = this.getSelection(); selection && selection.lock(); } var dialogDefinitions = CKEDITOR.dialog._.dialogDefinitions[ dialogName ], dialogSkin = this.skin.dialog; if ( CKEDITOR.dialog._.currentTop === null ) showCover( this ); // If the dialogDefinition is already loaded, open it immediately. if ( typeof dialogDefinitions == 'function' && dialogSkin._isLoaded ) { var storedDialogs = this._.storedDialogs || ( this._.storedDialogs = {} ); var dialog = storedDialogs[ dialogName ] || ( storedDialogs[ dialogName ] = new CKEDITOR.dialog( this, dialogName ) ); callback && callback.call( dialog, dialog ); dialog.show(); return dialog; } else if ( dialogDefinitions == 'failed' ) { hideCover(); throw new Error( '[CKEDITOR.dialog.openDialog] Dialog "' + dialogName + '" failed when loading definition.' ); } var me = this; function onDialogFileLoaded( success ) { var dialogDefinition = CKEDITOR.dialog._.dialogDefinitions[ dialogName ], skin = me.skin.dialog; // Check if both skin part and definition is loaded. if ( !skin._isLoaded || loadDefinition && typeof success == 'undefined' ) return; // In case of plugin error, mark it as loading failed. if ( typeof dialogDefinition != 'function' ) CKEDITOR.dialog._.dialogDefinitions[ dialogName ] = 'failed'; me.openDialog( dialogName, callback ); } if ( typeof dialogDefinitions == 'string' ) { var loadDefinition = 1; CKEDITOR.scriptLoader.load( CKEDITOR.getUrl( dialogDefinitions ), onDialogFileLoaded, null, 0, 1 ); } CKEDITOR.skins.load( this, 'dialog', onDialogFileLoaded ); return null; } }); })(); CKEDITOR.plugins.add( 'dialog', { requires : [ 'dialogui' ] }); // Dialog related configurations. /** * The color of the dialog background cover. It should be a valid CSS color * string. * @name CKEDITOR.config.dialog_backgroundCoverColor * @type String * @default 'white' * @example * config.dialog_backgroundCoverColor = 'rgb(255, 254, 253)'; */ /** * The opacity of the dialog background cover. It should be a number within the * range [0.0, 1.0]. * @name CKEDITOR.config.dialog_backgroundCoverOpacity * @type Number * @default 0.5 * @example * config.dialog_backgroundCoverOpacity = 0.7; */ /** * If the dialog has more than one tab, put focus into the first tab as soon as dialog is opened. * @name CKEDITOR.config.dialog_startupFocusTab * @type Boolean * @default false * @example * config.dialog_startupFocusTab = true; */ /** * The distance of magnetic borders used in moving and resizing dialogs, * measured in pixels. * @name CKEDITOR.config.dialog_magnetDistance * @type Number * @default 20 * @example * config.dialog_magnetDistance = 30; */ /** * The guideline to follow when generating the dialog buttons. There are 3 possible options: * <ul> * <li>'OS' - the buttons will be displayed in the default order of the user's OS;</li> * <li>'ltr' - for Left-To-Right order;</li> * <li>'rtl' - for Right-To-Left order.</li> * </ul> * @name CKEDITOR.config.dialog_buttonsOrder * @type String * @default 'OS' * @since 3.5 * @example * config.dialog_buttonsOrder = 'rtl'; */ /** * The dialog contents to removed. It's a string composed by dialog name and tab name with a colon between them. * Separate each pair with semicolon (see example). * <b>Note: All names are case-sensitive.</b> * <b>Note: Be cautious when specifying dialog tabs that are mandatory, like "info", dialog functionality might be broken because of this!</b> * @name CKEDITOR.config.removeDialogTabs * @type String * @since 3.5 * @default '' * @example * config.removeDialogTabs = 'flash:advanced;image:Link'; */ /** * Fired when a dialog definition is about to be used to create a dialog into * an editor instance. This event makes it possible to customize the definition * before creating it. * <p>Note that this event is called only the first time a specific dialog is * opened. Successive openings will use the cached dialog, and this event will * not get fired.</p> * @name CKEDITOR#dialogDefinition * @event * @param {CKEDITOR.dialog.definition} data The dialog defination that * is being loaded. * @param {CKEDITOR.editor} editor The editor instance that will use the * dialog. */ /** * Fired when a tab is going to be selected in a dialog * @name CKEDITOR.dialog#selectPage * @event * @param {String} page The id of the page that it's gonna be selected. * @param {String} currentPage The id of the current page. */ /** * Fired when the user tries to dismiss a dialog * @name CKEDITOR.dialog#cancel * @event * @param {Boolean} hide Whether the event should proceed or not. */ /** * Fired when the user tries to confirm a dialog * @name CKEDITOR.dialog#ok * @event * @param {Boolean} hide Whether the event should proceed or not. */ /** * Fired when a dialog is shown * @name CKEDITOR.dialog#show * @event */ /** * Fired when a dialog is shown * @name CKEDITOR.editor#dialogShow * @event */ /** * Fired when a dialog is hidden * @name CKEDITOR.dialog#hide * @event */ /** * Fired when a dialog is hidden * @name CKEDITOR.editor#dialogHide * @event */ /** * Fired when a dialog is being resized. The event is fired on * both the 'CKEDITOR.dialog' object and the dialog instance * since 3.5.3, previously it's available only in the global object. * @name CKEDITOR.dialog#resize * @since 3.5 * @event * @param {CKEDITOR.dialog} dialog The dialog being resized (if * it's fired on the dialog itself, this parameter isn't sent). * @param {String} skin The skin name. * @param {Number} width The new width. * @param {Number} height The new height. */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview The "showblocks" plugin. Enable it will make all block level * elements being decorated with a border and the element name * displayed on the left-right corner. */ (function() { var cssTemplate = '.%2 p,'+ '.%2 div,'+ '.%2 pre,'+ '.%2 address,'+ '.%2 blockquote,'+ '.%2 h1,'+ '.%2 h2,'+ '.%2 h3,'+ '.%2 h4,'+ '.%2 h5,'+ '.%2 h6'+ '{'+ 'background-repeat: no-repeat;'+ 'background-position: top %3;'+ 'border: 1px dotted gray;'+ 'padding-top: 8px;'+ 'padding-%3: 8px;'+ '}'+ '.%2 p'+ '{'+ '%1p.png);'+ '}'+ '.%2 div'+ '{'+ '%1div.png);'+ '}'+ '.%2 pre'+ '{'+ '%1pre.png);'+ '}'+ '.%2 address'+ '{'+ '%1address.png);'+ '}'+ '.%2 blockquote'+ '{'+ '%1blockquote.png);'+ '}'+ '.%2 h1'+ '{'+ '%1h1.png);'+ '}'+ '.%2 h2'+ '{'+ '%1h2.png);'+ '}'+ '.%2 h3'+ '{'+ '%1h3.png);'+ '}'+ '.%2 h4'+ '{'+ '%1h4.png);'+ '}'+ '.%2 h5'+ '{'+ '%1h5.png);'+ '}'+ '.%2 h6'+ '{'+ '%1h6.png);'+ '}'; var cssTemplateRegex = /%1/g, cssClassRegex = /%2/g, backgroundPositionRegex = /%3/g; var commandDefinition = { readOnly : 1, preserveState : true, editorFocus : false, exec : function ( editor ) { this.toggleState(); this.refresh( editor ); }, refresh : function( editor ) { if ( editor.document ) { var funcName = ( this.state == CKEDITOR.TRISTATE_ON ) ? 'addClass' : 'removeClass'; editor.document.getBody()[ funcName ]( 'cke_show_blocks' ); } } }; CKEDITOR.plugins.add( 'showblocks', { requires : [ 'wysiwygarea' ], init : function( editor ) { var command = editor.addCommand( 'showblocks', commandDefinition ); command.canUndo = false; if ( editor.config.startupOutlineBlocks ) command.setState( CKEDITOR.TRISTATE_ON ); editor.addCss( cssTemplate .replace( cssTemplateRegex, 'background-image: url(' + CKEDITOR.getUrl( this.path ) + 'images/block_' ) .replace( cssClassRegex, 'cke_show_blocks ' ) .replace( backgroundPositionRegex, editor.lang.dir == 'rtl' ? 'right' : 'left' ) ); editor.ui.addButton( 'ShowBlocks', { label : editor.lang.showBlocks, command : 'showblocks' }); // Refresh the command on setData. editor.on( 'mode', function() { if ( command.state != CKEDITOR.TRISTATE_DISABLED ) command.refresh( editor ); }); // Refresh the command on setData. editor.on( 'contentDom', function() { if ( command.state != CKEDITOR.TRISTATE_DISABLED ) command.refresh( editor ); }); } }); } )(); /** * Whether to automaticaly enable the "show block" command when the editor * loads. (StartupShowBlocks in FCKeditor) * @name CKEDITOR.config.startupOutlineBlocks * @type Boolean * @default false * @example * config.startupOutlineBlocks = true; */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @stylesheetParser plugin. */ (function() { // We want to extract only the elements with classes defined in the stylesheets: function parseClasses( aRules, skipSelectors, validSelectors ) { // aRules are just the different rules in the style sheets // We want to merge them and them split them by commas, so we end up with only // the selectors var s = aRules.join(' '); // Remove selectors splitting the elements, leave only the class selector (.) s = s.replace( /(,|>|\+|~)/g, ' ' ); // Remove attribute selectors: table[border="0"] s = s.replace( /\[[^\]]*/g, '' ); // Remove Ids: div#main s = s.replace( /#[^\s]*/g, '' ); // Remove pseudo-selectors and pseudo-elements: :hover :nth-child(2n+1) ::before s = s.replace( /\:{1,2}[^\s]*/g, '' ); s = s.replace( /\s+/g, ' ' ); var aSelectors = s.split( ' ' ), aClasses = []; for ( var i = 0; i < aSelectors.length ; i++ ) { var selector = aSelectors[ i ]; if ( validSelectors.test( selector ) && !skipSelectors.test( selector ) ) { // If we still don't know about this one, add it if ( CKEDITOR.tools.indexOf( aClasses, selector ) == -1 ) aClasses.push( selector ); } } return aClasses; } function LoadStylesCSS( theDoc, skipSelectors, validSelectors ) { var styles = [], // It will hold all the rules of the applied stylesheets (except those internal to CKEditor) aRules = [], i; for ( i = 0; i < theDoc.styleSheets.length; i++ ) { var sheet = theDoc.styleSheets[ i ], node = sheet.ownerNode || sheet.owningElement; // Skip the internal stylesheets if ( node.getAttribute( 'data-cke-temp' ) ) continue; // Exclude stylesheets injected by extensions if ( sheet.href && sheet.href.substr(0, 9) == 'chrome://' ) continue; var sheetRules = sheet.cssRules || sheet.rules; for ( var j = 0; j < sheetRules.length; j++ ) aRules.push( sheetRules[ j ].selectorText ); } var aClasses = parseClasses( aRules, skipSelectors, validSelectors ); // Add each style to our "Styles" collection. for ( i = 0; i < aClasses.length; i++ ) { var oElement = aClasses[ i ].split( '.' ), element = oElement[ 0 ].toLowerCase(), sClassName = oElement[ 1 ]; styles.push( { name : element + '.' + sClassName, element : element, attributes : {'class' : sClassName} }); } return styles; } // Register a plugin named "stylesheetparser". CKEDITOR.plugins.add( 'stylesheetparser', { requires: [ 'styles' ], onLoad : function() { var obj = CKEDITOR.editor.prototype; obj.getStylesSet = CKEDITOR.tools.override( obj.getStylesSet, function( org ) { return function( callback ) { var self = this; org.call( this, function( definitions ) { // Rules that must be skipped var skipSelectors = self.config.stylesheetParser_skipSelectors || ( /(^body\.|^\.)/i ), // Rules that are valid validSelectors = self.config.stylesheetParser_validSelectors || ( /\w+\.\w+/ ); callback( ( self._.stylesDefinitions = definitions.concat( LoadStylesCSS( self.document.$, skipSelectors, validSelectors ) ) ) ); }); }; }); } }); })(); /** * A regular expression that defines whether a CSS rule will be * skipped by the Stylesheet Parser plugin. A CSS rule matching * the regular expression will be ignored and will not be available * in the Styles drop-down list. * @name CKEDITOR.config.stylesheetParser_skipSelectors * @type RegExp * @default /(^body\.|^\.)/i * @since 3.6 * @see CKEDITOR.config.stylesheetParser_validSelectors * @example * // Ignore rules for body and caption elements, classes starting with "high", and any class defined for no specific element. * config.stylesheetParser_skipSelectors = /(^body\.|^caption\.|\.high|^\.)/i; */ /** * A regular expression that defines which CSS rules will be used * by the Stylesheet Parser plugin. A CSS rule matching the regular * expression will be available in the Styles drop-down list. * @name CKEDITOR.config.stylesheetParser_validSelectors * @type RegExp * @default /\w+\.\w+/ * @since 3.6 * @see CKEDITOR.config.stylesheetParser_skipSelectors * @example * // Only add rules for p and span elements. * config.stylesheetParser_validSelectors = /\^(p|span)\.\w+/; */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** @fileoverview The "dialogui" plugin. */ CKEDITOR.plugins.add( 'dialogui' ); (function() { var initPrivateObject = function( elementDefinition ) { this._ || ( this._ = {} ); this._['default'] = this._.initValue = elementDefinition['default'] || ''; this._.required = elementDefinition[ 'required' ] || false; var args = [ this._ ]; for ( var i = 1 ; i < arguments.length ; i++ ) args.push( arguments[i] ); args.push( true ); CKEDITOR.tools.extend.apply( CKEDITOR.tools, args ); return this._; }, textBuilder = { build : function( dialog, elementDefinition, output ) { return new CKEDITOR.ui.dialog.textInput( dialog, elementDefinition, output ); } }, commonBuilder = { build : function( dialog, elementDefinition, output ) { return new CKEDITOR.ui.dialog[elementDefinition.type]( dialog, elementDefinition, output ); } }, containerBuilder = { build : function( dialog, elementDefinition, output ) { var children = elementDefinition.children, child, childHtmlList = [], childObjList = []; for ( var i = 0 ; ( i < children.length && ( child = children[i] ) ) ; i++ ) { var childHtml = []; childHtmlList.push( childHtml ); childObjList.push( CKEDITOR.dialog._.uiElementBuilders[ child.type ].build( dialog, child, childHtml ) ); } return new CKEDITOR.ui.dialog[ elementDefinition.type ]( dialog, childObjList, childHtmlList, output, elementDefinition ); } }, commonPrototype = { isChanged : function() { return this.getValue() != this.getInitValue(); }, reset : function( noChangeEvent ) { this.setValue( this.getInitValue(), noChangeEvent ); }, setInitValue : function() { this._.initValue = this.getValue(); }, resetInitValue : function() { this._.initValue = this._['default']; }, getInitValue : function() { return this._.initValue; } }, commonEventProcessors = CKEDITOR.tools.extend( {}, CKEDITOR.ui.dialog.uiElement.prototype.eventProcessors, { onChange : function( dialog, func ) { if ( !this._.domOnChangeRegistered ) { dialog.on( 'load', function() { this.getInputElement().on( 'change', function() { // Make sure 'onchange' doesn't get fired after dialog closed. (#5719) if ( !dialog.parts.dialog.isVisible() ) return; this.fire( 'change', { value : this.getValue() } ); }, this ); }, this ); this._.domOnChangeRegistered = true; } this.on( 'change', func ); } }, true ), eventRegex = /^on([A-Z]\w+)/, cleanInnerDefinition = function( def ) { // An inner UI element should not have the parent's type, title or events. for ( var i in def ) { if ( eventRegex.test( i ) || i == 'title' || i == 'type' ) delete def[i]; } return def; }; CKEDITOR.tools.extend( CKEDITOR.ui.dialog, /** @lends CKEDITOR.ui.dialog */ { /** * Base class for all dialog elements with a textual label on the left. * @constructor * @example * @extends CKEDITOR.ui.dialog.uiElement * @param {CKEDITOR.dialog} dialog * Parent dialog object. * @param {CKEDITOR.dialog.definition.uiElement} elementDefinition * The element definition. Accepted fields: * <ul> * <li><strong>label</strong> (Required) The label string.</li> * <li><strong>labelLayout</strong> (Optional) Put 'horizontal' here if the * label element is to be layed out horizontally. Otherwise a vertical * layout will be used.</li> * <li><strong>widths</strong> (Optional) This applies only for horizontal * layouts - an 2-element array of lengths to specify the widths of the * label and the content element.</li> * </ul> * @param {Array} htmlList * List of HTML code to output to. * @param {Function} contentHtml * A function returning the HTML code string to be added inside the content * cell. */ labeledElement : function( dialog, elementDefinition, htmlList, contentHtml ) { if ( arguments.length < 4 ) return; var _ = initPrivateObject.call( this, elementDefinition ); _.labelId = CKEDITOR.tools.getNextId() + '_label'; var children = this._.children = []; /** @ignore */ var innerHTML = function() { var html = [], requiredClass = elementDefinition.required ? ' cke_required' : '' ; if ( elementDefinition.labelLayout != 'horizontal' ) html.push( '<label class="cke_dialog_ui_labeled_label' + requiredClass + '" ', ' id="'+ _.labelId + '"', ' for="' + _.inputId + '"', ( elementDefinition.labelStyle ? ' style="' + elementDefinition.labelStyle + '"' : '' ) +'>', elementDefinition.label, '</label>', '<div class="cke_dialog_ui_labeled_content"' + ( elementDefinition.controlStyle ? ' style="' + elementDefinition.controlStyle + '"' : '' ) + ' role="presentation">', contentHtml.call( this, dialog, elementDefinition ), '</div>' ); else { var hboxDefinition = { type : 'hbox', widths : elementDefinition.widths, padding : 0, children : [ { type : 'html', html : '<label class="cke_dialog_ui_labeled_label' + requiredClass + '"' + ' id="' + _.labelId + '"' + ' for="' + _.inputId + '"' + ( elementDefinition.labelStyle ? ' style="' + elementDefinition.labelStyle + '"' : '' ) +'>' + CKEDITOR.tools.htmlEncode( elementDefinition.label ) + '</span>' }, { type : 'html', html : '<span class="cke_dialog_ui_labeled_content"' + ( elementDefinition.controlStyle ? ' style="' + elementDefinition.controlStyle + '"' : '' ) + '>' + contentHtml.call( this, dialog, elementDefinition ) + '</span>' } ] }; CKEDITOR.dialog._.uiElementBuilders.hbox.build( dialog, hboxDefinition, html ); } return html.join( '' ); }; CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition, htmlList, 'div', null, { role : 'presentation' }, innerHTML ); }, /** * A text input with a label. This UI element class represents both the * single-line text inputs and password inputs in dialog boxes. * @constructor * @example * @extends CKEDITOR.ui.dialog.labeledElement * @param {CKEDITOR.dialog} dialog * Parent dialog object. * @param {CKEDITOR.dialog.definition.uiElement} elementDefinition * The element definition. Accepted fields: * <ul> * <li><strong>default</strong> (Optional) The default value.</li> * <li><strong>validate</strong> (Optional) The validation function. </li> * <li><strong>maxLength</strong> (Optional) The maximum length of text box * contents.</li> * <li><strong>size</strong> (Optional) The size of the text box. This is * usually overridden by the size defined by the skin, however.</li> * </ul> * @param {Array} htmlList * List of HTML code to output to. */ textInput : function( dialog, elementDefinition, htmlList ) { if ( arguments.length < 3 ) return; initPrivateObject.call( this, elementDefinition ); var domId = this._.inputId = CKEDITOR.tools.getNextId() + '_textInput', attributes = { 'class' : 'cke_dialog_ui_input_' + elementDefinition.type, id : domId, type : 'text' }, i; // Set the validator, if any. if ( elementDefinition.validate ) this.validate = elementDefinition.validate; // Set the max length and size. if ( elementDefinition.maxLength ) attributes.maxlength = elementDefinition.maxLength; if ( elementDefinition.size ) attributes.size = elementDefinition.size; if ( elementDefinition.inputStyle ) attributes.style = elementDefinition.inputStyle; // If user presses Enter in a text box, it implies clicking OK for the dialog. var me = this, keyPressedOnMe = false; dialog.on( 'load', function() { me.getInputElement().on( 'keydown', function( evt ) { if ( evt.data.getKeystroke() == 13 ) keyPressedOnMe = true; } ); // Lower the priority this 'keyup' since 'ok' will close the dialog.(#3749) me.getInputElement().on( 'keyup', function( evt ) { if ( evt.data.getKeystroke() == 13 && keyPressedOnMe ) { dialog.getButton( 'ok' ) && setTimeout( function () { dialog.getButton( 'ok' ).click(); }, 0 ); keyPressedOnMe = false; } }, null, null, 1000 ); } ); /** @ignore */ var innerHTML = function() { // IE BUG: Text input fields in IE at 100% would exceed a <td> or inline // container's width, so need to wrap it inside a <div>. var html = [ '<div class="cke_dialog_ui_input_', elementDefinition.type, '" role="presentation"' ]; if ( elementDefinition.width ) html.push( 'style="width:'+ elementDefinition.width +'" ' ); html.push( '><input ' ); attributes[ 'aria-labelledby' ] = this._.labelId; this._.required && ( attributes[ 'aria-required' ] = this._.required ); for ( var i in attributes ) html.push( i + '="' + attributes[i] + '" ' ); html.push( ' /></div>' ); return html.join( '' ); }; CKEDITOR.ui.dialog.labeledElement.call( this, dialog, elementDefinition, htmlList, innerHTML ); }, /** * A text area with a label on the top or left. * @constructor * @extends CKEDITOR.ui.dialog.labeledElement * @example * @param {CKEDITOR.dialog} dialog * Parent dialog object. * @param {CKEDITOR.dialog.definition.uiElement} elementDefinition * The element definition. Accepted fields: * <ul> * <li><strong>rows</strong> (Optional) The number of rows displayed. * Defaults to 5 if not defined.</li> * <li><strong>cols</strong> (Optional) The number of cols displayed. * Defaults to 20 if not defined. Usually overridden by skins.</li> * <li><strong>default</strong> (Optional) The default value.</li> * <li><strong>validate</strong> (Optional) The validation function. </li> * </ul> * @param {Array} htmlList * List of HTML code to output to. */ textarea : function( dialog, elementDefinition, htmlList ) { if ( arguments.length < 3 ) return; initPrivateObject.call( this, elementDefinition ); var me = this, domId = this._.inputId = CKEDITOR.tools.getNextId() + '_textarea', attributes = {}; if ( elementDefinition.validate ) this.validate = elementDefinition.validate; // Generates the essential attributes for the textarea tag. attributes.rows = elementDefinition.rows || 5; attributes.cols = elementDefinition.cols || 20; if ( typeof elementDefinition.inputStyle != 'undefined' ) attributes.style = elementDefinition.inputStyle; /** @ignore */ var innerHTML = function() { attributes[ 'aria-labelledby' ] = this._.labelId; this._.required && ( attributes[ 'aria-required' ] = this._.required ); var html = [ '<div class="cke_dialog_ui_input_textarea" role="presentation"><textarea class="cke_dialog_ui_input_textarea" id="', domId, '" ' ]; for ( var i in attributes ) html.push( i + '="' + CKEDITOR.tools.htmlEncode( attributes[i] ) + '" ' ); html.push( '>', CKEDITOR.tools.htmlEncode( me._['default'] ), '</textarea></div>' ); return html.join( '' ); }; CKEDITOR.ui.dialog.labeledElement.call( this, dialog, elementDefinition, htmlList, innerHTML ); }, /** * A single checkbox with a label on the right. * @constructor * @extends CKEDITOR.ui.dialog.uiElement * @example * @param {CKEDITOR.dialog} dialog * Parent dialog object. * @param {CKEDITOR.dialog.definition.uiElement} elementDefinition * The element definition. Accepted fields: * <ul> * <li><strong>checked</strong> (Optional) Whether the checkbox is checked * on instantiation. Defaults to false.</li> * <li><strong>validate</strong> (Optional) The validation function.</li> * <li><strong>label</strong> (Optional) The checkbox label.</li> * </ul> * @param {Array} htmlList * List of HTML code to output to. */ checkbox : function( dialog, elementDefinition, htmlList ) { if ( arguments.length < 3 ) return; var _ = initPrivateObject.call( this, elementDefinition, { 'default' : !!elementDefinition[ 'default' ] } ); if ( elementDefinition.validate ) this.validate = elementDefinition.validate; /** @ignore */ var innerHTML = function() { var myDefinition = CKEDITOR.tools.extend( {}, elementDefinition, { id : elementDefinition.id ? elementDefinition.id + '_checkbox' : CKEDITOR.tools.getNextId() + '_checkbox' }, true ), html = []; var labelId = CKEDITOR.tools.getNextId() + '_label'; var attributes = { 'class' : 'cke_dialog_ui_checkbox_input', type : 'checkbox', 'aria-labelledby' : labelId }; cleanInnerDefinition( myDefinition ); if ( elementDefinition[ 'default' ] ) attributes.checked = 'checked'; if ( typeof myDefinition.inputStyle != 'undefined' ) myDefinition.style = myDefinition.inputStyle; _.checkbox = new CKEDITOR.ui.dialog.uiElement( dialog, myDefinition, html, 'input', null, attributes ); html.push( ' <label id="', labelId, '" for="', attributes.id, '"' + ( elementDefinition.labelStyle ? ' style="' + elementDefinition.labelStyle + '"' : '' ) + '>', CKEDITOR.tools.htmlEncode( elementDefinition.label ), '</label>' ); return html.join( '' ); }; CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition, htmlList, 'span', null, null, innerHTML ); }, /** * A group of radio buttons. * @constructor * @example * @extends CKEDITOR.ui.dialog.labeledElement * @param {CKEDITOR.dialog} dialog * Parent dialog object. * @param {CKEDITOR.dialog.definition.uiElement} elementDefinition * The element definition. Accepted fields: * <ul> * <li><strong>default</strong> (Required) The default value.</li> * <li><strong>validate</strong> (Optional) The validation function.</li> * <li><strong>items</strong> (Required) An array of options. Each option * is a 1- or 2-item array of format [ 'Description', 'Value' ]. If 'Value' * is missing, then the value would be assumed to be the same as the * description.</li> * </ul> * @param {Array} htmlList * List of HTML code to output to. */ radio : function( dialog, elementDefinition, htmlList ) { if ( arguments.length < 3) return; initPrivateObject.call( this, elementDefinition ); if ( !this._['default'] ) this._['default'] = this._.initValue = elementDefinition.items[0][1]; if ( elementDefinition.validate ) this.validate = elementDefinition.valdiate; var children = [], me = this; /** @ignore */ var innerHTML = function() { var inputHtmlList = [], html = [], commonAttributes = { 'class' : 'cke_dialog_ui_radio_item', 'aria-labelledby' : this._.labelId }, commonName = elementDefinition.id ? elementDefinition.id + '_radio' : CKEDITOR.tools.getNextId() + '_radio'; for ( var i = 0 ; i < elementDefinition.items.length ; i++ ) { var item = elementDefinition.items[i], title = item[2] !== undefined ? item[2] : item[0], value = item[1] !== undefined ? item[1] : item[0], inputId = CKEDITOR.tools.getNextId() + '_radio_input', labelId = inputId + '_label', inputDefinition = CKEDITOR.tools.extend( {}, elementDefinition, { id : inputId, title : null, type : null }, true ), labelDefinition = CKEDITOR.tools.extend( {}, inputDefinition, { title : title }, true ), inputAttributes = { type : 'radio', 'class' : 'cke_dialog_ui_radio_input', name : commonName, value : value, 'aria-labelledby' : labelId }, inputHtml = []; if ( me._['default'] == value ) inputAttributes.checked = 'checked'; cleanInnerDefinition( inputDefinition ); cleanInnerDefinition( labelDefinition ); if ( typeof inputDefinition.inputStyle != 'undefined' ) inputDefinition.style = inputDefinition.inputStyle; children.push( new CKEDITOR.ui.dialog.uiElement( dialog, inputDefinition, inputHtml, 'input', null, inputAttributes ) ); inputHtml.push( ' ' ); new CKEDITOR.ui.dialog.uiElement( dialog, labelDefinition, inputHtml, 'label', null, { id : labelId, 'for' : inputAttributes.id }, item[0] ); inputHtmlList.push( inputHtml.join( '' ) ); } new CKEDITOR.ui.dialog.hbox( dialog, children, inputHtmlList, html ); return html.join( '' ); }; CKEDITOR.ui.dialog.labeledElement.call( this, dialog, elementDefinition, htmlList, innerHTML ); this._.children = children; }, /** * A button with a label inside. * @constructor * @example * @extends CKEDITOR.ui.dialog.uiElement * @param {CKEDITOR.dialog} dialog * Parent dialog object. * @param {CKEDITOR.dialog.definition.uiElement} elementDefinition * The element definition. Accepted fields: * <ul> * <li><strong>label</strong> (Required) The button label.</li> * <li><strong>disabled</strong> (Optional) Set to true if you want the * button to appear in disabled state.</li> * </ul> * @param {Array} htmlList * List of HTML code to output to. */ button : function( dialog, elementDefinition, htmlList ) { if ( !arguments.length ) return; if ( typeof elementDefinition == 'function' ) elementDefinition = elementDefinition( dialog.getParentEditor() ); initPrivateObject.call( this, elementDefinition, { disabled : elementDefinition.disabled || false } ); // Add OnClick event to this input. CKEDITOR.event.implementOn( this ); var me = this; // Register an event handler for processing button clicks. dialog.on( 'load', function( eventInfo ) { var element = this.getElement(); (function() { element.on( 'click', function( evt ) { me.fire( 'click', { dialog : me.getDialog() } ); evt.data.preventDefault(); } ); element.on( 'keydown', function( evt ) { if ( evt.data.getKeystroke() in { 32:1 } ) { me.click(); evt.data.preventDefault(); } } ); })(); element.unselectable(); }, this ); var outerDefinition = CKEDITOR.tools.extend( {}, elementDefinition ); delete outerDefinition.style; var labelId = CKEDITOR.tools.getNextId() + '_label'; CKEDITOR.ui.dialog.uiElement.call( this, dialog, outerDefinition, htmlList, 'a', null, { style : elementDefinition.style, href : 'javascript:void(0)', title : elementDefinition.label, hidefocus : 'true', 'class' : elementDefinition['class'], role : 'button', 'aria-labelledby' : labelId }, '<span id="' + labelId + '" class="cke_dialog_ui_button">' + CKEDITOR.tools.htmlEncode( elementDefinition.label ) + '</span>' ); }, /** * A select box. * @extends CKEDITOR.ui.dialog.uiElement * @example * @constructor * @param {CKEDITOR.dialog} dialog * Parent dialog object. * @param {CKEDITOR.dialog.definition.uiElement} elementDefinition * The element definition. Accepted fields: * <ul> * <li><strong>default</strong> (Required) The default value.</li> * <li><strong>validate</strong> (Optional) The validation function.</li> * <li><strong>items</strong> (Required) An array of options. Each option * is a 1- or 2-item array of format [ 'Description', 'Value' ]. If 'Value' * is missing, then the value would be assumed to be the same as the * description.</li> * <li><strong>multiple</strong> (Optional) Set this to true if you'd like * to have a multiple-choice select box.</li> * <li><strong>size</strong> (Optional) The number of items to display in * the select box.</li> * </ul> * @param {Array} htmlList * List of HTML code to output to. */ select : function( dialog, elementDefinition, htmlList ) { if ( arguments.length < 3 ) return; var _ = initPrivateObject.call( this, elementDefinition ); if ( elementDefinition.validate ) this.validate = elementDefinition.validate; _.inputId = CKEDITOR.tools.getNextId() + '_select'; /** @ignore */ var innerHTML = function() { var myDefinition = CKEDITOR.tools.extend( {}, elementDefinition, { id : elementDefinition.id ? elementDefinition.id + '_select' : CKEDITOR.tools.getNextId() + '_select' }, true ), html = [], innerHTML = [], attributes = { 'id' : _.inputId, 'class' : 'cke_dialog_ui_input_select', 'aria-labelledby' : this._.labelId }; // Add multiple and size attributes from element definition. if ( elementDefinition.size != undefined ) attributes.size = elementDefinition.size; if ( elementDefinition.multiple != undefined ) attributes.multiple = elementDefinition.multiple; cleanInnerDefinition( myDefinition ); for ( var i = 0, item ; i < elementDefinition.items.length && ( item = elementDefinition.items[i] ) ; i++ ) { innerHTML.push( '<option value="', CKEDITOR.tools.htmlEncode( item[1] !== undefined ? item[1] : item[0] ).replace( /"/g, '&quot;' ), '" /> ', CKEDITOR.tools.htmlEncode( item[0] ) ); } if ( typeof myDefinition.inputStyle != 'undefined' ) myDefinition.style = myDefinition.inputStyle; _.select = new CKEDITOR.ui.dialog.uiElement( dialog, myDefinition, html, 'select', null, attributes, innerHTML.join( '' ) ); return html.join( '' ); }; CKEDITOR.ui.dialog.labeledElement.call( this, dialog, elementDefinition, htmlList, innerHTML ); }, /** * A file upload input. * @extends CKEDITOR.ui.dialog.labeledElement * @example * @constructor * @param {CKEDITOR.dialog} dialog * Parent dialog object. * @param {CKEDITOR.dialog.definition.uiElement} elementDefinition * The element definition. Accepted fields: * <ul> * <li><strong>validate</strong> (Optional) The validation function.</li> * </ul> * @param {Array} htmlList * List of HTML code to output to. */ file : function( dialog, elementDefinition, htmlList ) { if ( arguments.length < 3 ) return; if ( elementDefinition['default'] === undefined ) elementDefinition['default'] = ''; var _ = CKEDITOR.tools.extend( initPrivateObject.call( this, elementDefinition ), { definition : elementDefinition, buttons : [] } ); if ( elementDefinition.validate ) this.validate = elementDefinition.validate; /** @ignore */ var innerHTML = function() { _.frameId = CKEDITOR.tools.getNextId() + '_fileInput'; // Support for custom document.domain in IE. var isCustomDomain = CKEDITOR.env.isCustomDomain(); var html = [ '<iframe' + ' frameborder="0"' + ' allowtransparency="0"' + ' class="cke_dialog_ui_input_file"' + ' id="', _.frameId, '"' + ' title="', elementDefinition.label, '"' + ' src="javascript:void(' ]; html.push( isCustomDomain ? '(function(){' + 'document.open();' + 'document.domain=\'' + document.domain + '\';' + 'document.close();' + '})()' : '0' ); html.push( ')">' + '</iframe>' ); return html.join( '' ); }; // IE BUG: Parent container does not resize to contain the iframe automatically. dialog.on( 'load', function() { var iframe = CKEDITOR.document.getById( _.frameId ), contentDiv = iframe.getParent(); contentDiv.addClass( 'cke_dialog_ui_input_file' ); } ); CKEDITOR.ui.dialog.labeledElement.call( this, dialog, elementDefinition, htmlList, innerHTML ); }, /** * A button for submitting the file in a file upload input. * @extends CKEDITOR.ui.dialog.button * @example * @constructor * @param {CKEDITOR.dialog} dialog * Parent dialog object. * @param {CKEDITOR.dialog.definition.uiElement} elementDefinition * The element definition. Accepted fields: * <ul> * <li><strong>for</strong> (Required) The file input's page and element Id * to associate to, in a 2-item array format: [ 'page_id', 'element_id' ]. * </li> * <li><strong>validate</strong> (Optional) The validation function.</li> * </ul> * @param {Array} htmlList * List of HTML code to output to. */ fileButton : function( dialog, elementDefinition, htmlList ) { if ( arguments.length < 3 ) return; var _ = initPrivateObject.call( this, elementDefinition ), me = this; if ( elementDefinition.validate ) this.validate = elementDefinition.validate; var myDefinition = CKEDITOR.tools.extend( {}, elementDefinition ); var onClick = myDefinition.onClick; myDefinition.className = ( myDefinition.className ? myDefinition.className + ' ' : '' ) + 'cke_dialog_ui_button'; myDefinition.onClick = function( evt ) { var target = elementDefinition[ 'for' ]; // [ pageId, elementId ] if ( !onClick || onClick.call( this, evt ) !== false ) { dialog.getContentElement( target[0], target[1] ).submit(); this.disable(); } }; dialog.on( 'load', function() { dialog.getContentElement( elementDefinition[ 'for' ][0], elementDefinition[ 'for' ][1] )._.buttons.push( me ); } ); CKEDITOR.ui.dialog.button.call( this, dialog, myDefinition, htmlList ); }, html : (function() { var myHtmlRe = /^\s*<[\w:]+\s+([^>]*)?>/, theirHtmlRe = /^(\s*<[\w:]+(?:\s+[^>]*)?)((?:.|\r|\n)+)$/, emptyTagRe = /\/$/; /** * A dialog element made from raw HTML code. * @extends CKEDITOR.ui.dialog.uiElement * @name CKEDITOR.ui.dialog.html * @param {CKEDITOR.dialog} dialog Parent dialog object. * @param {CKEDITOR.dialog.definition.uiElement} elementDefinition Element definition. * Accepted fields: * <ul> * <li><strong>html</strong> (Required) HTML code of this element.</li> * </ul> * @param {Array} htmlList List of HTML code to be added to the dialog's content area. * @example * @constructor */ return function( dialog, elementDefinition, htmlList ) { if ( arguments.length < 3 ) return; var myHtmlList = [], myHtml, theirHtml = elementDefinition.html, myMatch, theirMatch; // If the HTML input doesn't contain any tags at the beginning, add a <span> tag around it. if ( theirHtml.charAt( 0 ) != '<' ) theirHtml = '<span>' + theirHtml + '</span>'; // Look for focus function in definition. var focus = elementDefinition.focus; if ( focus ) { var oldFocus = this.focus; this.focus = function() { oldFocus.call( this ); typeof focus == 'function' && focus.call( this ); this.fire( 'focus' ); }; if ( elementDefinition.isFocusable ) { var oldIsFocusable = this.isFocusable; this.isFocusable = oldIsFocusable; } this.keyboardFocusable = true; } CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition, myHtmlList, 'span', null, null, '' ); // Append the attributes created by the uiElement call to the real HTML. myHtml = myHtmlList.join( '' ); myMatch = myHtml.match( myHtmlRe ); theirMatch = theirHtml.match( theirHtmlRe ) || [ '', '', '' ]; if ( emptyTagRe.test( theirMatch[1] ) ) { theirMatch[1] = theirMatch[1].slice( 0, -1 ); theirMatch[2] = '/' + theirMatch[2]; } htmlList.push( [ theirMatch[1], ' ', myMatch[1] || '', theirMatch[2] ].join( '' ) ); }; })(), /** * Form fieldset for grouping dialog UI elements. * @constructor * @extends CKEDITOR.ui.dialog.uiElement * @param {CKEDITOR.dialog} dialog Parent dialog object. * @param {Array} childObjList * Array of {@link CKEDITOR.ui.dialog.uiElement} objects inside this * container. * @param {Array} childHtmlList * Array of HTML code that correspond to the HTML output of all the * objects in childObjList. * @param {Array} htmlList * Array of HTML code that this element will output to. * @param {CKEDITOR.dialog.definition.uiElement} elementDefinition * The element definition. Accepted fields: * <ul> * <li><strong>label</strong> (Optional) The legend of the this fieldset.</li> * <li><strong>children</strong> (Required) An array of dialog field definitions which will be grouped inside this fieldset. </li> * </ul> */ fieldset : function( dialog, childObjList, childHtmlList, htmlList, elementDefinition ) { var legendLabel = elementDefinition.label; /** @ignore */ var innerHTML = function() { var html = []; legendLabel && html.push( '<legend>' + legendLabel + '</legend>' ); for ( var i = 0; i < childHtmlList.length; i++ ) html.push( childHtmlList[ i ] ); return html.join( '' ); }; this._ = { children : childObjList }; CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition, htmlList, 'fieldset', null, null, innerHTML ); } }, true ); CKEDITOR.ui.dialog.html.prototype = new CKEDITOR.ui.dialog.uiElement; CKEDITOR.ui.dialog.labeledElement.prototype = CKEDITOR.tools.extend( new CKEDITOR.ui.dialog.uiElement, /** @lends CKEDITOR.ui.dialog.labeledElement.prototype */ { /** * Sets the label text of the element. * @param {String} label The new label text. * @returns {CKEDITOR.ui.dialog.labeledElement} The current labeled element. * @example */ setLabel : function( label ) { var node = CKEDITOR.document.getById( this._.labelId ); if ( node.getChildCount() < 1 ) ( new CKEDITOR.dom.text( label, CKEDITOR.document ) ).appendTo( node ); else node.getChild( 0 ).$.nodeValue = label; return this; }, /** * Retrieves the current label text of the elment. * @returns {String} The current label text. * @example */ getLabel : function() { var node = CKEDITOR.document.getById( this._.labelId ); if ( !node || node.getChildCount() < 1 ) return ''; else return node.getChild( 0 ).getText(); }, /** * Defines the onChange event for UI element definitions. * @field * @type Object * @example */ eventProcessors : commonEventProcessors }, true ); CKEDITOR.ui.dialog.button.prototype = CKEDITOR.tools.extend( new CKEDITOR.ui.dialog.uiElement, /** @lends CKEDITOR.ui.dialog.button.prototype */ { /** * Simulates a click to the button. * @example * @returns {Object} Return value of the 'click' event. */ click : function() { if ( !this._.disabled ) return this.fire( 'click', { dialog : this._.dialog } ); this.getElement().$.blur(); return false; }, /** * Enables the button. * @example */ enable : function() { this._.disabled = false; var element = this.getElement(); element && element.removeClass( 'cke_disabled' ); }, /** * Disables the button. * @example */ disable : function() { this._.disabled = true; this.getElement().addClass( 'cke_disabled' ); }, isVisible : function() { return this.getElement().getFirst().isVisible(); }, isEnabled : function() { return !this._.disabled; }, /** * Defines the onChange event and onClick for button element definitions. * @field * @type Object * @example */ eventProcessors : CKEDITOR.tools.extend( {}, CKEDITOR.ui.dialog.uiElement.prototype.eventProcessors, { /** @ignore */ onClick : function( dialog, func ) { this.on( 'click', func ); } }, true ), /** * Handler for the element's access key up event. Simulates a click to * the button. * @example */ accessKeyUp : function() { this.click(); }, /** * Handler for the element's access key down event. Simulates a mouse * down to the button. * @example */ accessKeyDown : function() { this.focus(); }, keyboardFocusable : true }, true ); CKEDITOR.ui.dialog.textInput.prototype = CKEDITOR.tools.extend( new CKEDITOR.ui.dialog.labeledElement, /** @lends CKEDITOR.ui.dialog.textInput.prototype */ { /** * Gets the text input DOM element under this UI object. * @example * @returns {CKEDITOR.dom.element} The DOM element of the text input. */ getInputElement : function() { return CKEDITOR.document.getById( this._.inputId ); }, /** * Puts focus into the text input. * @example */ focus : function() { var me = this.selectParentTab(); // GECKO BUG: setTimeout() is needed to workaround invisible selections. setTimeout( function() { var element = me.getInputElement(); element && element.$.focus(); }, 0 ); }, /** * Selects all the text in the text input. * @example */ select : function() { var me = this.selectParentTab(); // GECKO BUG: setTimeout() is needed to workaround invisible selections. setTimeout( function() { var e = me.getInputElement(); if ( e ) { e.$.focus(); e.$.select(); } }, 0 ); }, /** * Handler for the text input's access key up event. Makes a select() * call to the text input. * @example */ accessKeyUp : function() { this.select(); }, /** * Sets the value of this text input object. * @param {Object} value The new value. * @returns {CKEDITOR.ui.dialog.textInput} The current UI element. * @example * uiElement.setValue( 'Blamo' ); */ setValue : function( value ) { !value && ( value = '' ); return CKEDITOR.ui.dialog.uiElement.prototype.setValue.apply( this, arguments ); }, keyboardFocusable : true }, commonPrototype, true ); CKEDITOR.ui.dialog.textarea.prototype = new CKEDITOR.ui.dialog.textInput(); CKEDITOR.ui.dialog.select.prototype = CKEDITOR.tools.extend( new CKEDITOR.ui.dialog.labeledElement, /** @lends CKEDITOR.ui.dialog.select.prototype */ { /** * Gets the DOM element of the select box. * @returns {CKEDITOR.dom.element} The &lt;select&gt; element of this UI * element. * @example */ getInputElement : function() { return this._.select.getElement(); }, /** * Adds an option to the select box. * @param {String} label Option label. * @param {String} value (Optional) Option value, if not defined it'll be * assumed to be the same as the label. * @param {Number} index (Optional) Position of the option to be inserted * to. If not defined the new option will be inserted to the end of list. * @example * @returns {CKEDITOR.ui.dialog.select} The current select UI element. */ add : function( label, value, index ) { var option = new CKEDITOR.dom.element( 'option', this.getDialog().getParentEditor().document ), selectElement = this.getInputElement().$; option.$.text = label; option.$.value = ( value === undefined || value === null ) ? label : value; if ( index === undefined || index === null ) { if ( CKEDITOR.env.ie ) selectElement.add( option.$ ); else selectElement.add( option.$, null ); } else selectElement.add( option.$, index ); return this; }, /** * Removes an option from the selection list. * @param {Number} index Index of the option to be removed. * @example * @returns {CKEDITOR.ui.dialog.select} The current select UI element. */ remove : function( index ) { var selectElement = this.getInputElement().$; selectElement.remove( index ); return this; }, /** * Clears all options out of the selection list. * @returns {CKEDITOR.ui.dialog.select} The current select UI element. */ clear : function() { var selectElement = this.getInputElement().$; while ( selectElement.length > 0 ) selectElement.remove( 0 ); return this; }, keyboardFocusable : true }, commonPrototype, true ); CKEDITOR.ui.dialog.checkbox.prototype = CKEDITOR.tools.extend( new CKEDITOR.ui.dialog.uiElement, /** @lends CKEDITOR.ui.dialog.checkbox.prototype */ { /** * Gets the checkbox DOM element. * @example * @returns {CKEDITOR.dom.element} The DOM element of the checkbox. */ getInputElement : function() { return this._.checkbox.getElement(); }, /** * Sets the state of the checkbox. * @example * @param {Boolean} true to tick the checkbox, false to untick it. * @param {Boolean} noChangeEvent Internal commit, to supress 'change' event on this element. */ setValue : function( checked, noChangeEvent ) { this.getInputElement().$.checked = checked; !noChangeEvent && this.fire( 'change', { value : checked } ); }, /** * Gets the state of the checkbox. * @example * @returns {Boolean} true means the checkbox is ticked, false means it's not ticked. */ getValue : function() { return this.getInputElement().$.checked; }, /** * Handler for the access key up event. Toggles the checkbox. * @example */ accessKeyUp : function() { this.setValue( !this.getValue() ); }, /** * Defines the onChange event for UI element definitions. * @field * @type Object * @example */ eventProcessors : { onChange : function( dialog, func ) { if ( !CKEDITOR.env.ie ) return commonEventProcessors.onChange.apply( this, arguments ); else { dialog.on( 'load', function() { var element = this._.checkbox.getElement(); element.on( 'propertychange', function( evt ) { evt = evt.data.$; if ( evt.propertyName == 'checked' ) this.fire( 'change', { value : element.$.checked } ); }, this ); }, this ); this.on( 'change', func ); } return null; } }, keyboardFocusable : true }, commonPrototype, true ); CKEDITOR.ui.dialog.radio.prototype = CKEDITOR.tools.extend( new CKEDITOR.ui.dialog.uiElement, /** @lends CKEDITOR.ui.dialog.radio.prototype */ { /** * Checks one of the radio buttons in this button group. * @example * @param {String} value The value of the button to be chcked. * @param {Boolean} noChangeEvent Internal commit, to supress 'change' event on this element. */ setValue : function( value, noChangeEvent ) { var children = this._.children, item; for ( var i = 0 ; ( i < children.length ) && ( item = children[i] ) ; i++ ) item.getElement().$.checked = ( item.getValue() == value ); !noChangeEvent && this.fire( 'change', { value : value } ); }, /** * Gets the value of the currently checked radio button. * @example * @returns {String} The currently checked button's value. */ getValue : function() { var children = this._.children; for ( var i = 0 ; i < children.length ; i++ ) { if ( children[i].getElement().$.checked ) return children[i].getValue(); } return null; }, /** * Handler for the access key up event. Focuses the currently * selected radio button, or the first radio button if none is * selected. * @example */ accessKeyUp : function() { var children = this._.children, i; for ( i = 0 ; i < children.length ; i++ ) { if ( children[i].getElement().$.checked ) { children[i].getElement().focus(); return; } } children[0].getElement().focus(); }, /** * Defines the onChange event for UI element definitions. * @field * @type Object * @example */ eventProcessors : { onChange : function( dialog, func ) { if ( !CKEDITOR.env.ie ) return commonEventProcessors.onChange.apply( this, arguments ); else { dialog.on( 'load', function() { var children = this._.children, me = this; for ( var i = 0 ; i < children.length ; i++ ) { var element = children[i].getElement(); element.on( 'propertychange', function( evt ) { evt = evt.data.$; if ( evt.propertyName == 'checked' && this.$.checked ) me.fire( 'change', { value : this.getAttribute( 'value' ) } ); } ); } }, this ); this.on( 'change', func ); } return null; } }, keyboardFocusable : true }, commonPrototype, true ); CKEDITOR.ui.dialog.file.prototype = CKEDITOR.tools.extend( new CKEDITOR.ui.dialog.labeledElement, commonPrototype, /** @lends CKEDITOR.ui.dialog.file.prototype */ { /** * Gets the &lt;input&gt; element of this file input. * @returns {CKEDITOR.dom.element} The file input element. * @example */ getInputElement : function() { var frameDocument = CKEDITOR.document.getById( this._.frameId ).getFrameDocument(); return frameDocument.$.forms.length > 0 ? new CKEDITOR.dom.element( frameDocument.$.forms[0].elements[0] ) : this.getElement(); }, /** * Uploads the file in the file input. * @returns {CKEDITOR.ui.dialog.file} This object. * @example */ submit : function() { this.getInputElement().getParent().$.submit(); return this; }, /** * Get the action assigned to the form. * @returns {String} The value of the action. * @example */ getAction : function() { return this.getInputElement().getParent().$.action; }, /** * The events must be applied on the inner input element, and * that must be done when the iframe & form has been loaded */ registerEvents : function( definition ) { var regex = /^on([A-Z]\w+)/, match; var registerDomEvent = function( uiElement, dialog, eventName, func ) { uiElement.on( 'formLoaded', function() { uiElement.getInputElement().on( eventName, func, uiElement ); }); }; for ( var i in definition ) { if ( !( match = i.match( regex ) ) ) continue; if ( this.eventProcessors[i] ) this.eventProcessors[i].call( this, this._.dialog, definition[i] ); else registerDomEvent( this, this._.dialog, match[1].toLowerCase(), definition[i] ); } return this; }, /** * Redraws the file input and resets the file path in the file input. * The redraw logic is necessary because non-IE browsers tend to clear * the &lt;iframe&gt; containing the file input after closing the dialog. * @example */ reset : function() { var _ = this._, frameElement = CKEDITOR.document.getById( _.frameId ), frameDocument = frameElement.getFrameDocument(), elementDefinition = _.definition, buttons = _.buttons, callNumber = this.formLoadedNumber, unloadNumber = this.formUnloadNumber, langDir = _.dialog._.editor.lang.dir, langCode = _.dialog._.editor.langCode; // The callback function for the iframe, but we must call tools.addFunction only once // so we store the function number in this.formLoadedNumber if ( !callNumber ) { callNumber = this.formLoadedNumber = CKEDITOR.tools.addFunction( function() { // Now we can apply the events to the input type=file this.fire( 'formLoaded' ) ; }, this ) ; // Remove listeners attached to the content of the iframe (the file input) unloadNumber = this.formUnloadNumber = CKEDITOR.tools.addFunction( function() { this.getInputElement().clearCustomData(); }, this ) ; this.getDialog()._.editor.on( 'destroy', function() { CKEDITOR.tools.removeFunction( callNumber ); CKEDITOR.tools.removeFunction( unloadNumber ); } ); } function generateFormField() { frameDocument.$.open(); // Support for custom document.domain in IE. if ( CKEDITOR.env.isCustomDomain() ) frameDocument.$.domain = document.domain; var size = ''; if ( elementDefinition.size ) size = elementDefinition.size - ( CKEDITOR.env.ie ? 7 : 0 ); // "Browse" button is bigger in IE. frameDocument.$.write( [ '<html dir="' + langDir + '" lang="' + langCode + '"><head><title></title></head><body style="margin: 0; overflow: hidden; background: transparent;">', '<form enctype="multipart/form-data" method="POST" dir="' + langDir + '" lang="' + langCode + '" action="', CKEDITOR.tools.htmlEncode( elementDefinition.action ), '">', '<input type="file" name="', CKEDITOR.tools.htmlEncode( elementDefinition.id || 'cke_upload' ), '" size="', CKEDITOR.tools.htmlEncode( size > 0 ? size : "" ), '" />', '</form>', '</body></html>', '<script>window.parent.CKEDITOR.tools.callFunction(' + callNumber + ');', 'window.onbeforeunload = function() {window.parent.CKEDITOR.tools.callFunction(' + unloadNumber + ')}</script>' ].join( '' ) ); frameDocument.$.close(); for ( var i = 0 ; i < buttons.length ; i++ ) buttons[i].enable(); } // #3465: Wait for the browser to finish rendering the dialog first. if ( CKEDITOR.env.gecko ) setTimeout( generateFormField, 500 ); else generateFormField(); }, getValue : function() { return this.getInputElement().$.value || ''; }, /*** * The default value of input type="file" is an empty string, but during initialization * of this UI element, the iframe still isn't ready so it can't be read from that object * Setting it manually prevents later issues about the current value ("") being different * of the initial value (undefined as it asked for .value of a div) */ setInitValue : function() { this._.initValue = ''; }, /** * Defines the onChange event for UI element definitions. * @field * @type Object * @example */ eventProcessors : { onChange : function( dialog, func ) { // If this method is called several times (I'm not sure about how this can happen but the default // onChange processor includes this protection) // In order to reapply to the new element, the property is deleted at the beggining of the registerEvents method if ( !this._.domOnChangeRegistered ) { // By listening for the formLoaded event, this handler will get reapplied when a new // form is created this.on( 'formLoaded', function() { this.getInputElement().on( 'change', function(){ this.fire( 'change', { value : this.getValue() } ); }, this ); }, this ); this._.domOnChangeRegistered = true; } this.on( 'change', func ); } }, keyboardFocusable : true }, true ); CKEDITOR.ui.dialog.fileButton.prototype = new CKEDITOR.ui.dialog.button; CKEDITOR.ui.dialog.fieldset.prototype = CKEDITOR.tools.clone( CKEDITOR.ui.dialog.hbox.prototype ); CKEDITOR.dialog.addUIElement( 'text', textBuilder ); CKEDITOR.dialog.addUIElement( 'password', textBuilder ); CKEDITOR.dialog.addUIElement( 'textarea', commonBuilder ); CKEDITOR.dialog.addUIElement( 'checkbox', commonBuilder ); CKEDITOR.dialog.addUIElement( 'radio', commonBuilder ); CKEDITOR.dialog.addUIElement( 'button', commonBuilder ); CKEDITOR.dialog.addUIElement( 'select', commonBuilder ); CKEDITOR.dialog.addUIElement( 'file', commonBuilder ); CKEDITOR.dialog.addUIElement( 'fileButton', commonBuilder ); CKEDITOR.dialog.addUIElement( 'html', commonBuilder ); CKEDITOR.dialog.addUIElement( 'fieldset', containerBuilder ); })(); /** * Fired when the value of the uiElement is changed * @name CKEDITOR.ui.dialog.uiElement#change * @event */ /** * Fired when the inner frame created by the element is ready. * Each time the button is used or the dialog is loaded a new * form might be created. * @name CKEDITOR.ui.dialog.fileButton#formLoaded * @event */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { var cssStyle = CKEDITOR.htmlParser.cssStyle, cssLength = CKEDITOR.tools.cssLength; var cssLengthRegex = /^((?:\d*(?:\.\d+))|(?:\d+))(.*)?$/i; /* * Replacing the former CSS length value with the later one, with * adjustment to the length unit. */ function replaceCssLength( length1, length2 ) { var parts1 = cssLengthRegex.exec( length1 ), parts2 = cssLengthRegex.exec( length2 ); // Omit pixel length unit when necessary, // e.g. replaceCssLength( 10, '20px' ) -> 20 if ( parts1 ) { if ( !parts1[ 2 ] && parts2[ 2 ] == 'px' ) return parts2[ 1 ]; if ( parts1[ 2 ] == 'px' && !parts2[ 2 ] ) return parts2[ 1 ] + 'px'; } return length2; } var htmlFilterRules = { elements : { $ : function( element ) { var attributes = element.attributes, realHtml = attributes && attributes[ 'data-cke-realelement' ], realFragment = realHtml && new CKEDITOR.htmlParser.fragment.fromHtml( decodeURIComponent( realHtml ) ), realElement = realFragment && realFragment.children[ 0 ]; // Width/height in the fake object are subjected to clone into the real element. if ( realElement && element.attributes[ 'data-cke-resizable' ] ) { var styles = new cssStyle( element ).rules, realAttrs = realElement.attributes, width = styles.width, height = styles.height; width && ( realAttrs.width = replaceCssLength( realAttrs.width, width ) ); height && ( realAttrs.height = replaceCssLength( realAttrs.height, height ) ); } return realElement; } } }; CKEDITOR.plugins.add( 'fakeobjects', { requires : [ 'htmlwriter' ], afterInit : function( editor ) { var dataProcessor = editor.dataProcessor, htmlFilter = dataProcessor && dataProcessor.htmlFilter; if ( htmlFilter ) htmlFilter.addRules( htmlFilterRules ); } }); CKEDITOR.editor.prototype.createFakeElement = function( realElement, className, realElementType, isResizable ) { var lang = this.lang.fakeobjects, label = lang[ realElementType ] || lang.unknown; var attributes = { 'class' : className, src : CKEDITOR.getUrl( 'images/spacer.gif' ), 'data-cke-realelement' : encodeURIComponent( realElement.getOuterHtml() ), 'data-cke-real-node-type' : realElement.type, alt : label, title : label, align : realElement.getAttribute( 'align' ) || '' }; if ( realElementType ) attributes[ 'data-cke-real-element-type' ] = realElementType; if ( isResizable ) { attributes[ 'data-cke-resizable' ] = isResizable; var fakeStyle = new cssStyle(); var width = realElement.getAttribute( 'width' ), height = realElement.getAttribute( 'height' ); width && ( fakeStyle.rules.width = cssLength( width ) ); height && ( fakeStyle.rules.height = cssLength( height ) ); fakeStyle.populate( attributes ); } return this.document.createElement( 'img', { attributes : attributes } ); }; CKEDITOR.editor.prototype.createFakeParserElement = function( realElement, className, realElementType, isResizable ) { var lang = this.lang.fakeobjects, label = lang[ realElementType ] || lang.unknown, html; var writer = new CKEDITOR.htmlParser.basicWriter(); realElement.writeHtml( writer ); html = writer.getHtml(); var attributes = { 'class' : className, src : CKEDITOR.getUrl( 'images/spacer.gif' ), 'data-cke-realelement' : encodeURIComponent( html ), 'data-cke-real-node-type' : realElement.type, alt : label, title : label, align : realElement.attributes.align || '' }; if ( realElementType ) attributes[ 'data-cke-real-element-type' ] = realElementType; if ( isResizable ) { attributes[ 'data-cke-resizable' ] = isResizable; var realAttrs = realElement.attributes, fakeStyle = new cssStyle(); var width = realAttrs.width, height = realAttrs.height; width != undefined && ( fakeStyle.rules.width = cssLength( width ) ); height != undefined && ( fakeStyle.rules.height = cssLength ( height ) ); fakeStyle.populate( attributes ); } return new CKEDITOR.htmlParser.element( 'img', attributes ); }; CKEDITOR.editor.prototype.restoreRealElement = function( fakeElement ) { if ( fakeElement.data( 'cke-real-node-type' ) != CKEDITOR.NODE_ELEMENT ) return null; var element = CKEDITOR.dom.element.createFromHtml( decodeURIComponent( fakeElement.data( 'cke-realelement' ) ), this.document ); if ( fakeElement.data( 'cke-resizable') ) { var width = fakeElement.getStyle( 'width' ), height = fakeElement.getStyle( 'height' ); width && element.setAttribute( 'width', replaceCssLength( element.getAttribute( 'width' ), width ) ); height && element.setAttribute( 'height', replaceCssLength( element.getAttribute( 'height' ), height ) ); } return element; }; })();
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.add( 'floatpanel', { requires : [ 'panel' ] }); (function() { var panels = {}; var isShowing = false; function getPanel( editor, doc, parentElement, definition, level ) { // Generates the panel key: docId-eleId-skinName-langDir[-uiColor][-CSSs][-level] var key = CKEDITOR.tools.genKey( doc.getUniqueId(), parentElement.getUniqueId(), editor.skinName, editor.lang.dir, editor.uiColor || '', definition.css || '', level || '' ); var panel = panels[ key ]; if ( !panel ) { panel = panels[ key ] = new CKEDITOR.ui.panel( doc, definition ); panel.element = parentElement.append( CKEDITOR.dom.element.createFromHtml( panel.renderHtml( editor ), doc ) ); panel.element.setStyles( { display : 'none', position : 'absolute' }); } return panel; } CKEDITOR.ui.floatPanel = CKEDITOR.tools.createClass( { $ : function( editor, parentElement, definition, level ) { definition.forceIFrame = 1; var doc = parentElement.getDocument(), panel = getPanel( editor, doc, parentElement, definition, level || 0 ), element = panel.element, iframe = element.getFirst().getFirst(); this.element = element; this._ = { editor : editor, // The panel that will be floating. panel : panel, parentElement : parentElement, definition : definition, document : doc, iframe : iframe, children : [], dir : editor.lang.dir }; editor.on( 'mode', function(){ this.hide(); }, this ); }, proto : { addBlock : function( name, block ) { return this._.panel.addBlock( name, block ); }, addListBlock : function( name, multiSelect ) { return this._.panel.addListBlock( name, multiSelect ); }, getBlock : function( name ) { return this._.panel.getBlock( name ); }, /* corner (LTR): 1 = top-left 2 = top-right 3 = bottom-right 4 = bottom-left corner (RTL): 1 = top-right 2 = top-left 3 = bottom-left 4 = bottom-right */ showBlock : function( name, offsetParent, corner, offsetX, offsetY ) { var panel = this._.panel, block = panel.showBlock( name ); this.allowBlur( false ); isShowing = 1; // Record from where the focus is when open panel. this._.returnFocus = this._.editor.focusManager.hasFocus ? this._.editor : new CKEDITOR.dom.element( CKEDITOR.document.$.activeElement ); var element = this.element, iframe = this._.iframe, definition = this._.definition, position = offsetParent.getDocumentPosition( element.getDocument() ), rtl = this._.dir == 'rtl'; var left = position.x + ( offsetX || 0 ), top = position.y + ( offsetY || 0 ); // Floating panels are off by (-1px, 0px) in RTL mode. (#3438) if ( rtl && ( corner == 1 || corner == 4 ) ) left += offsetParent.$.offsetWidth; else if ( !rtl && ( corner == 2 || corner == 3 ) ) left += offsetParent.$.offsetWidth - 1; if ( corner == 3 || corner == 4 ) top += offsetParent.$.offsetHeight - 1; // Memorize offsetParent by it's ID. this._.panel._.offsetParentId = offsetParent.getId(); element.setStyles( { top : top + 'px', left: 0, display : '' }); // Don't use display or visibility style because we need to // calculate the rendering layout later and focus the element. element.setOpacity( 0 ); // To allow the context menu to decrease back their width element.getFirst().removeStyle( 'width' ); // Configure the IFrame blur event. Do that only once. if ( !this._.blurSet ) { // Non IE prefer the event into a window object. var focused = CKEDITOR.env.ie ? iframe : new CKEDITOR.dom.window( iframe.$.contentWindow ); // With addEventListener compatible browsers, we must // useCapture when registering the focus/blur events to // guarantee they will be firing in all situations. (#3068, #3222 ) CKEDITOR.event.useCapture = true; focused.on( 'blur', function( ev ) { if ( !this.allowBlur() ) return; // As we are using capture to register the listener, // the blur event may get fired even when focusing // inside the window itself, so we must ensure the // target is out of it. var target = ev.data.getTarget() ; if ( target.getName && target.getName() != 'iframe' ) return; if ( this.visible && !this._.activeChild && !isShowing ) { // Panel close is caused by user's navigating away the focus, e.g. click outside the panel. // DO NOT restore focus in this case. delete this._.returnFocus; this.hide(); } }, this ); focused.on( 'focus', function() { this._.focused = true; this.hideChild(); this.allowBlur( true ); }, this ); CKEDITOR.event.useCapture = false; this._.blurSet = 1; } panel.onEscape = CKEDITOR.tools.bind( function( keystroke ) { if ( this.onEscape && this.onEscape( keystroke ) === false ) return false; }, this ); CKEDITOR.tools.setTimeout( function() { if ( rtl ) left -= element.$.offsetWidth; var panelLoad = CKEDITOR.tools.bind( function () { var target = element.getFirst(); if ( block.autoSize ) { // We must adjust first the width or IE6 could include extra lines in the height computation var widthNode = block.element.$; if ( CKEDITOR.env.gecko || CKEDITOR.env.opera ) widthNode = widthNode.parentNode; if ( CKEDITOR.env.ie ) widthNode = widthNode.document.body; var width = widthNode.scrollWidth; // Account for extra height needed due to IE quirks box model bug: // http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug // (#3426) if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && width > 0 ) width += ( target.$.offsetWidth || 0 ) - ( target.$.clientWidth || 0 ) + 3; // A little extra at the end. // If not present, IE6 might break into the next line, but also it looks better this way width += 4 ; target.setStyle( 'width', width + 'px' ); // IE doesn't compute the scrollWidth if a filter is applied previously block.element.addClass( 'cke_frameLoaded' ); var height = block.element.$.scrollHeight; // Account for extra height needed due to IE quirks box model bug: // http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug // (#3426) if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && height > 0 ) height += ( target.$.offsetHeight || 0 ) - ( target.$.clientHeight || 0 ) + 3; target.setStyle( 'height', height + 'px' ); // Fix IE < 8 visibility. panel._.currentBlock.element.setStyle( 'display', 'none' ).removeStyle( 'display' ); } else target.removeStyle( 'height' ); var panelElement = panel.element, panelWindow = panelElement.getWindow(), windowScroll = panelWindow.getScrollPosition(), viewportSize = panelWindow.getViewPaneSize(), panelSize = { 'height' : panelElement.$.offsetHeight, 'width' : panelElement.$.offsetWidth }; // If the menu is horizontal off, shift it toward // the opposite language direction. if ( rtl ? left < 0 : left + panelSize.width > viewportSize.width + windowScroll.x ) left += ( panelSize.width * ( rtl ? 1 : -1 ) ); // Vertical off screen is simpler. if ( top + panelSize.height > viewportSize.height + windowScroll.y ) top -= panelSize.height; // If IE is in RTL, we have troubles with absolute // position and horizontal scrolls. Here we have a // series of hacks to workaround it. (#6146) if ( CKEDITOR.env.ie ) { var offsetParent = new CKEDITOR.dom.element( element.$.offsetParent ), scrollParent = offsetParent; // Quirks returns <body>, but standards returns <html>. if ( scrollParent.getName() == 'html' ) scrollParent = scrollParent.getDocument().getBody(); if ( scrollParent.getComputedStyle( 'direction' ) == 'rtl' ) { // For IE8, there is not much logic on this, but it works. if ( CKEDITOR.env.ie8Compat ) left -= element.getDocument().getDocumentElement().$.scrollLeft * 2; else left -= ( offsetParent.$.scrollWidth - offsetParent.$.clientWidth ); } } // Trigger the onHide event of the previously active panel to prevent // incorrect styles from being applied (#6170) var innerElement = element.getFirst(), activePanel; if ( ( activePanel = innerElement.getCustomData( 'activePanel' ) ) ) activePanel.onHide && activePanel.onHide.call( this, 1 ); innerElement.setCustomData( 'activePanel', this ); element.setStyles( { top : top + 'px', left : left + 'px' } ); element.setOpacity( 1 ); } , this ); panel.isLoaded ? panelLoad() : panel.onLoad = panelLoad; // Set the panel frame focus, so the blur event gets fired. CKEDITOR.tools.setTimeout( function() { iframe.$.contentWindow.focus(); // We need this get fired manually because of unfired focus() function. this.allowBlur( true ); }, 0, this); }, CKEDITOR.env.air ? 200 : 0, this); this.visible = 1; if ( this.onShow ) this.onShow.call( this ); isShowing = 0; }, hide : function( returnFocus ) { if ( this.visible && ( !this.onHide || this.onHide.call( this ) !== true ) ) { this.hideChild(); // Blur previously focused element. (#6671) CKEDITOR.env.gecko && this._.iframe.getFrameDocument().$.activeElement.blur(); this.element.setStyle( 'display', 'none' ); this.visible = 0; this.element.getFirst().removeCustomData( 'activePanel' ); // Return focus properly. (#6247) var focusReturn = returnFocus !== false && this._.returnFocus; if ( focusReturn ) { // Webkit requires focus moved out panel iframe first. if ( CKEDITOR.env.webkit && focusReturn.type ) focusReturn.getWindow().$.focus(); focusReturn.focus(); } } }, allowBlur : function( allow ) // Prevent editor from hiding the panel. #3222. { var panel = this._.panel; if ( allow != undefined ) panel.allowBlur = allow; return panel.allowBlur; }, showAsChild : function( panel, blockName, offsetParent, corner, offsetX, offsetY ) { // Skip reshowing of child which is already visible. if ( this._.activeChild == panel && panel._.panel._.offsetParentId == offsetParent.getId() ) return; this.hideChild(); panel.onHide = CKEDITOR.tools.bind( function() { // Use a timeout, so we give time for this menu to get // potentially focused. CKEDITOR.tools.setTimeout( function() { if ( !this._.focused ) this.hide(); }, 0, this ); }, this ); this._.activeChild = panel; this._.focused = false; panel.showBlock( blockName, offsetParent, corner, offsetX, offsetY ); /* #3767 IE: Second level menu may not have borders */ if ( CKEDITOR.env.ie7Compat || ( CKEDITOR.env.ie8 && CKEDITOR.env.ie6Compat ) ) { setTimeout(function() { panel.element.getChild( 0 ).$.style.cssText += ''; }, 100); } }, hideChild : function() { var activeChild = this._.activeChild; if ( activeChild ) { delete activeChild.onHide; // Sub panels don't manage focus. (#7881) delete activeChild._.returnFocus; delete this._.activeChild; activeChild.hide(); } } } }); CKEDITOR.on( 'instanceDestroyed', function() { var isLastInstance = CKEDITOR.tools.isEmpty( CKEDITOR.instances ); for ( var i in panels ) { var panel = panels[ i ]; // Safe to destroy it since there're no more instances.(#4241) if ( isLastInstance ) panel.destroy(); // Panel might be used by other instances, just hide them.(#4552) else panel.element.hide(); } // Remove the registration. isLastInstance && ( panels = {} ); } ); })();
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { function forceHtmlMode( evt ) { evt.data.mode = 'html'; } CKEDITOR.plugins.add( 'pastefromword', { init : function( editor ) { // Flag indicate this command is actually been asked instead of a generic // pasting. var forceFromWord = 0; var resetFromWord = function( evt ) { evt && evt.removeListener(); editor.removeListener( 'beforePaste', forceHtmlMode ); forceFromWord && setTimeout( function() { forceFromWord = 0; }, 0 ); }; // Features bring by this command beside the normal process: // 1. No more bothering of user about the clean-up. // 2. Perform the clean-up even if content is not from MS-Word. // (e.g. from a MS-Word similar application.) editor.addCommand( 'pastefromword', { canUndo : false, exec : function() { // Ensure the received data format is HTML and apply content filtering. (#6718) forceFromWord = 1; editor.on( 'beforePaste', forceHtmlMode ); if ( editor.execCommand( 'paste', 'html' ) === false ) { editor.on( 'dialogShow', function ( evt ) { evt.removeListener(); evt.data.on( 'cancel', resetFromWord ); }); editor.on( 'dialogHide', function( evt ) { evt.data.removeListener( 'cancel', resetFromWord ); } ); } editor.on( 'afterPaste', resetFromWord ); } }); // Register the toolbar button. editor.ui.addButton( 'PasteFromWord', { label : editor.lang.pastefromword.toolbar, command : 'pastefromword' }); editor.on( 'pasteState', function( evt ) { editor.getCommand( 'pastefromword' ).setState( evt.data ); }); editor.on( 'paste', function( evt ) { var data = evt.data, mswordHtml; // MS-WORD format sniffing. if ( ( mswordHtml = data[ 'html' ] ) && ( forceFromWord || ( /(class=\"?Mso|style=\"[^\"]*\bmso\-|w:WordDocument)/ ).test( mswordHtml ) ) ) { var isLazyLoad = this.loadFilterRules( function() { // Event continuation with the original data. if ( isLazyLoad ) editor.fire( 'paste', data ); else if ( !editor.config.pasteFromWordPromptCleanup || ( forceFromWord || confirm( editor.lang.pastefromword.confirmCleanup ) ) ) { data[ 'html' ] = CKEDITOR.cleanWord( mswordHtml, editor ); } }); // The cleanup rules are to be loaded, we should just cancel // this event. isLazyLoad && evt.cancel(); } }, this ); }, loadFilterRules : function( callback ) { var isLoaded = CKEDITOR.cleanWord; if ( isLoaded ) callback(); else { var filterFilePath = CKEDITOR.getUrl( CKEDITOR.config.pasteFromWordCleanupFile || ( this.path + 'filter/default.js' ) ); // Load with busy indicator. CKEDITOR.scriptLoader.load( filterFilePath, callback, null, true ); } return !isLoaded; }, requires : [ 'clipboard' ] }); })(); /** * Whether to prompt the user about the clean up of content being pasted from * MS Word. * @name CKEDITOR.config.pasteFromWordPromptCleanup * @since 3.1 * @type Boolean * @default undefined * @example * config.pasteFromWordPromptCleanup = true; */ /** * The file that provides the MS Word cleanup function for pasting operations. * Note: This is a global configuration shared by all editor instances present * in the page. * @name CKEDITOR.config.pasteFromWordCleanupFile * @since 3.1 * @type String * @default 'default' * @example * // Load from 'pastefromword' plugin 'filter' sub folder (custom.js file). * CKEDITOR.config.pasteFromWordCleanupFile = 'custom'; */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { var fragmentPrototype = CKEDITOR.htmlParser.fragment.prototype, elementPrototype = CKEDITOR.htmlParser.element.prototype; fragmentPrototype.onlyChild = elementPrototype.onlyChild = function() { var children = this.children, count = children.length, firstChild = ( count == 1 ) && children[ 0 ]; return firstChild || null; }; elementPrototype.removeAnyChildWithName = function( tagName ) { var children = this.children, childs = [], child; for ( var i = 0; i < children.length; i++ ) { child = children[ i ]; if ( !child.name ) continue; if ( child.name == tagName ) { childs.push( child ); children.splice( i--, 1 ); } childs = childs.concat( child.removeAnyChildWithName( tagName ) ); } return childs; }; elementPrototype.getAncestor = function( tagNameRegex ) { var parent = this.parent; while ( parent && !( parent.name && parent.name.match( tagNameRegex ) ) ) parent = parent.parent; return parent; }; fragmentPrototype.firstChild = elementPrototype.firstChild = function( evaluator ) { var child; for ( var i = 0 ; i < this.children.length ; i++ ) { child = this.children[ i ]; if ( evaluator( child ) ) return child; else if ( child.name ) { child = child.firstChild( evaluator ); if ( child ) return child; } } return null; }; // Adding a (set) of styles to the element's 'style' attributes. elementPrototype.addStyle = function( name, value, isPrepend ) { var styleText, addingStyleText = ''; // name/value pair. if ( typeof value == 'string' ) addingStyleText += name + ':' + value + ';'; else { // style literal. if ( typeof name == 'object' ) { for ( var style in name ) { if ( name.hasOwnProperty( style ) ) addingStyleText += style + ':' + name[ style ] + ';'; } } // raw style text form. else addingStyleText += name; isPrepend = value; } if ( !this.attributes ) this.attributes = {}; styleText = this.attributes.style || ''; styleText = ( isPrepend ? [ addingStyleText, styleText ] : [ styleText, addingStyleText ] ).join( ';' ); this.attributes.style = styleText.replace( /^;|;(?=;)/, '' ); }; /** * Return the DTD-valid parent tag names of the specified one. * @param tagName */ CKEDITOR.dtd.parentOf = function( tagName ) { var result = {}; for ( var tag in this ) { if ( tag.indexOf( '$' ) == -1 && this[ tag ][ tagName ] ) result[ tag ] = 1; } return result; }; // 1. move consistent list item styles up to list root. // 2. clear out unnecessary list item numbering. function postProcessList( list ) { var children = list.children, child, attrs, count = list.children.length, match, mergeStyle, styleTypeRegexp = /list-style-type:(.*?)(?:;|$)/, stylesFilter = CKEDITOR.plugins.pastefromword.filters.stylesFilter; attrs = list.attributes; if ( styleTypeRegexp.exec( attrs.style ) ) return; for ( var i = 0; i < count; i++ ) { child = children[ i ]; if ( child.attributes.value && Number( child.attributes.value ) == i + 1 ) delete child.attributes.value; match = styleTypeRegexp.exec( child.attributes.style ); if ( match ) { if ( match[ 1 ] == mergeStyle || !mergeStyle ) mergeStyle = match[ 1 ]; else { mergeStyle = null; break; } } } if ( mergeStyle ) { for ( i = 0; i < count; i++ ) { attrs = children[ i ].attributes; attrs.style && ( attrs.style = stylesFilter( [ [ 'list-style-type'] ] )( attrs.style ) || '' ); } list.addStyle( 'list-style-type', mergeStyle ); } } var cssLengthRelativeUnit = /^([.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz){1}?/i; var emptyMarginRegex = /^(?:\b0[^\s]*\s*){1,4}$/; // e.g. 0px 0pt 0px var romanLiternalPattern = '^m{0,4}(cm|cd|d?c{0,3})(xc|xl|l?x{0,3})(ix|iv|v?i{0,3})$', lowerRomanLiteralRegex = new RegExp( romanLiternalPattern ), upperRomanLiteralRegex = new RegExp( romanLiternalPattern.toUpperCase() ); var orderedPatterns = { 'decimal' : /\d+/, 'lower-roman': lowerRomanLiteralRegex, 'upper-roman': upperRomanLiteralRegex, 'lower-alpha' : /^[a-z]+$/, 'upper-alpha': /^[A-Z]+$/ }, unorderedPatterns = { 'disc' : /[l\u00B7\u2002]/, 'circle' : /[\u006F\u00D8]/,'square' : /[\u006E\u25C6]/}, listMarkerPatterns = { 'ol' : orderedPatterns, 'ul' : unorderedPatterns }, romans = [ [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I'] ], alpahbets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // Convert roman numbering back to decimal. function fromRoman( str ) { str = str.toUpperCase(); var l = romans.length, retVal = 0; for ( var i = 0; i < l; ++i ) { for ( var j = romans[i], k = j[1].length; str.substr( 0, k ) == j[1]; str = str.substr( k ) ) retVal += j[ 0 ]; } return retVal; } // Convert alphabet numbering back to decimal. function fromAlphabet( str ) { str = str.toUpperCase(); var l = alpahbets.length, retVal = 1; for ( var x = 1; str.length > 0; x *= l ) { retVal += alpahbets.indexOf( str.charAt( str.length - 1 ) ) * x; str = str.substr( 0, str.length - 1 ); } return retVal; } var listBaseIndent = 0, previousListItemMargin = null, previousListId; var plugin = ( CKEDITOR.plugins.pastefromword = { utils : { // Create a <cke:listbullet> which indicate an list item type. createListBulletMarker : function ( bullet, bulletText ) { var marker = new CKEDITOR.htmlParser.element( 'cke:listbullet' ); marker.attributes = { 'cke:listsymbol' : bullet[ 0 ] }; marker.add( new CKEDITOR.htmlParser.text( bulletText ) ); return marker; }, isListBulletIndicator : function( element ) { var styleText = element.attributes && element.attributes.style; if ( /mso-list\s*:\s*Ignore/i.test( styleText ) ) return true; }, isContainingOnlySpaces : function( element ) { var text; return ( ( text = element.onlyChild() ) && ( /^(:?\s|&nbsp;)+$/ ).test( text.value ) ); }, resolveList : function( element ) { // <cke:listbullet> indicate a list item. var attrs = element.attributes, listMarker; if ( ( listMarker = element.removeAnyChildWithName( 'cke:listbullet' ) ) && listMarker.length && ( listMarker = listMarker[ 0 ] ) ) { element.name = 'cke:li'; if ( attrs.style ) { attrs.style = plugin.filters.stylesFilter( [ // Text-indent is not representing list item level any more. [ 'text-indent' ], [ 'line-height' ], // First attempt is to resolve indent level from on a constant margin increment. [ ( /^margin(:?-left)?$/ ), null, function( margin ) { // Deal with component/short-hand form. var values = margin.split( ' ' ); margin = CKEDITOR.tools.convertToPx( values[ 3 ] || values[ 1 ] || values [ 0 ] ); // Figure out the indent unit by checking the first time of incrementation. if ( !listBaseIndent && previousListItemMargin !== null && margin > previousListItemMargin ) listBaseIndent = margin - previousListItemMargin; previousListItemMargin = margin; attrs[ 'cke:indent' ] = listBaseIndent && ( Math.ceil( margin / listBaseIndent ) + 1 ) || 1; } ], // The best situation: "mso-list:l0 level1 lfo2" tells the belonged list root, list item indentation, etc. [ ( /^mso-list$/ ), null, function( val ) { val = val.split( ' ' ); var listId = Number( val[ 0 ].match( /\d+/ ) ), indent = Number( val[ 1 ].match( /\d+/ ) ); if ( indent == 1 ) { listId !== previousListId && ( attrs[ 'cke:reset' ] = 1 ); previousListId = listId; } attrs[ 'cke:indent' ] = indent; } ] ] )( attrs.style, element ) || ''; } // First level list item might be presented without a margin. // In case all above doesn't apply. if ( !attrs[ 'cke:indent' ] ) { previousListItemMargin = 0; attrs[ 'cke:indent' ] = 1; } // Inherit attributes from bullet. CKEDITOR.tools.extend( attrs, listMarker.attributes ); return true; } // Current list disconnected. else previousListId = previousListItemMargin = listBaseIndent = null; return false; }, // Providing a shorthand style then retrieve one or more style component values. getStyleComponents : ( function() { var calculator = CKEDITOR.dom.element.createFromHtml( '<div style="position:absolute;left:-9999px;top:-9999px;"></div>', CKEDITOR.document ); CKEDITOR.document.getBody().append( calculator ); return function( name, styleValue, fetchList ) { calculator.setStyle( name, styleValue ); var styles = {}, count = fetchList.length; for ( var i = 0; i < count; i++ ) styles[ fetchList[ i ] ] = calculator.getStyle( fetchList[ i ] ); return styles; }; } )(), listDtdParents : CKEDITOR.dtd.parentOf( 'ol' ) }, filters : { // Transform a normal list into flat list items only presentation. // E.g. <ul><li>level1<ol><li>level2</li></ol></li> => // <cke:li cke:listtype="ul" cke:indent="1">level1</cke:li> // <cke:li cke:listtype="ol" cke:indent="2">level2</cke:li> flattenList : function( element, level ) { level = typeof level == 'number' ? level : 1; var attrs = element.attributes, listStyleType; // All list items are of the same type. switch ( attrs.type ) { case 'a' : listStyleType = 'lower-alpha'; break; case '1' : listStyleType = 'decimal'; break; // TODO: Support more list style type from MS-Word. } var children = element.children, child; for ( var i = 0; i < children.length; i++ ) { child = children[ i ]; if ( child.name in CKEDITOR.dtd.$listItem ) { var attributes = child.attributes, listItemChildren = child.children, count = listItemChildren.length, last = listItemChildren[ count - 1 ]; // Move out nested list. if ( last.name in CKEDITOR.dtd.$list ) { element.add( last, i + 1 ); // Remove the parent list item if it's just a holder. if ( !--listItemChildren.length ) children.splice( i--, 1 ); } child.name = 'cke:li'; // Inherit numbering from list root on the first list item. attrs.start && !i && ( attributes.value = attrs.start ); plugin.filters.stylesFilter( [ [ 'tab-stops', null, function( val ) { var margin = val.split( ' ' )[ 1 ].match( cssLengthRelativeUnit ); margin && ( previousListItemMargin = CKEDITOR.tools.convertToPx( margin[ 0 ] ) ); } ], ( level == 1 ? [ 'mso-list', null, function( val ) { val = val.split( ' ' ); var listId = Number( val[ 0 ].match( /\d+/ ) ); listId !== previousListId && ( attributes[ 'cke:reset' ] = 1 ); previousListId = listId; } ] : null ) ] )( attributes.style ); attributes[ 'cke:indent' ] = level; attributes[ 'cke:listtype' ] = element.name; attributes[ 'cke:list-style-type' ] = listStyleType; } // Flatten sub list. else if ( child.name in CKEDITOR.dtd.$list ) { // Absorb sub list children. arguments.callee.apply( this, [ child, level + 1 ] ); children = children.slice( 0, i ).concat( child.children ).concat( children.slice( i + 1 ) ); element.children = []; for ( var j = 0, num = children.length; j < num ; j++ ) element.add( children[ j ] ); } } delete element.name; // We're loosing tag name here, signalize this element as a list. attrs[ 'cke:list' ] = 1; }, /** * Try to collect all list items among the children and establish one * or more HTML list structures for them. * @param element */ assembleList : function( element ) { var children = element.children, child, listItem, // The current processing cke:li element. listItemAttrs, listItemIndent, // Indent level of current list item. lastIndent, lastListItem, // The previous one just been added to the list. list, // Current staging list and it's parent list if any. openedLists = [], previousListStyleType, previousListType; // Properties of the list item are to be resolved from the list bullet. var bullet, listType, listStyleType, itemNumeric; for ( var i = 0; i < children.length; i++ ) { child = children[ i ]; if ( 'cke:li' == child.name ) { child.name = 'li'; listItem = child; listItemAttrs = listItem.attributes; bullet = listItemAttrs[ 'cke:listsymbol' ]; bullet = bullet && bullet.match( /^(?:[(]?)([^\s]+?)([.)]?)$/ ); listType = listStyleType = itemNumeric = null; if ( listItemAttrs[ 'cke:ignored' ] ) { children.splice( i--, 1 ); continue; } // This's from a new list root. listItemAttrs[ 'cke:reset' ] && ( list = lastIndent = lastListItem = null ); // List item indent level might come from a real list indentation or // been resolved from a pseudo list item's margin value, even get // no indentation at all. listItemIndent = Number( listItemAttrs[ 'cke:indent' ] ); // We're moving out of the current list, cleaning up. if ( listItemIndent != lastIndent ) previousListType = previousListStyleType = null; // List type and item style are already resolved. if ( !bullet ) { listType = listItemAttrs[ 'cke:listtype' ] || 'ol'; listStyleType = listItemAttrs[ 'cke:list-style-type' ]; } else { // Probably share the same list style type with previous list item, // give it priority to avoid ambiguous between C(Alpha) and C.(Roman). if ( previousListType && listMarkerPatterns[ previousListType ] [ previousListStyleType ].test( bullet[ 1 ] ) ) { listType = previousListType; listStyleType = previousListStyleType; } else { for ( var type in listMarkerPatterns ) { for ( var style in listMarkerPatterns[ type ] ) { if ( listMarkerPatterns[ type ][ style ].test( bullet[ 1 ] ) ) { // Small numbering has higher priority, when dealing with ambiguous // between C(Alpha) and C.(Roman). if ( type == 'ol' && ( /alpha|roman/ ).test( style ) ) { var num = /roman/.test( style ) ? fromRoman( bullet[ 1 ] ) : fromAlphabet( bullet[ 1 ] ); if ( !itemNumeric || num < itemNumeric ) { itemNumeric = num; listType = type; listStyleType = style; } } else { listType = type; listStyleType = style; break; } } } } } // Simply use decimal/disc for the rest forms of unrepresentable // numerals, e.g. Chinese..., but as long as there a second part // included, it has a bigger chance of being a order list ;) !listType && ( listType = bullet[ 2 ] ? 'ol' : 'ul' ); } previousListType = listType; previousListStyleType = listStyleType || ( listType == 'ol' ? 'decimal' : 'disc' ); if ( listStyleType && listStyleType != ( listType == 'ol' ? 'decimal' : 'disc' ) ) listItem.addStyle( 'list-style-type', listStyleType ); // Figure out start numbering. if ( listType == 'ol' && bullet ) { switch ( listStyleType ) { case 'decimal' : itemNumeric = Number( bullet[ 1 ] ); break; case 'lower-roman': case 'upper-roman': itemNumeric = fromRoman( bullet[ 1 ] ); break; case 'lower-alpha': case 'upper-alpha': itemNumeric = fromAlphabet( bullet[ 1 ] ); break; } // Always create the numbering, swipe out unnecessary ones later. listItem.attributes.value = itemNumeric; } // Start the list construction. if ( !list ) { openedLists.push( list = new CKEDITOR.htmlParser.element( listType ) ); list.add( listItem ); children[ i ] = list; } else { if ( listItemIndent > lastIndent ) { openedLists.push( list = new CKEDITOR.htmlParser.element( listType ) ); list.add( listItem ); lastListItem.add( list ); } else if ( listItemIndent < lastIndent ) { // There might be a negative gap between two list levels. (#4944) var diff = lastIndent - listItemIndent, parent; while ( diff-- && ( parent = list.parent ) ) list = parent.parent; list.add( listItem ); } else list.add( listItem ); children.splice( i--, 1 ); } lastListItem = listItem; lastIndent = listItemIndent; } else if ( list ) list = lastIndent = lastListItem = null; } for ( i = 0; i < openedLists.length; i++ ) postProcessList( openedLists[ i ] ); list = lastIndent = lastListItem = previousListId = previousListItemMargin = listBaseIndent = null; }, /** * A simple filter which always rejecting. */ falsyFilter : function( value ) { return false; }, /** * A filter dedicated on the 'style' attribute filtering, e.g. dropping/replacing style properties. * @param styles {Array} in form of [ styleNameRegexp, styleValueRegexp, * newStyleValue/newStyleGenerator, newStyleName ] where only the first * parameter is mandatory. * @param whitelist {Boolean} Whether the {@param styles} will be considered as a white-list. */ stylesFilter : function( styles, whitelist ) { return function( styleText, element ) { var rules = []; // html-encoded quote might be introduced by 'font-family' // from MS-Word which confused the following regexp. e.g. //'font-family: &quot;Lucida, Console&quot;' ( styleText || '' ) .replace( /&quot;/g, '"' ) .replace( /\s*([^ :;]+)\s*:\s*([^;]+)\s*(?=;|$)/g, function( match, name, value ) { name = name.toLowerCase(); name == 'font-family' && ( value = value.replace( /["']/g, '' ) ); var namePattern, valuePattern, newValue, newName; for ( var i = 0 ; i < styles.length; i++ ) { if ( styles[ i ] ) { namePattern = styles[ i ][ 0 ]; valuePattern = styles[ i ][ 1 ]; newValue = styles[ i ][ 2 ]; newName = styles[ i ][ 3 ]; if ( name.match( namePattern ) && ( !valuePattern || value.match( valuePattern ) ) ) { name = newName || name; whitelist && ( newValue = newValue || value ); if ( typeof newValue == 'function' ) newValue = newValue( value, element, name ); // Return an couple indicate both name and value // changed. if ( newValue && newValue.push ) name = newValue[ 0 ], newValue = newValue[ 1 ]; if ( typeof newValue == 'string' ) rules.push( [ name, newValue ] ); return; } } } !whitelist && rules.push( [ name, value ] ); }); for ( var i = 0 ; i < rules.length ; i++ ) rules[ i ] = rules[ i ].join( ':' ); return rules.length ? ( rules.join( ';' ) + ';' ) : false; }; }, /** * Migrate the element by decorate styles on it. * @param styleDefiniton * @param variables */ elementMigrateFilter : function ( styleDefiniton, variables ) { return function( element ) { var styleDef = variables ? new CKEDITOR.style( styleDefiniton, variables )._.definition : styleDefiniton; element.name = styleDef.element; CKEDITOR.tools.extend( element.attributes, CKEDITOR.tools.clone( styleDef.attributes ) ); element.addStyle( CKEDITOR.style.getStyleText( styleDef ) ); }; }, /** * Migrate styles by creating a new nested stylish element. * @param styleDefinition */ styleMigrateFilter : function( styleDefinition, variableName ) { var elementMigrateFilter = this.elementMigrateFilter; return function( value, element ) { // Build an stylish element first. var styleElement = new CKEDITOR.htmlParser.element( null ), variables = {}; variables[ variableName ] = value; elementMigrateFilter( styleDefinition, variables )( styleElement ); // Place the new element inside the existing span. styleElement.children = element.children; element.children = [ styleElement ]; }; }, /** * A filter which remove cke-namespaced-attribute on * all none-cke-namespaced elements. * @param value * @param element */ bogusAttrFilter : function( value, element ) { if ( element.name.indexOf( 'cke:' ) == -1 ) return false; }, /** * A filter which will be used to apply inline css style according the stylesheet * definition rules, is generated lazily when filtering. */ applyStyleFilter : null }, getRules : function( editor ) { var dtd = CKEDITOR.dtd, blockLike = CKEDITOR.tools.extend( {}, dtd.$block, dtd.$listItem, dtd.$tableContent ), config = editor.config, filters = this.filters, falsyFilter = filters.falsyFilter, stylesFilter = filters.stylesFilter, elementMigrateFilter = filters.elementMigrateFilter, styleMigrateFilter = CKEDITOR.tools.bind( this.filters.styleMigrateFilter, this.filters ), createListBulletMarker = this.utils.createListBulletMarker, flattenList = filters.flattenList, assembleList = filters.assembleList, isListBulletIndicator = this.utils.isListBulletIndicator, containsNothingButSpaces = this.utils.isContainingOnlySpaces, resolveListItem = this.utils.resolveList, convertToPx = function( value ) { value = CKEDITOR.tools.convertToPx( value ); return isNaN( value ) ? value : value + 'px'; }, getStyleComponents = this.utils.getStyleComponents, listDtdParents = this.utils.listDtdParents, removeFontStyles = config.pasteFromWordRemoveFontStyles !== false, removeStyles = config.pasteFromWordRemoveStyles !== false; return { elementNames : [ // Remove script, meta and link elements. [ ( /meta|link|script/ ), '' ] ], root : function( element ) { element.filterChildren(); assembleList( element ); }, elements : { '^' : function( element ) { // Transform CSS style declaration to inline style. var applyStyleFilter; if ( CKEDITOR.env.gecko && ( applyStyleFilter = filters.applyStyleFilter ) ) applyStyleFilter( element ); }, $ : function( element ) { var tagName = element.name || '', attrs = element.attributes; // Convert length unit of width/height on blocks to // a more editor-friendly way (px). if ( tagName in blockLike && attrs.style ) { attrs.style = stylesFilter( [ [ ( /^(:?width|height)$/ ), null, convertToPx ] ] )( attrs.style ) || ''; } // Processing headings. if ( tagName.match( /h\d/ ) ) { element.filterChildren(); // Is the heading actually a list item? if ( resolveListItem( element ) ) return; // Adapt heading styles to editor's convention. elementMigrateFilter( config[ 'format_' + tagName ] )( element ); } // Remove inline elements which contain only empty spaces. else if ( tagName in dtd.$inline ) { element.filterChildren(); if ( containsNothingButSpaces( element ) ) delete element.name; } // Remove element with ms-office namespace, // with it's content preserved, e.g. 'o:p'. else if ( tagName.indexOf( ':' ) != -1 && tagName.indexOf( 'cke' ) == -1 ) { element.filterChildren(); // Restore image real link from vml. if ( tagName == 'v:imagedata' ) { var href = element.attributes[ 'o:href' ]; if ( href ) element.attributes.src = href; element.name = 'img'; return; } delete element.name; } // Assembling list items into a whole list. if ( tagName in listDtdParents ) { element.filterChildren(); assembleList( element ); } }, // We'll drop any style sheet, but Firefox conclude // certain styles in a single style element, which are // required to be changed into inline ones. 'style' : function( element ) { if ( CKEDITOR.env.gecko ) { // Grab only the style definition section. var styleDefSection = element.onlyChild().value.match( /\/\* Style Definitions \*\/([\s\S]*?)\/\*/ ), styleDefText = styleDefSection && styleDefSection[ 1 ], rules = {}; // Storing the parsed result. if ( styleDefText ) { styleDefText // Remove line-breaks. .replace(/[\n\r]/g,'') // Extract selectors and style properties. .replace( /(.+?)\{(.+?)\}/g, function( rule, selectors, styleBlock ) { selectors = selectors.split( ',' ); var length = selectors.length, selector; for ( var i = 0; i < length; i++ ) { // Assume MS-Word mostly generate only simple // selector( [Type selector][Class selector]). CKEDITOR.tools.trim( selectors[ i ] ) .replace( /^(\w+)(\.[\w-]+)?$/g, function( match, tagName, className ) { tagName = tagName || '*'; className = className.substring( 1, className.length ); // Reject MS-Word Normal styles. if ( className.match( /MsoNormal/ ) ) return; if ( !rules[ tagName ] ) rules[ tagName ] = {}; if ( className ) rules[ tagName ][ className ] = styleBlock; else rules[ tagName ] = styleBlock; } ); } }); filters.applyStyleFilter = function( element ) { var name = rules[ '*' ] ? '*' : element.name, className = element.attributes && element.attributes[ 'class' ], style; if ( name in rules ) { style = rules[ name ]; if ( typeof style == 'object' ) style = style[ className ]; // Maintain style rules priorities. style && element.addStyle( style, true ); } }; } } return false; }, 'p' : function( element ) { // This's a fall-back approach to recognize list item in FF3.6, // as it's not perfect as not all list style (e.g. "heading list") is shipped // with this pattern. (#6662) if ( /MsoListParagraph/.exec( element.attributes[ 'class' ] ) ) { var bulletText = element.firstChild( function( node ) { return node.type == CKEDITOR.NODE_TEXT && !containsNothingButSpaces( node.parent ); }); var bullet = bulletText && bulletText.parent, bulletAttrs = bullet && bullet.attributes; bulletAttrs && !bulletAttrs.style && ( bulletAttrs.style = 'mso-list: Ignore;' ); } element.filterChildren(); // Is the paragraph actually a list item? if ( resolveListItem( element ) ) return; // Adapt paragraph formatting to editor's convention // according to enter-mode. if ( config.enterMode == CKEDITOR.ENTER_BR ) { // We suffer from attribute/style lost in this situation. delete element.name; element.add( new CKEDITOR.htmlParser.element( 'br' ) ); } else elementMigrateFilter( config[ 'format_' + ( config.enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' ) ] )( element ); }, 'div' : function( element ) { // Aligned table with no text surrounded is represented by a wrapper div, from which // table cells inherit as text-align styles, which is wrong. // Instead we use a clear-float div after the table to properly achieve the same layout. var singleChild = element.onlyChild(); if ( singleChild && singleChild.name == 'table' ) { var attrs = element.attributes; singleChild.attributes = CKEDITOR.tools.extend( singleChild.attributes, attrs ); attrs.style && singleChild.addStyle( attrs.style ); var clearFloatDiv = new CKEDITOR.htmlParser.element( 'div' ); clearFloatDiv.addStyle( 'clear' ,'both' ); element.add( clearFloatDiv ); delete element.name; } }, 'td' : function ( element ) { // 'td' in 'thead' is actually <th>. if ( element.getAncestor( 'thead') ) element.name = 'th'; }, // MS-Word sometimes present list as a mixing of normal list // and pseudo-list, normalize the previous ones into pseudo form. 'ol' : flattenList, 'ul' : flattenList, 'dl' : flattenList, 'font' : function( element ) { // Drop the font tag if it comes from list bullet text. if ( isListBulletIndicator( element.parent ) ) { delete element.name; return; } element.filterChildren(); var attrs = element.attributes, styleText = attrs.style, parent = element.parent; if ( 'font' == parent.name ) // Merge nested <font> tags. { CKEDITOR.tools.extend( parent.attributes, element.attributes ); styleText && parent.addStyle( styleText ); delete element.name; } // Convert the merged into a span with all attributes preserved. else { styleText = styleText || ''; // IE's having those deprecated attributes, normalize them. if ( attrs.color ) { attrs.color != '#000000' && ( styleText += 'color:' + attrs.color + ';' ); delete attrs.color; } if ( attrs.face ) { styleText += 'font-family:' + attrs.face + ';'; delete attrs.face; } // TODO: Mapping size in ranges of xx-small, // x-small, small, medium, large, x-large, xx-large. if ( attrs.size ) { styleText += 'font-size:' + ( attrs.size > 3 ? 'large' : ( attrs.size < 3 ? 'small' : 'medium' ) ) + ';'; delete attrs.size; } element.name = 'span'; element.addStyle( styleText ); } }, 'span' : function( element ) { // Remove the span if it comes from list bullet text. if ( isListBulletIndicator( element.parent ) ) return false; element.filterChildren(); if ( containsNothingButSpaces( element ) ) { delete element.name; return null; } // List item bullet type is supposed to be indicated by // the text of a span with style 'mso-list : Ignore' or an image. if ( isListBulletIndicator( element ) ) { var listSymbolNode = element.firstChild( function( node ) { return node.value || node.name == 'img'; }); var listSymbol = listSymbolNode && ( listSymbolNode.value || 'l.' ), listType = listSymbol && listSymbol.match( /^(?:[(]?)([^\s]+?)([.)]?)$/ ); if ( listType ) { var marker = createListBulletMarker( listType, listSymbol ); // Some non-existed list items might be carried by an inconsequential list, indicate by "mso-hide:all/display:none", // those are to be removed later, now mark it with "cke:ignored". var ancestor = element.getAncestor( 'span' ); if ( ancestor && (/ mso-hide:\s*all|display:\s*none /).test( ancestor.attributes.style ) ) marker.attributes[ 'cke:ignored' ] = 1; return marker; } } // Update the src attribute of image element with href. var children = element.children, attrs = element.attributes, styleText = attrs && attrs.style, firstChild = children && children[ 0 ]; // Assume MS-Word mostly carry font related styles on <span>, // adapting them to editor's convention. if ( styleText ) { attrs.style = stylesFilter( [ // Drop 'inline-height' style which make lines overlapping. [ 'line-height' ], [ ( /^font-family$/ ), null, !removeFontStyles ? styleMigrateFilter( config[ 'font_style' ], 'family' ) : null ] , [ ( /^font-size$/ ), null, !removeFontStyles ? styleMigrateFilter( config[ 'fontSize_style' ], 'size' ) : null ] , [ ( /^color$/ ), null, !removeFontStyles ? styleMigrateFilter( config[ 'colorButton_foreStyle' ], 'color' ) : null ] , [ ( /^background-color$/ ), null, !removeFontStyles ? styleMigrateFilter( config[ 'colorButton_backStyle' ], 'color' ) : null ] ] )( styleText, element ) || ''; } return null; }, // Migrate basic style formats to editor configured ones. 'b' : elementMigrateFilter( config[ 'coreStyles_bold' ] ), 'i' : elementMigrateFilter( config[ 'coreStyles_italic' ] ), 'u' : elementMigrateFilter( config[ 'coreStyles_underline' ] ), 's' : elementMigrateFilter( config[ 'coreStyles_strike' ] ), 'sup' : elementMigrateFilter( config[ 'coreStyles_superscript' ] ), 'sub' : elementMigrateFilter( config[ 'coreStyles_subscript' ] ), // Editor doesn't support anchor with content currently (#3582), // drop such anchors with content preserved. 'a' : function( element ) { var attrs = element.attributes; if ( attrs && !attrs.href && attrs.name ) delete element.name; else if ( CKEDITOR.env.webkit && attrs.href && attrs.href.match( /file:\/\/\/[\S]+#/i ) ) attrs.href = attrs.href.replace( /file:\/\/\/[^#]+/i,'' ); }, 'cke:listbullet' : function( element ) { if ( element.getAncestor( /h\d/ ) && !config.pasteFromWordNumberedHeadingToList ) delete element.name; } }, attributeNames : [ // Remove onmouseover and onmouseout events (from MS Word comments effect) [ ( /^onmouse(:?out|over)/ ), '' ], // Onload on image element. [ ( /^onload$/ ), '' ], // Remove office and vml attribute from elements. [ ( /(?:v|o):\w+/ ), '' ], // Remove lang/language attributes. [ ( /^lang/ ), '' ] ], attributes : { 'style' : stylesFilter( removeStyles ? // Provide a white-list of styles that we preserve, those should // be the ones that could later be altered with editor tools. [ // Leave list-style-type [ ( /^list-style-type$/ ), null ], // Preserve margin-left/right which used as default indent style in the editor. [ ( /^margin$|^margin-(?!bottom|top)/ ), null, function( value, element, name ) { if ( element.name in { p : 1, div : 1 } ) { var indentStyleName = config.contentsLangDirection == 'ltr' ? 'margin-left' : 'margin-right'; // Extract component value from 'margin' shorthand. if ( name == 'margin' ) { value = getStyleComponents( name, value, [ indentStyleName ] )[ indentStyleName ]; } else if ( name != indentStyleName ) return null; if ( value && !emptyMarginRegex.test( value ) ) return [ indentStyleName, value ]; } return null; } ], // Preserve clear float style. [ ( /^clear$/ ) ], [ ( /^border.*|margin.*|vertical-align|float$/ ), null, function( value, element ) { if ( element.name == 'img' ) return value; } ], [ (/^width|height$/ ), null, function( value, element ) { if ( element.name in { table : 1, td : 1, th : 1, img : 1 } ) return value; } ] ] : // Otherwise provide a black-list of styles that we remove. [ [ ( /^mso-/ ) ], // Fixing color values. [ ( /-color$/ ), null, function( value ) { if ( value == 'transparent' ) return false; if ( CKEDITOR.env.gecko ) return value.replace( /-moz-use-text-color/g, 'transparent' ); } ], // Remove empty margin values, e.g. 0.00001pt 0em 0pt [ ( /^margin$/ ), emptyMarginRegex ], [ 'text-indent', '0cm' ], [ 'page-break-before' ], [ 'tab-stops' ], [ 'display', 'none' ], removeFontStyles ? [ ( /font-?/ ) ] : null ], removeStyles ), // Prefer width styles over 'width' attributes. 'width' : function( value, element ) { if ( element.name in dtd.$tableContent ) return false; }, // Prefer border styles over table 'border' attributes. 'border' : function( value, element ) { if ( element.name in dtd.$tableContent ) return false; }, // Only Firefox carry style sheet from MS-Word, which // will be applied by us manually. For other browsers // the css className is useless. 'class' : falsyFilter, // MS-Word always generate 'background-color' along with 'bgcolor', // simply drop the deprecated attributes. 'bgcolor' : falsyFilter, // Deprecate 'valign' attribute in favor of 'vertical-align'. 'valign' : removeStyles ? falsyFilter : function( value, element ) { element.addStyle( 'vertical-align', value ); return false; } }, // Fore none-IE, some useful data might be buried under these IE-conditional // comments where RegExp were the right approach to dig them out where usual approach // is transform it into a fake element node which hold the desired data. comment : !CKEDITOR.env.ie ? function( value, node ) { var imageInfo = value.match( /<img.*?>/ ), listInfo = value.match( /^\[if !supportLists\]([\s\S]*?)\[endif\]$/ ); // Seek for list bullet indicator. if ( listInfo ) { // Bullet symbol could be either text or an image. var listSymbol = listInfo[ 1 ] || ( imageInfo && 'l.' ), listType = listSymbol && listSymbol.match( />(?:[(]?)([^\s]+?)([.)]?)</ ); return createListBulletMarker( listType, listSymbol ); } // Reveal the <img> element in conditional comments for Firefox. if ( CKEDITOR.env.gecko && imageInfo ) { var img = CKEDITOR.htmlParser.fragment.fromHtml( imageInfo[ 0 ] ).children[ 0 ], previousComment = node.previous, // Try to dig the real image link from vml markup from previous comment text. imgSrcInfo = previousComment && previousComment.value.match( /<v:imagedata[^>]*o:href=['"](.*?)['"]/ ), imgSrc = imgSrcInfo && imgSrcInfo[ 1 ]; // Is there a real 'src' url to be used? imgSrc && ( img.attributes.src = imgSrc ); return img; } return false; } : falsyFilter }; } }); // The paste processor here is just a reduced copy of html data processor. var pasteProcessor = function() { this.dataFilter = new CKEDITOR.htmlParser.filter(); }; pasteProcessor.prototype = { toHtml : function( data ) { var fragment = CKEDITOR.htmlParser.fragment.fromHtml( data, false ), writer = new CKEDITOR.htmlParser.basicWriter(); fragment.writeHtml( writer, this.dataFilter ); return writer.getHtml( true ); } }; CKEDITOR.cleanWord = function( data, editor ) { // Firefox will be confused by those downlevel-revealed IE conditional // comments, fixing them first( convert it to upperlevel-revealed one ). // e.g. <![if !vml]>...<![endif]> if ( CKEDITOR.env.gecko ) data = data.replace( /(<!--\[if[^<]*?\])-->([\S\s]*?)<!--(\[endif\]-->)/gi, '$1$2$3' ); var dataProcessor = new pasteProcessor(), dataFilter = dataProcessor.dataFilter; // These rules will have higher priorities than default ones. dataFilter.addRules( CKEDITOR.plugins.pastefromword.getRules( editor ) ); // Allow extending data filter rules. editor.fire( 'beforeCleanWord', { filter : dataFilter } ); try { data = dataProcessor.toHtml( data, false ); } catch ( e ) { alert( editor.lang.pastefromword.error ); } /* Below post processing those things that are unable to delivered by filter rules. */ // Remove 'cke' namespaced attribute used in filter rules as marker. data = data.replace( /cke:.*?".*?"/g, '' ); // Remove empty style attribute. data = data.replace( /style=""/g, '' ); // Remove the dummy spans ( having no inline style ). data = data.replace( /<span>/g, '' ); return data; }; })(); /** * Whether to ignore all font related formatting styles, including: * <ul> <li>font size;</li> * <li>font family;</li> * <li>font foreground/background color.</li></ul> * @name CKEDITOR.config.pasteFromWordRemoveFontStyles * @since 3.1 * @type Boolean * @default true * @example * config.pasteFromWordRemoveFontStyles = false; */ /** * Whether to transform MS Word outline numbered headings into lists. * @name CKEDITOR.config.pasteFromWordNumberedHeadingToList * @since 3.1 * @type Boolean * @default false * @example * config.pasteFromWordNumberedHeadingToList = true; */ /** * Whether to remove element styles that can't be managed with the editor. Note * that this doesn't handle the font specific styles, which depends on the * {@link CKEDITOR.config.pasteFromWordRemoveFontStyles} setting instead. * @name CKEDITOR.config.pasteFromWordRemoveStyles * @since 3.1 * @type Boolean * @default true * @example * config.pasteFromWordRemoveStyles = false; */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview The "wysiwygarea" plugin. It registers the "wysiwyg" editing * mode, which handles the main editing area space. */ (function() { // Matching an empty paragraph at the end of document. var emptyParagraphRegexp = /(^|<body\b[^>]*>)\s*<(p|div|address|h\d|center|pre)[^>]*>\s*(?:<br[^>]*>|&nbsp;|\u00A0|&#160;)?\s*(:?<\/\2>)?\s*(?=$|<\/body>)/gi; var notWhitespaceEval = CKEDITOR.dom.walker.whitespaces( true ); // Elements that could blink the cursor anchoring beside it, like hr, page-break. (#6554) function nonEditable( element ) { return element.isBlockBoundary() && CKEDITOR.dtd.$empty[ element.getName() ]; } function onInsert( insertFunc ) { return function( evt ) { if ( this.mode == 'wysiwyg' ) { this.focus(); this.fire( 'saveSnapshot' ); insertFunc.call( this, evt.data ); // Save snaps after the whole execution completed. // This's a workaround for make DOM modification's happened after // 'insertElement' to be included either, e.g. Form-based dialogs' 'commitContents' // call. CKEDITOR.tools.setTimeout( function() { this.fire( 'saveSnapshot' ); }, 0, this ); } }; } function doInsertHtml( data ) { if ( this.dataProcessor ) data = this.dataProcessor.toHtml( data ); if ( !data ) return; // HTML insertion only considers the first range. var selection = this.getSelection(), range = selection.getRanges()[ 0 ]; if ( range.checkReadOnly() ) return; // Opera: force block splitting when pasted content contains block. (#7801) if ( CKEDITOR.env.opera ) { var path = new CKEDITOR.dom.elementPath( range.startContainer ); if ( path.block ) { var nodes = CKEDITOR.htmlParser.fragment.fromHtml( data, false ).children; for ( var i = 0, count = nodes.length; i < count; i++ ) { if ( nodes[ i ]._.isBlockLike ) { range.splitBlock( this.enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p' ); range.insertNode( range.document.createText( '' ) ); range.select(); break; } } } } if ( CKEDITOR.env.ie ) { var selIsLocked = selection.isLocked; if ( selIsLocked ) selection.unlock(); var $sel = selection.getNative(); // Delete control selections to avoid IE bugs on pasteHTML. if ( $sel.type == 'Control' ) $sel.clear(); else if ( selection.getType() == CKEDITOR.SELECTION_TEXT ) { // Due to IE bugs on handling contenteditable=false blocks // (#6005), we need to make some checks and eventually // delete the selection first. range = selection.getRanges()[ 0 ]; var endContainer = range && range.endContainer; if ( endContainer && endContainer.type == CKEDITOR.NODE_ELEMENT && endContainer.getAttribute( 'contenteditable' ) == 'false' && range.checkBoundaryOfElement( endContainer, CKEDITOR.END ) ) { range.setEndAfter( range.endContainer ); range.deleteContents(); } } $sel.createRange().pasteHTML( data ); if ( selIsLocked ) this.getSelection().lock(); } else this.document.$.execCommand( 'inserthtml', false, data ); // Webkit does not scroll to the cursor position after pasting (#5558) if ( CKEDITOR.env.webkit ) { selection = this.getSelection(); selection.scrollIntoView(); } } function doInsertText( text ) { var selection = this.getSelection(), mode = selection.getStartElement().hasAscendant( 'pre', true ) ? CKEDITOR.ENTER_BR : this.config.enterMode, isEnterBrMode = mode == CKEDITOR.ENTER_BR; var html = CKEDITOR.tools.htmlEncode( text.replace( /\r\n|\r/g, '\n' ) ); // Convert leading and trailing whitespaces into &nbsp; html = html.replace( /^[ \t]+|[ \t]+$/g, function( match, offset, s ) { if ( match.length == 1 ) // one space, preserve it return '&nbsp;'; else if ( !offset ) // beginning of block return CKEDITOR.tools.repeat( '&nbsp;', match.length - 1 ) + ' '; else // end of block return ' ' + CKEDITOR.tools.repeat( '&nbsp;', match.length - 1 ); } ); // Convert subsequent whitespaces into &nbsp; html = html.replace( /[ \t]{2,}/g, function ( match ) { return CKEDITOR.tools.repeat( '&nbsp;', match.length - 1 ) + ' '; } ); var paragraphTag = mode == CKEDITOR.ENTER_P ? 'p' : 'div'; // Two line-breaks create one paragraph. if ( !isEnterBrMode ) { html = html.replace( /(\n{2})([\s\S]*?)(?:$|\1)/g, function( match, group1, text ) { return '<'+paragraphTag + '>' + text + '</' + paragraphTag + '>'; }); } // One <br> per line-break. html = html.replace( /\n/g, '<br>' ); // Compensate padding <br> for non-IE. if ( !( isEnterBrMode || CKEDITOR.env.ie ) ) { html = html.replace( new RegExp( '<br>(?=</' + paragraphTag + '>)' ), function( match ) { return CKEDITOR.tools.repeat( match, 2 ); } ); } // Inline styles have to be inherited in Firefox. if ( CKEDITOR.env.gecko || CKEDITOR.env.webkit ) { var path = new CKEDITOR.dom.elementPath( selection.getStartElement() ), context = []; for ( var i = 0; i < path.elements.length; i++ ) { var tag = path.elements[ i ].getName(); if ( tag in CKEDITOR.dtd.$inline ) context.unshift( path.elements[ i ].getOuterHtml().match( /^<.*?>/) ); else if ( tag in CKEDITOR.dtd.$block ) break; } // Reproduce the context by preceding the pasted HTML with opening inline tags. html = context.join( '' ) + html; } doInsertHtml.call( this, html ); } function doInsertElement( element ) { var selection = this.getSelection(), ranges = selection.getRanges(), elementName = element.getName(), isBlock = CKEDITOR.dtd.$block[ elementName ]; var selIsLocked = selection.isLocked; if ( selIsLocked ) selection.unlock(); var range, clone, lastElement, bookmark; for ( var i = ranges.length - 1 ; i >= 0 ; i-- ) { range = ranges[ i ]; if ( !range.checkReadOnly() ) { // Remove the original contents, merge splitted nodes. range.deleteContents( 1 ); clone = !i && element || element.clone( 1 ); // If we're inserting a block at dtd-violated position, split // the parent blocks until we reach blockLimit. var current, dtd; if ( isBlock ) { while ( ( current = range.getCommonAncestor( 0, 1 ) ) && ( dtd = CKEDITOR.dtd[ current.getName() ] ) && !( dtd && dtd [ elementName ] ) ) { // Split up inline elements. if ( current.getName() in CKEDITOR.dtd.span ) range.splitElement( current ); // If we're in an empty block which indicate a new paragraph, // simply replace it with the inserting block.(#3664) else if ( range.checkStartOfBlock() && range.checkEndOfBlock() ) { range.setStartBefore( current ); range.collapse( true ); current.remove(); } else range.splitBlock(); } } // Insert the new node. range.insertNode( clone ); // Save the last element reference so we can make the // selection later. if ( !lastElement ) lastElement = clone; } } if ( lastElement ) { range.moveToPosition( lastElement, CKEDITOR.POSITION_AFTER_END ); // If we're inserting a block element immediatelly followed by // another block element, the selection must move there. (#3100,#5436) if ( isBlock ) { var next = lastElement.getNext( notWhitespaceEval ), nextName = next && next.type == CKEDITOR.NODE_ELEMENT && next.getName(); // Check if it's a block element that accepts text. if ( nextName && CKEDITOR.dtd.$block[ nextName ] && CKEDITOR.dtd[ nextName ]['#'] ) range.moveToElementEditStart( next ); } } selection.selectRanges( [ range ] ); if ( selIsLocked ) this.getSelection().lock(); } // DOM modification here should not bother dirty flag.(#4385) function restoreDirty( editor ) { if ( !editor.checkDirty() ) setTimeout( function(){ editor.resetDirty(); }, 0 ); } var isNotWhitespace = CKEDITOR.dom.walker.whitespaces( true ), isNotBookmark = CKEDITOR.dom.walker.bookmark( false, true ); function isNotEmpty( node ) { return isNotWhitespace( node ) && isNotBookmark( node ); } function isNbsp( node ) { return node.type == CKEDITOR.NODE_TEXT && CKEDITOR.tools.trim( node.getText() ).match( /^(?:&nbsp;|\xa0)$/ ); } function restoreSelection( selection ) { if ( selection.isLocked ) { selection.unlock(); setTimeout( function() { selection.lock(); }, 0 ); } } function isBlankParagraph( block ) { return block.getOuterHtml().match( emptyParagraphRegexp ); } isNotWhitespace = CKEDITOR.dom.walker.whitespaces( true ); // Gecko need a key event to 'wake up' the editing // ability when document is empty.(#3864, #5781) function activateEditing( editor ) { var win = editor.window, doc = editor.document, body = editor.document.getBody(), bodyFirstChild = body.getFirst(), bodyChildsNum = body.getChildren().count(); if ( !bodyChildsNum || bodyChildsNum == 1 && bodyFirstChild.type == CKEDITOR.NODE_ELEMENT && bodyFirstChild.hasAttribute( '_moz_editor_bogus_node' ) ) { restoreDirty( editor ); // Memorize scroll position to restore it later (#4472). var hostDocument = editor.element.getDocument(); var hostDocumentElement = hostDocument.getDocumentElement(); var scrollTop = hostDocumentElement.$.scrollTop; var scrollLeft = hostDocumentElement.$.scrollLeft; // Simulating keyboard character input by dispatching a keydown of white-space text. var keyEventSimulate = doc.$.createEvent( "KeyEvents" ); keyEventSimulate.initKeyEvent( 'keypress', true, true, win.$, false, false, false, false, 0, 32 ); doc.$.dispatchEvent( keyEventSimulate ); if ( scrollTop != hostDocumentElement.$.scrollTop || scrollLeft != hostDocumentElement.$.scrollLeft ) hostDocument.getWindow().$.scrollTo( scrollLeft, scrollTop ); // Restore the original document status by placing the cursor before a bogus br created (#5021). bodyChildsNum && body.getFirst().remove(); doc.getBody().appendBogus(); var nativeRange = new CKEDITOR.dom.range( doc ); nativeRange.setStartAt( body , CKEDITOR.POSITION_AFTER_START ); nativeRange.select(); } } /** * Auto-fixing block-less content by wrapping paragraph (#3190), prevent * non-exitable-block by padding extra br.(#3189) */ function onSelectionChangeFixBody( evt ) { var editor = evt.editor, path = evt.data.path, blockLimit = path.blockLimit, selection = evt.data.selection, range = selection.getRanges()[0], body = editor.document.getBody(), enterMode = editor.config.enterMode; if ( CKEDITOR.env.gecko ) { activateEditing( editor ); // Ensure bogus br could help to move cursor (out of styles) to the end of block. (#7041) var pathBlock = path.block || path.blockLimit, lastNode = pathBlock && pathBlock.getLast( isNotEmpty ); // Check some specialities of the current path block: // 1. It is really displayed as block; (#7221) // 2. It doesn't end with one inner block; (#7467) // 3. It doesn't have bogus br yet. if ( pathBlock && pathBlock.isBlockBoundary() && !( lastNode && lastNode.type == CKEDITOR.NODE_ELEMENT && lastNode.isBlockBoundary() ) && !pathBlock.is( 'pre' ) && !pathBlock.getBogus() ) { pathBlock.appendBogus(); } } // When we're in block enter mode, a new paragraph will be established // to encapsulate inline contents right under body. (#3657) if ( editor.config.autoParagraph !== false && enterMode != CKEDITOR.ENTER_BR && range.collapsed && blockLimit.getName() == 'body' && !path.block ) { var fixedBlock = range.fixBlock( true, editor.config.enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p' ); // For IE, we should remove any filler node which was introduced before. if ( CKEDITOR.env.ie ) { var first = fixedBlock.getFirst( isNotEmpty ); first && isNbsp( first ) && first.remove(); } // If the fixed block is actually blank and is already followed by an exitable blank // block, we should revert the fix and move into the existed one. (#3684) if ( isBlankParagraph( fixedBlock ) ) { var element = fixedBlock.getNext( isNotWhitespace ); if ( element && element.type == CKEDITOR.NODE_ELEMENT && !nonEditable( element ) ) { range.moveToElementEditStart( element ); fixedBlock.remove(); } else { element = fixedBlock.getPrevious( isNotWhitespace ); if ( element && element.type == CKEDITOR.NODE_ELEMENT && !nonEditable( element ) ) { range.moveToElementEditEnd( element ); fixedBlock.remove(); } } } range.select(); // Cancel this selection change in favor of the next (correct). (#6811) evt.cancel(); } // Browsers are incapable of moving cursor out of certain block elements (e.g. table, div, pre) // at the end of document, makes it unable to continue adding content, we have to make this // easier by opening an new empty paragraph. var testRange = new CKEDITOR.dom.range( editor.document ); testRange.moveToElementEditEnd( editor.document.getBody() ); var testPath = new CKEDITOR.dom.elementPath( testRange.startContainer ); if ( !testPath.blockLimit.is( 'body') ) { var paddingBlock; if ( enterMode != CKEDITOR.ENTER_BR ) paddingBlock = body.append( editor.document.createElement( enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' ) ); else paddingBlock = body; if ( !CKEDITOR.env.ie ) paddingBlock.appendBogus(); } } CKEDITOR.plugins.add( 'wysiwygarea', { requires : [ 'editingblock' ], init : function( editor ) { var fixForBody = ( editor.config.enterMode != CKEDITOR.ENTER_BR && editor.config.autoParagraph !== false ) ? editor.config.enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p' : false; var frameLabel = editor.lang.editorTitle.replace( '%1', editor.name ); var contentDomReadyHandler; editor.on( 'editingBlockReady', function() { var mainElement, iframe, isLoadingData, isPendingFocus, frameLoaded, fireMode; // Support for custom document.domain in IE. var isCustomDomain = CKEDITOR.env.isCustomDomain(); // Creates the iframe that holds the editable document. var createIFrame = function( data ) { if ( iframe ) iframe.remove(); var src = 'document.open();' + // The document domain must be set any time we // call document.open(). ( isCustomDomain ? ( 'document.domain="' + document.domain + '";' ) : '' ) + 'document.close();'; // With IE, the custom domain has to be taken care at first, // for other browers, the 'src' attribute should be left empty to // trigger iframe's 'load' event. src = CKEDITOR.env.air ? 'javascript:void(0)' : CKEDITOR.env.ie ? 'javascript:void(function(){' + encodeURIComponent( src ) + '}())' : ''; iframe = CKEDITOR.dom.element.createFromHtml( '<iframe' + ' style="width:100%;height:100%"' + ' frameBorder="0"' + ' title="' + frameLabel + '"' + ' src="' + src + '"' + ' tabIndex="' + ( CKEDITOR.env.webkit? -1 : editor.tabIndex ) + '"' + ' allowTransparency="true"' + '></iframe>' ); // Running inside of Firefox chrome the load event doesn't bubble like in a normal page (#5689) if ( document.location.protocol == 'chrome:' ) CKEDITOR.event.useCapture = true; // With FF, it's better to load the data on iframe.load. (#3894,#4058) iframe.on( 'load', function( ev ) { frameLoaded = 1; ev.removeListener(); var doc = iframe.getFrameDocument(); doc.write( data ); CKEDITOR.env.air && contentDomReady( doc.getWindow().$ ); }); // Reset adjustment back to default (#5689) if ( document.location.protocol == 'chrome:' ) CKEDITOR.event.useCapture = false; mainElement.append( iframe ); }; // The script that launches the bootstrap logic on 'domReady', so the document // is fully editable even before the editing iframe is fully loaded (#4455). contentDomReadyHandler = CKEDITOR.tools.addFunction( contentDomReady ); var activationScript = '<script id="cke_actscrpt" type="text/javascript" data-cke-temp="1">' + ( isCustomDomain ? ( 'document.domain="' + document.domain + '";' ) : '' ) + 'window.parent.CKEDITOR.tools.callFunction( ' + contentDomReadyHandler + ', window );' + '</script>'; // Editing area bootstrap code. function contentDomReady( domWindow ) { if ( !frameLoaded ) return; frameLoaded = 0; editor.fire( 'ariaWidget', iframe ); var domDocument = domWindow.document, body = domDocument.body; // Remove this script from the DOM. var script = domDocument.getElementById( "cke_actscrpt" ); script && script.parentNode.removeChild( script ); body.spellcheck = !editor.config.disableNativeSpellChecker; var editable = !editor.readOnly; if ( CKEDITOR.env.ie ) { // Don't display the focus border. body.hideFocus = true; // Disable and re-enable the body to avoid IE from // taking the editing focus at startup. (#141 / #523) body.disabled = true; body.contentEditable = editable; body.removeAttribute( 'disabled' ); } else { // Avoid opening design mode in a frame window thread, // which will cause host page scrolling.(#4397) setTimeout( function() { // Prefer 'contentEditable' instead of 'designMode'. (#3593) if ( CKEDITOR.env.gecko && CKEDITOR.env.version >= 10900 || CKEDITOR.env.opera ) domDocument.$.body.contentEditable = editable; else if ( CKEDITOR.env.webkit ) domDocument.$.body.parentNode.contentEditable = editable; else domDocument.$.designMode = editable? 'off' : 'on'; }, 0 ); } editable && CKEDITOR.env.gecko && CKEDITOR.tools.setTimeout( activateEditing, 0, null, editor ); domWindow = editor.window = new CKEDITOR.dom.window( domWindow ); domDocument = editor.document = new CKEDITOR.dom.document( domDocument ); editable && domDocument.on( 'dblclick', function( evt ) { var element = evt.data.getTarget(), data = { element : element, dialog : '' }; editor.fire( 'doubleclick', data ); data.dialog && editor.openDialog( data.dialog ); }); // Prevent automatic submission in IE #6336 CKEDITOR.env.ie && domDocument.on( 'click', function( evt ) { var element = evt.data.getTarget(); if ( element.is( 'input' ) ) { var type = element.getAttribute( 'type' ); if ( type == 'submit' || type == 'reset' ) evt.data.preventDefault(); } }); // Gecko/Webkit need some help when selecting control type elements. (#3448) if ( !( CKEDITOR.env.ie || CKEDITOR.env.opera ) ) { domDocument.on( 'mousedown', function( ev ) { var control = ev.data.getTarget(); if ( control.is( 'img', 'hr', 'input', 'textarea', 'select' ) ) editor.getSelection().selectElement( control ); } ); } if ( CKEDITOR.env.gecko ) { domDocument.on( 'mouseup', function( ev ) { if ( ev.data.$.button == 2 ) { var target = ev.data.getTarget(); // Prevent right click from selecting an empty block even // when selection is anchored inside it. (#5845) if ( !target.getOuterHtml().replace( emptyParagraphRegexp, '' ) ) { var range = new CKEDITOR.dom.range( domDocument ); range.moveToElementEditStart( target ); range.select( true ); } } } ); } // Prevent the browser opening links in read-only blocks. (#6032) domDocument.on( 'click', function( ev ) { ev = ev.data; if ( ev.getTarget().is( 'a' ) && ev.$.button != 2 ) ev.preventDefault(); }); // Webkit: avoid from editing form control elements content. if ( CKEDITOR.env.webkit ) { // Mark that cursor will right blinking (#7113). domDocument.on( 'mousedown', function() { wasFocused = 1; } ); // Prevent from tick checkbox/radiobox/select domDocument.on( 'click', function( ev ) { if ( ev.data.getTarget().is( 'input', 'select' ) ) ev.data.preventDefault(); } ); // Prevent from editig textfield/textarea value. domDocument.on( 'mouseup', function( ev ) { if ( ev.data.getTarget().is( 'input', 'textarea' ) ) ev.data.preventDefault(); } ); } // IE standard compliant in editing frame doesn't focus the editor when // clicking outside actual content, manually apply the focus. (#1659) if ( editable && CKEDITOR.env.ie && domDocument.$.compatMode == 'CSS1Compat' || CKEDITOR.env.gecko || CKEDITOR.env.opera ) { var htmlElement = domDocument.getDocumentElement(); htmlElement.on( 'mousedown', function( evt ) { // Setting focus directly on editor doesn't work, we // have to use here a temporary element to 'redirect' // the focus. if ( evt.data.getTarget().equals( htmlElement ) ) { if ( CKEDITOR.env.gecko && CKEDITOR.env.version >= 10900 ) blinkCursor(); focusGrabber.focus(); } } ); } var focusTarget = CKEDITOR.env.ie ? iframe : domWindow; focusTarget.on( 'blur', function() { editor.focusManager.blur(); }); var wasFocused; focusTarget.on( 'focus', function() { var doc = editor.document; if ( editable && CKEDITOR.env.gecko && CKEDITOR.env.version >= 10900 ) blinkCursor(); else if ( CKEDITOR.env.opera ) doc.getBody().focus(); // Webkit needs focus for the first time on the HTML element. (#6153) else if ( CKEDITOR.env.webkit ) { if ( !wasFocused ) { editor.document.getDocumentElement().focus(); wasFocused = 1; } } editor.focusManager.focus(); }); var keystrokeHandler = editor.keystrokeHandler; // Prevent backspace from navigating off the page. keystrokeHandler.blockedKeystrokes[ 8 ] = !editable; keystrokeHandler.attach( domDocument ); domDocument.getDocumentElement().addClass( domDocument.$.compatMode ); // Override keystroke behaviors. editable && domDocument.on( 'keydown', function( evt ) { var keyCode = evt.data.getKeystroke(); // Backspace OR Delete. if ( keyCode in { 8 : 1, 46 : 1 } ) { var sel = editor.getSelection(), selected = sel.getSelectedElement(), range = sel.getRanges()[ 0 ]; // Override keystrokes which should have deletion behavior // on fully selected element . (#4047) (#7645) if ( selected ) { // Make undo snapshot. editor.fire( 'saveSnapshot' ); // Delete any element that 'hasLayout' (e.g. hr,table) in IE8 will // break up the selection, safely manage it here. (#4795) range.moveToPosition( selected, CKEDITOR.POSITION_BEFORE_START ); // Remove the control manually. selected.remove(); range.select(); editor.fire( 'saveSnapshot' ); evt.data.preventDefault(); return; } } } ); // PageUp/PageDown scrolling is broken in document // with standard doctype, manually fix it. (#4736) if ( CKEDITOR.env.ie && domDocument.$.compatMode == 'CSS1Compat' ) { var pageUpDownKeys = { 33 : 1, 34 : 1 }; domDocument.on( 'keydown', function( evt ) { if ( evt.data.getKeystroke() in pageUpDownKeys ) { setTimeout( function () { editor.getSelection().scrollIntoView(); }, 0 ); } } ); } // Prevent IE from leaving new paragraph after deleting all contents in body. (#6966) if ( CKEDITOR.env.ie && editor.config.enterMode != CKEDITOR.ENTER_P ) { domDocument.on( 'selectionchange', function() { var body = domDocument.getBody(), range = editor.getSelection().getRanges()[ 0 ]; if ( body.getHtml().match( /^<p>&nbsp;<\/p>$/i ) && range.startContainer.equals( body ) ) { // Avoid the ambiguity from a real user cursor position. setTimeout( function () { range = editor.getSelection().getRanges()[ 0 ]; if ( !range.startContainer.equals ( 'body' ) ) { body.getFirst().remove( 1 ); range.moveToElementEditEnd( body ); range.select( 1 ); } }, 0 ); } }); } // Adds the document body as a context menu target. if ( editor.contextMenu ) editor.contextMenu.addTarget( domDocument, editor.config.browserContextMenuOnCtrl !== false ); setTimeout( function() { editor.fire( 'contentDom' ); if ( fireMode ) { editor.mode = 'wysiwyg'; editor.fire( 'mode', { previousMode : editor._.previousMode } ); fireMode = false; } isLoadingData = false; if ( isPendingFocus ) { editor.focus(); isPendingFocus = false; } setTimeout( function() { editor.fire( 'dataReady' ); }, 0 ); // IE, Opera and Safari may not support it and throw errors. try { editor.document.$.execCommand( 'enableInlineTableEditing', false, !editor.config.disableNativeTableHandles ); } catch(e) {} if ( editor.config.disableObjectResizing ) { try { editor.document.$.execCommand( 'enableObjectResizing', false, false ); } catch(e) { // For browsers in which the above method failed, we can cancel the resizing on the fly (#4208) editor.document.getBody().on( CKEDITOR.env.ie ? 'resizestart' : 'resize', function( evt ) { evt.data.preventDefault(); }); } } /* * IE BUG: IE might have rendered the iframe with invisible contents. * (#3623). Push some inconsequential CSS style changes to force IE to * refresh it. * * Also, for some unknown reasons, short timeouts (e.g. 100ms) do not * fix the problem. :( */ if ( CKEDITOR.env.ie ) { setTimeout( function() { if ( editor.document ) { var $body = editor.document.$.body; $body.runtimeStyle.marginBottom = '0px'; $body.runtimeStyle.marginBottom = ''; } }, 1000 ); } }, 0 ); } editor.addMode( 'wysiwyg', { load : function( holderElement, data, isSnapshot ) { mainElement = holderElement; if ( CKEDITOR.env.ie && CKEDITOR.env.quirks ) holderElement.setStyle( 'position', 'relative' ); // The editor data "may be dirty" after this // point. editor.mayBeDirty = true; fireMode = true; if ( isSnapshot ) this.loadSnapshotData( data ); else this.loadData( data ); }, loadData : function( data ) { isLoadingData = true; editor._.dataStore = { id : 1 }; var config = editor.config, fullPage = config.fullPage, docType = config.docType; // Build the additional stuff to be included into <head>. var headExtra = '<style type="text/css" data-cke-temp="1">' + editor._.styles.join( '\n' ) + '</style>'; !fullPage && ( headExtra = CKEDITOR.tools.buildStyleHtml( editor.config.contentsCss ) + headExtra ); var baseTag = config.baseHref ? '<base href="' + config.baseHref + '" data-cke-temp="1" />' : ''; if ( fullPage ) { // Search and sweep out the doctype declaration. data = data.replace( /<!DOCTYPE[^>]*>/i, function( match ) { editor.docType = docType = match; return ''; }).replace( /<\?xml\s[^\?]*\?>/i, function( match ) { editor.xmlDeclaration = match; return ''; }); } // Get the HTML version of the data. if ( editor.dataProcessor ) data = editor.dataProcessor.toHtml( data, fixForBody ); if ( fullPage ) { // Check if the <body> tag is available. if ( !(/<body[\s|>]/).test( data ) ) data = '<body>' + data; // Check if the <html> tag is available. if ( !(/<html[\s|>]/).test( data ) ) data = '<html>' + data + '</html>'; // Check if the <head> tag is available. if ( !(/<head[\s|>]/).test( data ) ) data = data.replace( /<html[^>]*>/, '$&<head><title></title></head>' ) ; else if ( !(/<title[\s|>]/).test( data ) ) data = data.replace( /<head[^>]*>/, '$&<title></title>' ) ; // The base must be the first tag in the HEAD, e.g. to get relative // links on styles. baseTag && ( data = data.replace( /<head>/, '$&' + baseTag ) ); // Inject the extra stuff into <head>. // Attention: do not change it before testing it well. (V2) // This is tricky... if the head ends with <meta ... content type>, // Firefox will break. But, it works if we place our extra stuff as // the last elements in the HEAD. data = data.replace( /<\/head\s*>/, headExtra + '$&' ); // Add the DOCTYPE back to it. data = docType + data; } else { data = config.docType + '<html dir="' + config.contentsLangDirection + '"' + ' lang="' + ( config.contentsLanguage || editor.langCode ) + '">' + '<head>' + '<title>' + frameLabel + '</title>' + baseTag + headExtra + '</head>' + '<body' + ( config.bodyId ? ' id="' + config.bodyId + '"' : '' ) + ( config.bodyClass ? ' class="' + config.bodyClass + '"' : '' ) + '>' + data + '</html>'; } // Distinguish bogus to normal BR at the end of document for Mozilla. (#5293). if ( CKEDITOR.env.gecko ) data = data.replace( /<br \/>(?=\s*<\/(:?html|body)>)/, '$&<br type="_moz" />' ); data += activationScript; // The iframe is recreated on each call of setData, so we need to clear DOM objects this.onDispose(); createIFrame( data ); }, getData : function() { var config = editor.config, fullPage = config.fullPage, docType = fullPage && editor.docType, xmlDeclaration = fullPage && editor.xmlDeclaration, doc = iframe.getFrameDocument(); var data = fullPage ? doc.getDocumentElement().getOuterHtml() : doc.getBody().getHtml(); // BR at the end of document is bogus node for Mozilla. (#5293). if ( CKEDITOR.env.gecko ) data = data.replace( /<br>(?=\s*(:?$|<\/body>))/, '' ); if ( editor.dataProcessor ) data = editor.dataProcessor.toDataFormat( data, fixForBody ); // Reset empty if the document contains only one empty paragraph. if ( config.ignoreEmptyParagraph ) data = data.replace( emptyParagraphRegexp, function( match, lookback ) { return lookback; } ); if ( xmlDeclaration ) data = xmlDeclaration + '\n' + data; if ( docType ) data = docType + '\n' + data; return data; }, getSnapshotData : function() { return iframe.getFrameDocument().getBody().getHtml(); }, loadSnapshotData : function( data ) { iframe.getFrameDocument().getBody().setHtml( data ); }, onDispose : function() { if ( !editor.document ) return; editor.document.getDocumentElement().clearCustomData(); editor.document.getBody().clearCustomData(); editor.window.clearCustomData(); editor.document.clearCustomData(); iframe.clearCustomData(); /* * IE BUG: When destroying editor DOM with the selection remains inside * editing area would break IE7/8's selection system, we have to put the editing * iframe offline first. (#3812 and #5441) */ iframe.remove(); }, unload : function( holderElement ) { this.onDispose(); editor.window = editor.document = iframe = mainElement = isPendingFocus = null; editor.fire( 'contentDomUnload' ); }, focus : function() { var win = editor.window; if ( isLoadingData ) isPendingFocus = true; else if ( win ) { // AIR needs a while to focus when moving from a link. CKEDITOR.env.air ? setTimeout( function () { win.focus(); }, 0 ) : win.focus(); editor.selectionChange(); } } }); editor.on( 'insertHtml', onInsert( doInsertHtml ) , null, null, 20 ); editor.on( 'insertElement', onInsert( doInsertElement ), null, null, 20 ); editor.on( 'insertText', onInsert( doInsertText ), null, null, 20 ); // Auto fixing on some document structure weakness to enhance usabilities. (#3190 and #3189) editor.on( 'selectionChange', function( evt ) { if ( editor.readOnly ) return; var sel = editor.getSelection(); // Do it only when selection is not locked. (#8222) if ( sel && !sel.isLocked ) { var isDirty = editor.checkDirty(); editor.fire( 'saveSnapshot', { contentOnly : 1 } ); onSelectionChangeFixBody.call( this, evt ); editor.fire( 'updateSnapshot' ); !isDirty && editor.resetDirty(); } }, null, null, 1 ); }); var titleBackup; // Setting voice label as window title, backup the original one // and restore it before running into use. editor.on( 'contentDom', function() { var title = editor.document.getElementsByTag( 'title' ).getItem( 0 ); title.data( 'cke-title', editor.document.$.title ); editor.document.$.title = frameLabel; }); editor.on( 'readOnly', function() { if ( editor.mode == 'wysiwyg' ) { // Symply reload the wysiwyg area. It'll take care of read-only. var wysiwyg = editor.getMode(); wysiwyg.loadData( wysiwyg.getData() ); } }); // IE>=8 stricts mode doesn't have 'contentEditable' in effect // on element unless it has layout. (#5562) if ( CKEDITOR.document.$.documentMode >= 8 ) { editor.addCss( 'html.CSS1Compat [contenteditable=false]{ min-height:0 !important;}' ); var selectors = []; for ( var tag in CKEDITOR.dtd.$removeEmpty ) selectors.push( 'html.CSS1Compat ' + tag + '[contenteditable=false]' ); editor.addCss( selectors.join( ',' ) + '{ display:inline-block;}' ); } // Set the HTML style to 100% to have the text cursor in affect (#6341) else if ( CKEDITOR.env.gecko ) { editor.addCss( 'html { height: 100% !important; }' ); editor.addCss( 'img:-moz-broken { -moz-force-broken-image-icon : 1; width : 24px; height : 24px; }' ); } /* #3658: [IE6] Editor document has horizontal scrollbar on long lines To prevent this misbehavior, we show the scrollbar always */ /* #6341: The text cursor must be set on the editor area. */ /* #6632: Avoid having "text" shape of cursor in IE7 scrollbars.*/ editor.addCss( 'html { _overflow-y: scroll; cursor: text; *cursor:auto;}' ); // Use correct cursor for these elements editor.addCss( 'img, input, textarea { cursor: default;}' ); // Switch on design mode for a short while and close it after then. function blinkCursor( retry ) { if ( editor.readOnly ) return; CKEDITOR.tools.tryThese( function() { editor.document.$.designMode = 'on'; setTimeout( function() { editor.document.$.designMode = 'off'; if ( CKEDITOR.currentInstance == editor ) editor.document.getBody().focus(); }, 50 ); }, function() { // The above call is known to fail when parent DOM // tree layout changes may break design mode. (#5782) // Refresh the 'contentEditable' is a cue to this. editor.document.$.designMode = 'off'; var body = editor.document.getBody(); body.setAttribute( 'contentEditable', false ); body.setAttribute( 'contentEditable', true ); // Try it again once.. !retry && blinkCursor( 1 ); }); } // Create an invisible element to grab focus. if ( CKEDITOR.env.gecko || CKEDITOR.env.ie || CKEDITOR.env.opera ) { var focusGrabber; editor.on( 'uiReady', function() { focusGrabber = editor.container.append( CKEDITOR.dom.element.createFromHtml( // Use 'span' instead of anything else to fly under the screen-reader radar. (#5049) '<span tabindex="-1" style="position:absolute;" role="presentation"></span>' ) ); focusGrabber.on( 'focus', function() { editor.focus(); } ); editor.focusGrabber = focusGrabber; } ); editor.on( 'destroy', function() { CKEDITOR.tools.removeFunction( contentDomReadyHandler ); focusGrabber.clearCustomData(); delete editor.focusGrabber; } ); } // Disable form elements editing mode provided by some browers. (#5746) editor.on( 'insertElement', function ( evt ) { var element = evt.data; if ( element.type == CKEDITOR.NODE_ELEMENT && ( element.is( 'input' ) || element.is( 'textarea' ) ) ) { // We should flag that the element was locked by our code so // it'll be editable by the editor functions (#6046). var readonly = element.getAttribute( 'contenteditable' ) == 'false'; if ( !readonly ) { element.data( 'cke-editable', element.hasAttribute( 'contenteditable' ) ? 'true' : '1' ); element.setAttribute( 'contenteditable', false ); } } }); } }); // Fixing Firefox 'Back-Forward Cache' break design mode. (#4514) if ( CKEDITOR.env.gecko ) { (function() { var body = document.body; if ( !body ) window.addEventListener( 'load', arguments.callee, false ); else { var currentHandler = body.getAttribute( 'onpageshow' ); body.setAttribute( 'onpageshow', ( currentHandler ? currentHandler + ';' : '') + 'event.persisted && (function(){' + 'var allInstances = CKEDITOR.instances, editor, doc;' + 'for ( var i in allInstances )' + '{' + ' editor = allInstances[ i ];' + ' doc = editor.document;' + ' if ( doc )' + ' {' + ' doc.$.designMode = "off";' + ' doc.$.designMode = "on";' + ' }' + '}' + '})();' ); } } )(); } })(); /** * Disables the ability of resize objects (image and tables) in the editing * area. * @type Boolean * @default false * @example * config.disableObjectResizing = true; */ CKEDITOR.config.disableObjectResizing = false; /** * Disables the "table tools" offered natively by the browser (currently * Firefox only) to make quick table editing operations, like adding or * deleting rows and columns. * @type Boolean * @default true * @example * config.disableNativeTableHandles = false; */ CKEDITOR.config.disableNativeTableHandles = true; /** * Disables the built-in words spell checker if browser provides one.<br /><br /> * * <strong>Note:</strong> Although word suggestions provided by browsers (natively) will not appear in CKEditor's default context menu, * users can always reach the native context menu by holding the <em>Ctrl</em> key when right-clicking if {@link CKEDITOR.config.browserContextMenuOnCtrl} * is enabled or you're simply not using the context menu plugin. * * @type Boolean * @default true * @example * config.disableNativeSpellChecker = false; */ CKEDITOR.config.disableNativeSpellChecker = true; /** * Whether the editor must output an empty value ("") if it's contents is made * by an empty paragraph only. * @type Boolean * @default true * @example * config.ignoreEmptyParagraph = false; */ CKEDITOR.config.ignoreEmptyParagraph = true; /** * Fired when data is loaded and ready for retrieval in an editor instance. * @name CKEDITOR.editor#dataReady * @event */ /** * Whether automatically create wrapping blocks around inline contents inside document body, * this helps to ensure the integrality of the block enter mode. * <strong>Note:</strong> Changing the default value might introduce unpredictable usability issues. * @name CKEDITOR.config.autoParagraph * @since 3.6 * @type Boolean * @default true * @example * config.autoParagraph = false; */ /** * Fired when some elements are added to the document * @name CKEDITOR.editor#ariaWidget * @event * @param {Object} element The element being added */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { CKEDITOR.plugins.add( 'stylescombo', { requires : [ 'richcombo', 'styles' ], init : function( editor ) { var config = editor.config, lang = editor.lang.stylesCombo, styles = {}, stylesList = [], combo; function loadStylesSet( callback ) { editor.getStylesSet( function( stylesDefinitions ) { if ( !stylesList.length ) { var style, styleName; // Put all styles into an Array. for ( var i = 0, count = stylesDefinitions.length ; i < count ; i++ ) { var styleDefinition = stylesDefinitions[ i ]; styleName = styleDefinition.name; style = styles[ styleName ] = new CKEDITOR.style( styleDefinition ); style._name = styleName; style._.enterMode = config.enterMode; stylesList.push( style ); } // Sorts the Array, so the styles get grouped by type. stylesList.sort( sortStyles ); } callback && callback(); }); } editor.ui.addRichCombo( 'Styles', { label : lang.label, title : lang.panelTitle, className : 'cke_styles', panel : { css : editor.skin.editor.css.concat( config.contentsCss ), multiSelect : true, attributes : { 'aria-label' : lang.panelTitle } }, init : function() { combo = this; loadStylesSet( function() { var style, styleName, lastType, type, i, count; // Loop over the Array, adding all items to the // combo. for ( i = 0, count = stylesList.length ; i < count ; i++ ) { style = stylesList[ i ]; styleName = style._name; type = style.type; if ( type != lastType ) { combo.startGroup( lang[ 'panelTitle' + String( type ) ] ); lastType = type; } combo.add( styleName, style.type == CKEDITOR.STYLE_OBJECT ? styleName : style.buildPreview(), styleName ); } combo.commit(); }); }, onClick : function( value ) { editor.focus(); editor.fire( 'saveSnapshot' ); var style = styles[ value ], selection = editor.getSelection(), elementPath = new CKEDITOR.dom.elementPath( selection.getStartElement() ); style[ style.checkActive( elementPath ) ? 'remove' : 'apply' ]( editor.document ); editor.fire( 'saveSnapshot' ); }, onRender : function() { editor.on( 'selectionChange', function( ev ) { var currentValue = this.getValue(), elementPath = ev.data.path, elements = elementPath.elements; // For each element into the elements path. for ( var i = 0, count = elements.length, element ; i < count ; i++ ) { element = elements[i]; // Check if the element is removable by any of // the styles. for ( var value in styles ) { if ( styles[ value ].checkElementRemovable( element, true ) ) { if ( value != currentValue ) this.setValue( value ); return; } } } // If no styles match, just empty it. this.setValue( '' ); }, this); }, onOpen : function() { if ( CKEDITOR.env.ie || CKEDITOR.env.webkit ) editor.focus(); var selection = editor.getSelection(), element = selection.getSelectedElement(), elementPath = new CKEDITOR.dom.elementPath( element || selection.getStartElement() ), counter = [ 0, 0, 0, 0 ]; this.showAll(); this.unmarkAll(); for ( var name in styles ) { var style = styles[ name ], type = style.type; if ( style.checkActive( elementPath ) ) this.mark( name ); else if ( type == CKEDITOR.STYLE_OBJECT && !style.checkApplicable( elementPath ) ) { this.hideItem( name ); counter[ type ]--; } counter[ type ]++; } if ( !counter[ CKEDITOR.STYLE_BLOCK ] ) this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_BLOCK ) ] ); if ( !counter[ CKEDITOR.STYLE_INLINE ] ) this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_INLINE ) ] ); if ( !counter[ CKEDITOR.STYLE_OBJECT ] ) this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_OBJECT ) ] ); }, // Force a reload of the data reset: function() { if ( combo ) { delete combo._.panel; delete combo._.list; combo._.committed = 0; combo._.items = {}; combo._.state = CKEDITOR.TRISTATE_OFF; } styles = {}; stylesList = []; loadStylesSet(); } }); editor.on( 'instanceReady', function() { loadStylesSet(); } ); } }); function sortStyles( styleA, styleB ) { var typeA = styleA.type, typeB = styleB.type; return typeA == typeB ? 0 : typeA == CKEDITOR.STYLE_OBJECT ? -1 : typeB == CKEDITOR.STYLE_OBJECT ? 1 : typeB == CKEDITOR.STYLE_BLOCK ? 1 : -1; } })();
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.add( 'find', { init : function( editor ) { var forms = CKEDITOR.plugins.find; editor.ui.addButton( 'Find', { label : editor.lang.findAndReplace.find, command : 'find' }); var findCommand = editor.addCommand( 'find', new CKEDITOR.dialogCommand( 'find' ) ); findCommand.canUndo = false; findCommand.readOnly = 1; editor.ui.addButton( 'Replace', { label : editor.lang.findAndReplace.replace, command : 'replace' }); var replaceCommand = editor.addCommand( 'replace', new CKEDITOR.dialogCommand( 'replace' ) ); replaceCommand.canUndo = false; CKEDITOR.dialog.add( 'find', this.path + 'dialogs/find.js' ); CKEDITOR.dialog.add( 'replace', this.path + 'dialogs/find.js' ); }, requires : [ 'styles' ] } ); /** * Defines the style to be used to highlight results with the find dialog. * @type Object * @default { element : 'span', styles : { 'background-color' : '#004', 'color' : '#fff' } } * @example * // Highlight search results with blue on yellow. * config.find_highlight = * { * element : 'span', * styles : { 'background-color' : '#ff0', 'color' : '#00f' } * }; */ CKEDITOR.config.find_highlight = { element : 'span', styles : { 'background-color' : '#004', 'color' : '#fff' } };
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { var isReplace; function findEvaluator( node ) { return node.type == CKEDITOR.NODE_TEXT && node.getLength() > 0 && ( !isReplace || !node.isReadOnly() ); } /** * Elements which break characters been considered as sequence. */ function nonCharactersBoundary( node ) { return !( node.type == CKEDITOR.NODE_ELEMENT && node.isBlockBoundary( CKEDITOR.tools.extend( {}, CKEDITOR.dtd.$empty, CKEDITOR.dtd.$nonEditable ) ) ); } /** * Get the cursor object which represent both current character and it's dom * position thing. */ var cursorStep = function() { return { textNode : this.textNode, offset : this.offset, character : this.textNode ? this.textNode.getText().charAt( this.offset ) : null, hitMatchBoundary : this._.matchBoundary }; }; var pages = [ 'find', 'replace' ], fieldsMapping = [ [ 'txtFindFind', 'txtFindReplace' ], [ 'txtFindCaseChk', 'txtReplaceCaseChk' ], [ 'txtFindWordChk', 'txtReplaceWordChk' ], [ 'txtFindCyclic', 'txtReplaceCyclic' ] ]; /** * Synchronize corresponding filed values between 'replace' and 'find' pages. * @param {String} currentPageId The page id which receive values. */ function syncFieldsBetweenTabs( currentPageId ) { var sourceIndex, targetIndex, sourceField, targetField; sourceIndex = currentPageId === 'find' ? 1 : 0; targetIndex = 1 - sourceIndex; var i, l = fieldsMapping.length; for ( i = 0 ; i < l ; i++ ) { sourceField = this.getContentElement( pages[ sourceIndex ], fieldsMapping[ i ][ sourceIndex ] ); targetField = this.getContentElement( pages[ targetIndex ], fieldsMapping[ i ][ targetIndex ] ); targetField.setValue( sourceField.getValue() ); } } var findDialog = function( editor, startupPage ) { // Style object for highlights: (#5018) // 1. Defined as full match style to avoid compromising ordinary text color styles. // 2. Must be apply onto inner-most text to avoid conflicting with ordinary text color styles visually. var highlightStyle = new CKEDITOR.style( CKEDITOR.tools.extend( { attributes : { 'data-cke-highlight': 1 }, fullMatch : 1, ignoreReadonly : 1, childRule : function(){ return 0; } }, editor.config.find_highlight, true ) ); /** * Iterator which walk through the specified range char by char. By * default the walking will not stop at the character boundaries, until * the end of the range is encountered. * @param { CKEDITOR.dom.range } range * @param {Boolean} matchWord Whether the walking will stop at character boundary. */ var characterWalker = function( range , matchWord ) { var self = this; var walker = new CKEDITOR.dom.walker( range ); walker.guard = matchWord ? nonCharactersBoundary : function( node ) { !nonCharactersBoundary( node ) && ( self._.matchBoundary = true ); }; walker[ 'evaluator' ] = findEvaluator; walker.breakOnFalse = 1; if ( range.startContainer.type == CKEDITOR.NODE_TEXT ) { this.textNode = range.startContainer; this.offset = range.startOffset - 1; } this._ = { matchWord : matchWord, walker : walker, matchBoundary : false }; }; characterWalker.prototype = { next : function() { return this.move(); }, back : function() { return this.move( true ); }, move : function( rtl ) { var currentTextNode = this.textNode; // Already at the end of document, no more character available. if ( currentTextNode === null ) return cursorStep.call( this ); this._.matchBoundary = false; // There are more characters in the text node, step forward. if ( currentTextNode && rtl && this.offset > 0 ) { this.offset--; return cursorStep.call( this ); } else if ( currentTextNode && this.offset < currentTextNode.getLength() - 1 ) { this.offset++; return cursorStep.call( this ); } else { currentTextNode = null; // At the end of the text node, walking foward for the next. while ( !currentTextNode ) { currentTextNode = this._.walker[ rtl ? 'previous' : 'next' ].call( this._.walker ); // Stop searching if we're need full word match OR // already reach document end. if ( this._.matchWord && !currentTextNode || this._.walker._.end ) break; } // Found a fresh text node. this.textNode = currentTextNode; if ( currentTextNode ) this.offset = rtl ? currentTextNode.getLength() - 1 : 0; else this.offset = 0; } return cursorStep.call( this ); } }; /** * A range of cursors which represent a trunk of characters which try to * match, it has the same length as the pattern string. */ var characterRange = function( characterWalker, rangeLength ) { this._ = { walker : characterWalker, cursors : [], rangeLength : rangeLength, highlightRange : null, isMatched : 0 }; }; characterRange.prototype = { /** * Translate this range to {@link CKEDITOR.dom.range} */ toDomRange : function() { var range = new CKEDITOR.dom.range( editor.document ); var cursors = this._.cursors; if ( cursors.length < 1 ) { var textNode = this._.walker.textNode; if ( textNode ) range.setStartAfter( textNode ); else return null; } else { var first = cursors[0], last = cursors[ cursors.length - 1 ]; range.setStart( first.textNode, first.offset ); range.setEnd( last.textNode, last.offset + 1 ); } return range; }, /** * Reflect the latest changes from dom range. */ updateFromDomRange : function( domRange ) { var cursor, walker = new characterWalker( domRange ); this._.cursors = []; do { cursor = walker.next(); if ( cursor.character ) this._.cursors.push( cursor ); } while ( cursor.character ); this._.rangeLength = this._.cursors.length; }, setMatched : function() { this._.isMatched = true; }, clearMatched : function() { this._.isMatched = false; }, isMatched : function() { return this._.isMatched; }, /** * Hightlight the current matched chunk of text. */ highlight : function() { // Do not apply if nothing is found. if ( this._.cursors.length < 1 ) return; // Remove the previous highlight if there's one. if ( this._.highlightRange ) this.removeHighlight(); // Apply the highlight. var range = this.toDomRange(), bookmark = range.createBookmark(); highlightStyle.applyToRange( range ); range.moveToBookmark( bookmark ); this._.highlightRange = range; // Scroll the editor to the highlighted area. var element = range.startContainer; if ( element.type != CKEDITOR.NODE_ELEMENT ) element = element.getParent(); element.scrollIntoView(); // Update the character cursors. this.updateFromDomRange( range ); }, /** * Remove highlighted find result. */ removeHighlight : function() { if ( !this._.highlightRange ) return; var bookmark = this._.highlightRange.createBookmark(); highlightStyle.removeFromRange( this._.highlightRange ); this._.highlightRange.moveToBookmark( bookmark ); this.updateFromDomRange( this._.highlightRange ); this._.highlightRange = null; }, isReadOnly : function() { if ( !this._.highlightRange ) return 0; return this._.highlightRange.startContainer.isReadOnly(); }, moveBack : function() { var retval = this._.walker.back(), cursors = this._.cursors; if ( retval.hitMatchBoundary ) this._.cursors = cursors = []; cursors.unshift( retval ); if ( cursors.length > this._.rangeLength ) cursors.pop(); return retval; }, moveNext : function() { var retval = this._.walker.next(), cursors = this._.cursors; // Clear the cursors queue if we've crossed a match boundary. if ( retval.hitMatchBoundary ) this._.cursors = cursors = []; cursors.push( retval ); if ( cursors.length > this._.rangeLength ) cursors.shift(); return retval; }, getEndCharacter : function() { var cursors = this._.cursors; if ( cursors.length < 1 ) return null; return cursors[ cursors.length - 1 ].character; }, getNextCharacterRange : function( maxLength ) { var lastCursor, nextRangeWalker, cursors = this._.cursors; if ( ( lastCursor = cursors[ cursors.length - 1 ] ) && lastCursor.textNode ) nextRangeWalker = new characterWalker( getRangeAfterCursor( lastCursor ) ); // In case it's an empty range (no cursors), figure out next range from walker (#4951). else nextRangeWalker = this._.walker; return new characterRange( nextRangeWalker, maxLength ); }, getCursors : function() { return this._.cursors; } }; // The remaining document range after the character cursor. function getRangeAfterCursor( cursor , inclusive ) { var range = new CKEDITOR.dom.range(); range.setStart( cursor.textNode, ( inclusive ? cursor.offset : cursor.offset + 1 ) ); range.setEndAt( editor.document.getBody(), CKEDITOR.POSITION_BEFORE_END ); return range; } // The document range before the character cursor. function getRangeBeforeCursor( cursor ) { var range = new CKEDITOR.dom.range(); range.setStartAt( editor.document.getBody(), CKEDITOR.POSITION_AFTER_START ); range.setEnd( cursor.textNode, cursor.offset ); return range; } var KMP_NOMATCH = 0, KMP_ADVANCED = 1, KMP_MATCHED = 2; /** * Examination the occurrence of a word which implement KMP algorithm. */ var kmpMatcher = function( pattern, ignoreCase ) { var overlap = [ -1 ]; if ( ignoreCase ) pattern = pattern.toLowerCase(); for ( var i = 0 ; i < pattern.length ; i++ ) { overlap.push( overlap[i] + 1 ); while ( overlap[ i + 1 ] > 0 && pattern.charAt( i ) != pattern .charAt( overlap[ i + 1 ] - 1 ) ) overlap[ i + 1 ] = overlap[ overlap[ i + 1 ] - 1 ] + 1; } this._ = { overlap : overlap, state : 0, ignoreCase : !!ignoreCase, pattern : pattern }; }; kmpMatcher.prototype = { feedCharacter : function( c ) { if ( this._.ignoreCase ) c = c.toLowerCase(); while ( true ) { if ( c == this._.pattern.charAt( this._.state ) ) { this._.state++; if ( this._.state == this._.pattern.length ) { this._.state = 0; return KMP_MATCHED; } return KMP_ADVANCED; } else if ( !this._.state ) return KMP_NOMATCH; else this._.state = this._.overlap[ this._.state ]; } return null; }, reset : function() { this._.state = 0; } }; var wordSeparatorRegex = /[.,"'?!;: \u0085\u00a0\u1680\u280e\u2028\u2029\u202f\u205f\u3000]/; var isWordSeparator = function( c ) { if ( !c ) return true; var code = c.charCodeAt( 0 ); return ( code >= 9 && code <= 0xd ) || ( code >= 0x2000 && code <= 0x200a ) || wordSeparatorRegex.test( c ); }; var finder = { searchRange : null, matchRange : null, find : function( pattern, matchCase, matchWord, matchCyclic, highlightMatched, cyclicRerun ) { if ( !this.matchRange ) this.matchRange = new characterRange( new characterWalker( this.searchRange ), pattern.length ); else { this.matchRange.removeHighlight(); this.matchRange = this.matchRange.getNextCharacterRange( pattern.length ); } var matcher = new kmpMatcher( pattern, !matchCase ), matchState = KMP_NOMATCH, character = '%'; while ( character !== null ) { this.matchRange.moveNext(); while ( ( character = this.matchRange.getEndCharacter() ) ) { matchState = matcher.feedCharacter( character ); if ( matchState == KMP_MATCHED ) break; if ( this.matchRange.moveNext().hitMatchBoundary ) matcher.reset(); } if ( matchState == KMP_MATCHED ) { if ( matchWord ) { var cursors = this.matchRange.getCursors(), tail = cursors[ cursors.length - 1 ], head = cursors[ 0 ]; var headWalker = new characterWalker( getRangeBeforeCursor( head ), true ), tailWalker = new characterWalker( getRangeAfterCursor( tail ), true ); if ( ! ( isWordSeparator( headWalker.back().character ) && isWordSeparator( tailWalker.next().character ) ) ) continue; } this.matchRange.setMatched(); if ( highlightMatched !== false ) this.matchRange.highlight(); return true; } } this.matchRange.clearMatched(); this.matchRange.removeHighlight(); // Clear current session and restart with the default search // range. // Re-run the finding once for cyclic.(#3517) if ( matchCyclic && !cyclicRerun ) { this.searchRange = getSearchRange( 1 ); this.matchRange = null; return arguments.callee.apply( this, Array.prototype.slice.call( arguments ).concat( [ true ] ) ); } return false; }, /** * Record how much replacement occurred toward one replacing. */ replaceCounter : 0, replace : function( dialog, pattern, newString, matchCase, matchWord, matchCyclic , isReplaceAll ) { isReplace = 1; // Successiveness of current replace/find. var result = 0; // 1. Perform the replace when there's already a match here. // 2. Otherwise perform the find but don't replace it immediately. if ( this.matchRange && this.matchRange.isMatched() && !this.matchRange._.isReplaced && !this.matchRange.isReadOnly() ) { // Turn off highlight for a while when saving snapshots. this.matchRange.removeHighlight(); var domRange = this.matchRange.toDomRange(); var text = editor.document.createText( newString ); if ( !isReplaceAll ) { // Save undo snaps before and after the replacement. var selection = editor.getSelection(); selection.selectRanges( [ domRange ] ); editor.fire( 'saveSnapshot' ); } domRange.deleteContents(); domRange.insertNode( text ); if ( !isReplaceAll ) { selection.selectRanges( [ domRange ] ); editor.fire( 'saveSnapshot' ); } this.matchRange.updateFromDomRange( domRange ); if ( !isReplaceAll ) this.matchRange.highlight(); this.matchRange._.isReplaced = true; this.replaceCounter++; result = 1; } else result = this.find( pattern, matchCase, matchWord, matchCyclic, !isReplaceAll ); isReplace = 0; return result; } }; /** * The range in which find/replace happened, receive from user * selection prior. */ function getSearchRange( isDefault ) { var searchRange, sel = editor.getSelection(), body = editor.document.getBody(); if ( sel && !isDefault ) { searchRange = sel.getRanges()[ 0 ].clone(); searchRange.collapse( true ); } else { searchRange = new CKEDITOR.dom.range(); searchRange.setStartAt( body, CKEDITOR.POSITION_AFTER_START ); } searchRange.setEndAt( body, CKEDITOR.POSITION_BEFORE_END ); return searchRange; } var lang = editor.lang.findAndReplace; return { title : lang.title, resizable : CKEDITOR.DIALOG_RESIZE_NONE, minWidth : 350, minHeight : 170, buttons : [ CKEDITOR.dialog.cancelButton ], // Cancel button only. contents : [ { id : 'find', label : lang.find, title : lang.find, accessKey : '', elements : [ { type : 'hbox', widths : [ '230px', '90px' ], children : [ { type : 'text', id : 'txtFindFind', label : lang.findWhat, isChanged : false, labelLayout : 'horizontal', accessKey : 'F' }, { type : 'button', id : 'btnFind', align : 'left', style : 'width:100%', label : lang.find, onClick : function() { var dialog = this.getDialog(); if ( !finder.find( dialog.getValueOf( 'find', 'txtFindFind' ), dialog.getValueOf( 'find', 'txtFindCaseChk' ), dialog.getValueOf( 'find', 'txtFindWordChk' ), dialog.getValueOf( 'find', 'txtFindCyclic' ) ) ) alert( lang .notFoundMsg ); } } ] }, { type : 'fieldset', label : CKEDITOR.tools.htmlEncode( lang.findOptions ), style : 'margin-top:29px', children : [ { type : 'vbox', padding : 0, children : [ { type : 'checkbox', id : 'txtFindCaseChk', isChanged : false, label : lang.matchCase }, { type : 'checkbox', id : 'txtFindWordChk', isChanged : false, label : lang.matchWord }, { type : 'checkbox', id : 'txtFindCyclic', isChanged : false, 'default' : true, label : lang.matchCyclic } ] } ] } ] }, { id : 'replace', label : lang.replace, accessKey : 'M', elements : [ { type : 'hbox', widths : [ '230px', '90px' ], children : [ { type : 'text', id : 'txtFindReplace', label : lang.findWhat, isChanged : false, labelLayout : 'horizontal', accessKey : 'F' }, { type : 'button', id : 'btnFindReplace', align : 'left', style : 'width:100%', label : lang.replace, onClick : function() { var dialog = this.getDialog(); if ( !finder.replace( dialog, dialog.getValueOf( 'replace', 'txtFindReplace' ), dialog.getValueOf( 'replace', 'txtReplace' ), dialog.getValueOf( 'replace', 'txtReplaceCaseChk' ), dialog.getValueOf( 'replace', 'txtReplaceWordChk' ), dialog.getValueOf( 'replace', 'txtReplaceCyclic' ) ) ) alert( lang .notFoundMsg ); } } ] }, { type : 'hbox', widths : [ '230px', '90px' ], children : [ { type : 'text', id : 'txtReplace', label : lang.replaceWith, isChanged : false, labelLayout : 'horizontal', accessKey : 'R' }, { type : 'button', id : 'btnReplaceAll', align : 'left', style : 'width:100%', label : lang.replaceAll, isChanged : false, onClick : function() { var dialog = this.getDialog(); var replaceNums; finder.replaceCounter = 0; // Scope to full document. finder.searchRange = getSearchRange( 1 ); if ( finder.matchRange ) { finder.matchRange.removeHighlight(); finder.matchRange = null; } editor.fire( 'saveSnapshot' ); while ( finder.replace( dialog, dialog.getValueOf( 'replace', 'txtFindReplace' ), dialog.getValueOf( 'replace', 'txtReplace' ), dialog.getValueOf( 'replace', 'txtReplaceCaseChk' ), dialog.getValueOf( 'replace', 'txtReplaceWordChk' ), false, true ) ) { /*jsl:pass*/ } if ( finder.replaceCounter ) { alert( lang.replaceSuccessMsg.replace( /%1/, finder.replaceCounter ) ); editor.fire( 'saveSnapshot' ); } else alert( lang.notFoundMsg ); } } ] }, { type : 'fieldset', label : CKEDITOR.tools.htmlEncode( lang.findOptions ), children : [ { type : 'vbox', padding : 0, children : [ { type : 'checkbox', id : 'txtReplaceCaseChk', isChanged : false, label : lang.matchCase }, { type : 'checkbox', id : 'txtReplaceWordChk', isChanged : false, label : lang.matchWord }, { type : 'checkbox', id : 'txtReplaceCyclic', isChanged : false, 'default' : true, label : lang.matchCyclic } ] } ] } ] } ], onLoad : function() { var dialog = this; // Keep track of the current pattern field in use. var patternField, wholeWordChkField; // Ignore initial page select on dialog show var isUserSelect = 0; this.on( 'hide', function() { isUserSelect = 0; }); this.on( 'show', function() { isUserSelect = 1; }); this.selectPage = CKEDITOR.tools.override( this.selectPage, function( originalFunc ) { return function( pageId ) { originalFunc.call( dialog, pageId ); var currPage = dialog._.tabs[ pageId ]; var patternFieldInput, patternFieldId, wholeWordChkFieldId; patternFieldId = pageId === 'find' ? 'txtFindFind' : 'txtFindReplace'; wholeWordChkFieldId = pageId === 'find' ? 'txtFindWordChk' : 'txtReplaceWordChk'; patternField = dialog.getContentElement( pageId, patternFieldId ); wholeWordChkField = dialog.getContentElement( pageId, wholeWordChkFieldId ); // Prepare for check pattern text filed 'keyup' event if ( !currPage.initialized ) { patternFieldInput = CKEDITOR.document .getById( patternField._.inputId ); currPage.initialized = true; } // Synchronize fields on tab switch. if ( isUserSelect ) syncFieldsBetweenTabs.call( this, pageId ); }; } ); }, onShow : function() { // Establish initial searching start position. finder.searchRange = getSearchRange(); // Fill in the find field with selected text. var selectedText = this.getParentEditor().getSelection().getSelectedText(), patternFieldId = ( startupPage == 'find' ? 'txtFindFind' : 'txtFindReplace' ); var field = this.getContentElement( startupPage, patternFieldId ); field.setValue( selectedText ); field.select(); this.selectPage( startupPage ); this[ ( startupPage == 'find' && this._.editor.readOnly? 'hide' : 'show' ) + 'Page' ]( 'replace'); }, onHide : function() { var range; if ( finder.matchRange && finder.matchRange.isMatched() ) { finder.matchRange.removeHighlight(); editor.focus(); range = finder.matchRange.toDomRange(); if ( range ) editor.getSelection().selectRanges( [ range ] ); } // Clear current session before dialog close delete finder.matchRange; }, onFocus : function() { if ( startupPage == 'replace' ) return this.getContentElement( 'replace', 'txtFindReplace' ); else return this.getContentElement( 'find', 'txtFindFind' ); } }; }; CKEDITOR.dialog.add( 'find', function( editor ) { return findDialog( editor, 'find' ); }); CKEDITOR.dialog.add( 'replace', function( editor ) { return findDialog( editor, 'replace' ); }); })();
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.add( 'htmlwriter' ); /** * Class used to write HTML data. * @constructor * @example * var writer = new CKEDITOR.htmlWriter(); * writer.openTag( 'p' ); * writer.attribute( 'class', 'MyClass' ); * writer.openTagClose( 'p' ); * writer.text( 'Hello' ); * writer.closeTag( 'p' ); * alert( writer.getHtml() ); "&lt;p class="MyClass"&gt;Hello&lt;/p&gt;" */ CKEDITOR.htmlWriter = CKEDITOR.tools.createClass( { base : CKEDITOR.htmlParser.basicWriter, $ : function() { // Call the base contructor. this.base(); /** * The characters to be used for each identation step. * @type String * @default "\t" (tab) * @example * // Use two spaces for indentation. * editorInstance.dataProcessor.writer.indentationChars = ' '; */ this.indentationChars = '\t'; /** * The characters to be used to close "self-closing" elements, like "br" or * "img". * @type String * @default " /&gt;" * @example * // Use HTML4 notation for self-closing elements. * editorInstance.dataProcessor.writer.selfClosingEnd = '>'; */ this.selfClosingEnd = ' />'; /** * The characters to be used for line breaks. * @type String * @default "\n" (LF) * @example * // Use CRLF for line breaks. * editorInstance.dataProcessor.writer.lineBreakChars = '\r\n'; */ this.lineBreakChars = '\n'; this.forceSimpleAmpersand = 0; this.sortAttributes = 1; this._.indent = 0; this._.indentation = ''; // Indicate preformatted block context status. (#5789) this._.inPre = 0; this._.rules = {}; var dtd = CKEDITOR.dtd; for ( var e in CKEDITOR.tools.extend( {}, dtd.$nonBodyContent, dtd.$block, dtd.$listItem, dtd.$tableContent ) ) { this.setRules( e, { indent : 1, breakBeforeOpen : 1, breakAfterOpen : 1, breakBeforeClose : !dtd[ e ][ '#' ], breakAfterClose : 1 }); } this.setRules( 'br', { breakAfterOpen : 1 }); this.setRules( 'title', { indent : 0, breakAfterOpen : 0 }); this.setRules( 'style', { indent : 0, breakBeforeClose : 1 }); // Disable indentation on <pre>. this.setRules( 'pre', { indent : 0 }); }, proto : { /** * Writes the tag opening part for a opener tag. * @param {String} tagName The element name for this tag. * @param {Object} attributes The attributes defined for this tag. The * attributes could be used to inspect the tag. * @example * // Writes "&lt;p". * writer.openTag( 'p', { class : 'MyClass', id : 'MyId' } ); */ openTag : function( tagName, attributes ) { var rules = this._.rules[ tagName ]; if ( this._.indent ) this.indentation(); // Do not break if indenting. else if ( rules && rules.breakBeforeOpen ) { this.lineBreak(); this.indentation(); } this._.output.push( '<', tagName ); }, /** * Writes the tag closing part for a opener tag. * @param {String} tagName The element name for this tag. * @param {Boolean} isSelfClose Indicates that this is a self-closing tag, * like "br" or "img". * @example * // Writes "&gt;". * writer.openTagClose( 'p', false ); * @example * // Writes " /&gt;". * writer.openTagClose( 'br', true ); */ openTagClose : function( tagName, isSelfClose ) { var rules = this._.rules[ tagName ]; if ( isSelfClose ) this._.output.push( this.selfClosingEnd ); else { this._.output.push( '>' ); if ( rules && rules.indent ) this._.indentation += this.indentationChars; } if ( rules && rules.breakAfterOpen ) this.lineBreak(); tagName == 'pre' && ( this._.inPre = 1 ); }, /** * Writes an attribute. This function should be called after opening the * tag with {@link #openTagClose}. * @param {String} attName The attribute name. * @param {String} attValue The attribute value. * @example * // Writes ' class="MyClass"'. * writer.attribute( 'class', 'MyClass' ); */ attribute : function( attName, attValue ) { if ( typeof attValue == 'string' ) { this.forceSimpleAmpersand && ( attValue = attValue.replace( /&amp;/g, '&' ) ); // Browsers don't always escape special character in attribute values. (#4683, #4719). attValue = CKEDITOR.tools.htmlEncodeAttr( attValue ); } this._.output.push( ' ', attName, '="', attValue, '"' ); }, /** * Writes a closer tag. * @param {String} tagName The element name for this tag. * @example * // Writes "&lt;/p&gt;". * writer.closeTag( 'p' ); */ closeTag : function( tagName ) { var rules = this._.rules[ tagName ]; if ( rules && rules.indent ) this._.indentation = this._.indentation.substr( this.indentationChars.length ); if ( this._.indent ) this.indentation(); // Do not break if indenting. else if ( rules && rules.breakBeforeClose ) { this.lineBreak(); this.indentation(); } this._.output.push( '</', tagName, '>' ); tagName == 'pre' && ( this._.inPre = 0 ); if ( rules && rules.breakAfterClose ) this.lineBreak(); }, /** * Writes text. * @param {String} text The text value * @example * // Writes "Hello Word". * writer.text( 'Hello Word' ); */ text : function( text ) { if ( this._.indent ) { this.indentation(); !this._.inPre && ( text = CKEDITOR.tools.ltrim( text ) ); } this._.output.push( text ); }, /** * Writes a comment. * @param {String} comment The comment text. * @example * // Writes "&lt;!-- My comment --&gt;". * writer.comment( ' My comment ' ); */ comment : function( comment ) { if ( this._.indent ) this.indentation(); this._.output.push( '<!--', comment, '-->' ); }, /** * Writes a line break. It uses the {@link #lineBreakChars} property for it. * @example * // Writes "\n" (e.g.). * writer.lineBreak(); */ lineBreak : function() { if ( !this._.inPre && this._.output.length > 0 ) this._.output.push( this.lineBreakChars ); this._.indent = 1; }, /** * Writes the current indentation chars. It uses the * {@link #indentationChars} property, repeating it for the current * indentation steps. * @example * // Writes "\t" (e.g.). * writer.indentation(); */ indentation : function() { if( !this._.inPre ) this._.output.push( this._.indentation ); this._.indent = 0; }, /** * Sets formatting rules for a give element. The possible rules are: * <ul> * <li><b>indent</b>: indent the element contents.</li> * <li><b>breakBeforeOpen</b>: break line before the opener tag for this element.</li> * <li><b>breakAfterOpen</b>: break line after the opener tag for this element.</li> * <li><b>breakBeforeClose</b>: break line before the closer tag for this element.</li> * <li><b>breakAfterClose</b>: break line after the closer tag for this element.</li> * </ul> * * All rules default to "false". Each call to the function overrides * already present rules, leaving the undefined untouched. * * By default, all elements available in the {@link CKEDITOR.dtd.$block), * {@link CKEDITOR.dtd.$listItem} and {@link CKEDITOR.dtd.$tableContent} * lists have all the above rules set to "true". Additionaly, the "br" * element has the "breakAfterOpen" set to "true". * @param {String} tagName The element name to which set the rules. * @param {Object} rules An object containing the element rules. * @example * // Break line before and after "img" tags. * writer.setRules( 'img', * { * breakBeforeOpen : true * breakAfterOpen : true * }); * @example * // Reset the rules for the "h1" tag. * writer.setRules( 'h1', {} ); */ setRules : function( tagName, rules ) { var currentRules = this._.rules[ tagName ]; if ( currentRules ) CKEDITOR.tools.extend( currentRules, rules, true ); else this._.rules[ tagName ] = rules; } } });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Undo/Redo system for saving shapshot for document modification * and other recordable changes. */ (function() { CKEDITOR.plugins.add( 'undo', { requires : [ 'selection', 'wysiwygarea' ], init : function( editor ) { var undoManager = new UndoManager( editor ); var undoCommand = editor.addCommand( 'undo', { exec : function() { if ( undoManager.undo() ) { editor.selectionChange(); this.fire( 'afterUndo' ); } }, state : CKEDITOR.TRISTATE_DISABLED, canUndo : false }); var redoCommand = editor.addCommand( 'redo', { exec : function() { if ( undoManager.redo() ) { editor.selectionChange(); this.fire( 'afterRedo' ); } }, state : CKEDITOR.TRISTATE_DISABLED, canUndo : false }); undoManager.onChange = function() { undoCommand.setState( undoManager.undoable() ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED ); redoCommand.setState( undoManager.redoable() ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED ); }; function recordCommand( event ) { // If the command hasn't been marked to not support undo. if ( undoManager.enabled && event.data.command.canUndo !== false ) undoManager.save(); } // We'll save snapshots before and after executing a command. editor.on( 'beforeCommandExec', recordCommand ); editor.on( 'afterCommandExec', recordCommand ); // Save snapshots before doing custom changes. editor.on( 'saveSnapshot', function( evt ) { undoManager.save( evt.data && evt.data.contentOnly ); }); // Registering keydown on every document recreation.(#3844) editor.on( 'contentDom', function() { editor.document.on( 'keydown', function( event ) { // Do not capture CTRL hotkeys. if ( !event.data.$.ctrlKey && !event.data.$.metaKey ) undoManager.type( event ); }); }); // Always save an undo snapshot - the previous mode might have // changed editor contents. editor.on( 'beforeModeUnload', function() { editor.mode == 'wysiwyg' && undoManager.save( true ); }); // Make the undo manager available only in wysiwyg mode. editor.on( 'mode', function() { undoManager.enabled = editor.readOnly ? false : editor.mode == 'wysiwyg'; undoManager.onChange(); }); editor.ui.addButton( 'Undo', { label : editor.lang.undo, command : 'undo' }); editor.ui.addButton( 'Redo', { label : editor.lang.redo, command : 'redo' }); editor.resetUndo = function() { // Reset the undo stack. undoManager.reset(); // Create the first image. editor.fire( 'saveSnapshot' ); }; /** * Amend the top of undo stack (last undo image) with the current DOM changes. * @name CKEDITOR.editor#updateUndo * @example * function() * { * editor.fire( 'saveSnapshot' ); * editor.document.body.append(...); * // Make new changes following the last undo snapshot part of it. * editor.fire( 'updateSnapshot' ); * ... * } */ editor.on( 'updateSnapshot', function() { if ( undoManager.currentImage ) undoManager.update(); }); } }); CKEDITOR.plugins.undo = {}; /** * Undo snapshot which represents the current document status. * @name CKEDITOR.plugins.undo.Image * @param editor The editor instance on which the image is created. */ var Image = CKEDITOR.plugins.undo.Image = function( editor ) { this.editor = editor; editor.fire( 'beforeUndoImage' ); var contents = editor.getSnapshot(), selection = contents && editor.getSelection(); // In IE, we need to remove the expando attributes. CKEDITOR.env.ie && contents && ( contents = contents.replace( /\s+data-cke-expando=".*?"/g, '' ) ); this.contents = contents; this.bookmarks = selection && selection.createBookmarks2( true ); editor.fire( 'afterUndoImage' ); }; // Attributes that browser may changing them when setting via innerHTML. var protectedAttrs = /\b(?:href|src|name)="[^"]*?"/gi; Image.prototype = { equals : function( otherImage, contentOnly ) { var thisContents = this.contents, otherContents = otherImage.contents; // For IE6/7 : Comparing only the protected attribute values but not the original ones.(#4522) if ( CKEDITOR.env.ie && ( CKEDITOR.env.ie7Compat || CKEDITOR.env.ie6Compat ) ) { thisContents = thisContents.replace( protectedAttrs, '' ); otherContents = otherContents.replace( protectedAttrs, '' ); } if ( thisContents != otherContents ) return false; if ( contentOnly ) return true; var bookmarksA = this.bookmarks, bookmarksB = otherImage.bookmarks; if ( bookmarksA || bookmarksB ) { if ( !bookmarksA || !bookmarksB || bookmarksA.length != bookmarksB.length ) return false; for ( var i = 0 ; i < bookmarksA.length ; i++ ) { var bookmarkA = bookmarksA[ i ], bookmarkB = bookmarksB[ i ]; if ( bookmarkA.startOffset != bookmarkB.startOffset || bookmarkA.endOffset != bookmarkB.endOffset || !CKEDITOR.tools.arrayCompare( bookmarkA.start, bookmarkB.start ) || !CKEDITOR.tools.arrayCompare( bookmarkA.end, bookmarkB.end ) ) { return false; } } } return true; } }; /** * @constructor Main logic for Redo/Undo feature. */ function UndoManager( editor ) { this.editor = editor; // Reset the undo stack. this.reset(); } var editingKeyCodes = { /*Backspace*/ 8:1, /*Delete*/ 46:1 }, modifierKeyCodes = { /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1 }, navigationKeyCodes = { 37:1, 38:1, 39:1, 40:1 }; // Arrows: L, T, R, B UndoManager.prototype = { /** * Process undo system regard keystrikes. * @param {CKEDITOR.dom.event} event */ type : function( event ) { var keystroke = event && event.data.getKey(), isModifierKey = keystroke in modifierKeyCodes, isEditingKey = keystroke in editingKeyCodes, wasEditingKey = this.lastKeystroke in editingKeyCodes, sameAsLastEditingKey = isEditingKey && keystroke == this.lastKeystroke, // Keystrokes which navigation through contents. isReset = keystroke in navigationKeyCodes, wasReset = this.lastKeystroke in navigationKeyCodes, // Keystrokes which just introduce new contents. isContent = ( !isEditingKey && !isReset ), // Create undo snap for every different modifier key. modifierSnapshot = ( isEditingKey && !sameAsLastEditingKey ), // Create undo snap on the following cases: // 1. Just start to type . // 2. Typing some content after a modifier. // 3. Typing some content after make a visible selection. startedTyping = !( isModifierKey || this.typing ) || ( isContent && ( wasEditingKey || wasReset ) ); if ( startedTyping || modifierSnapshot ) { var beforeTypeImage = new Image( this.editor ); // Use setTimeout, so we give the necessary time to the // browser to insert the character into the DOM. CKEDITOR.tools.setTimeout( function() { var currentSnapshot = this.editor.getSnapshot(); // In IE, we need to remove the expando attributes. if ( CKEDITOR.env.ie ) currentSnapshot = currentSnapshot.replace( /\s+data-cke-expando=".*?"/g, '' ); if ( beforeTypeImage.contents != currentSnapshot ) { // It's safe to now indicate typing state. this.typing = true; // This's a special save, with specified snapshot // and without auto 'fireChange'. if ( !this.save( false, beforeTypeImage, false ) ) // Drop future snapshots. this.snapshots.splice( this.index + 1, this.snapshots.length - this.index - 1 ); this.hasUndo = true; this.hasRedo = false; this.typesCount = 1; this.modifiersCount = 1; this.onChange(); } }, 0, this ); } this.lastKeystroke = keystroke; // Create undo snap after typed too much (over 25 times). if ( isEditingKey ) { this.typesCount = 0; this.modifiersCount++; if ( this.modifiersCount > 25 ) { this.save( false, null, false ); this.modifiersCount = 1; } } else if ( !isReset ) { this.modifiersCount = 0; this.typesCount++; if ( this.typesCount > 25 ) { this.save( false, null, false ); this.typesCount = 1; } } }, reset : function() // Reset the undo stack. { /** * Remember last pressed key. */ this.lastKeystroke = 0; /** * Stack for all the undo and redo snapshots, they're always created/removed * in consistency. */ this.snapshots = []; /** * Current snapshot history index. */ this.index = -1; this.limit = this.editor.config.undoStackSize || 20; this.currentImage = null; this.hasUndo = false; this.hasRedo = false; this.resetType(); }, /** * Reset all states about typing. * @see UndoManager.type */ resetType : function() { this.typing = false; delete this.lastKeystroke; this.typesCount = 0; this.modifiersCount = 0; }, fireChange : function() { this.hasUndo = !!this.getNextImage( true ); this.hasRedo = !!this.getNextImage( false ); // Reset typing this.resetType(); this.onChange(); }, /** * Save a snapshot of document image for later retrieve. */ save : function( onContentOnly, image, autoFireChange ) { var snapshots = this.snapshots; // Get a content image. if ( !image ) image = new Image( this.editor ); // Do nothing if it was not possible to retrieve an image. if ( image.contents === false ) return false; // Check if this is a duplicate. In such case, do nothing. if ( this.currentImage && image.equals( this.currentImage, onContentOnly ) ) return false; // Drop future snapshots. snapshots.splice( this.index + 1, snapshots.length - this.index - 1 ); // If we have reached the limit, remove the oldest one. if ( snapshots.length == this.limit ) snapshots.shift(); // Add the new image, updating the current index. this.index = snapshots.push( image ) - 1; this.currentImage = image; if ( autoFireChange !== false ) this.fireChange(); return true; }, restoreImage : function( image ) { this.editor.loadSnapshot( image.contents ); if ( image.bookmarks ) this.editor.getSelection().selectBookmarks( image.bookmarks ); else if ( CKEDITOR.env.ie ) { // IE BUG: If I don't set the selection to *somewhere* after setting // document contents, then IE would create an empty paragraph at the bottom // the next time the document is modified. var $range = this.editor.document.getBody().$.createTextRange(); $range.collapse( true ); $range.select(); } this.index = image.index; // Update current image with the actual editor // content, since actualy content may differ from // the original snapshot due to dom change. (#4622) this.update(); this.fireChange(); }, // Get the closest available image. getNextImage : function( isUndo ) { var snapshots = this.snapshots, currentImage = this.currentImage, image, i; if ( currentImage ) { if ( isUndo ) { for ( i = this.index - 1 ; i >= 0 ; i-- ) { image = snapshots[ i ]; if ( !currentImage.equals( image, true ) ) { image.index = i; return image; } } } else { for ( i = this.index + 1 ; i < snapshots.length ; i++ ) { image = snapshots[ i ]; if ( !currentImage.equals( image, true ) ) { image.index = i; return image; } } } } return null; }, /** * Check the current redo state. * @return {Boolean} Whether the document has previous state to * retrieve. */ redoable : function() { return this.enabled && this.hasRedo; }, /** * Check the current undo state. * @return {Boolean} Whether the document has future state to restore. */ undoable : function() { return this.enabled && this.hasUndo; }, /** * Perform undo on current index. */ undo : function() { if ( this.undoable() ) { this.save( true ); var image = this.getNextImage( true ); if ( image ) return this.restoreImage( image ), true; } return false; }, /** * Perform redo on current index. */ redo : function() { if ( this.redoable() ) { // Try to save. If no changes have been made, the redo stack // will not change, so it will still be redoable. this.save( true ); // If instead we had changes, we can't redo anymore. if ( this.redoable() ) { var image = this.getNextImage( false ); if ( image ) return this.restoreImage( image ), true; } } return false; }, /** * Update the last snapshot of the undo stack with the current editor content. */ update : function() { this.snapshots.splice( this.index, 1, ( this.currentImage = new Image( this.editor ) ) ); } }; })(); /** * The number of undo steps to be saved. The higher this setting value the more * memory is used for it. * @name CKEDITOR.config.undoStackSize * @type Number * @default 20 * @example * config.undoStackSize = 50; */ /** * Fired when the editor is about to save an undo snapshot. This event can be * fired by plugins and customizations to make the editor saving undo snapshots. * @name CKEDITOR.editor#saveSnapshot * @event */ /** * Fired before an undo image is to be taken. An undo image represents the * editor state at some point. It's saved into an undo store, so the editor is * able to recover the editor state on undo and redo operations. * @name CKEDITOR.editor#beforeUndoImage * @since 3.5.3 * @see CKEDITOR.editor#afterUndoImage * @event */ /** * Fired after an undo image is taken. An undo image represents the * editor state at some point. It's saved into an undo store, so the editor is * able to recover the editor state on undo and redo operations. * @name CKEDITOR.editor#afterUndoImage * @since 3.5.3 * @see CKEDITOR.editor#beforeUndoImage * @event */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @file Forms Plugin */ CKEDITOR.plugins.add( 'forms', { init : function( editor ) { var lang = editor.lang; editor.addCss( 'form' + '{' + 'border: 1px dotted #FF0000;' + 'padding: 2px;' + '}\n' ); editor.addCss( 'img.cke_hidden' + '{' + 'background-image: url(' + CKEDITOR.getUrl( this.path + 'images/hiddenfield.gif' ) + ');' + 'background-position: center center;' + 'background-repeat: no-repeat;' + 'border: 1px solid #a9a9a9;' + 'width: 16px !important;' + 'height: 16px !important;' + '}' ); // All buttons use the same code to register. So, to avoid // duplications, let's use this tool function. var addButtonCommand = function( buttonName, commandName, dialogFile ) { editor.addCommand( commandName, new CKEDITOR.dialogCommand( commandName ) ); editor.ui.addButton( buttonName, { label : lang.common[ buttonName.charAt(0).toLowerCase() + buttonName.slice(1) ], command : commandName }); CKEDITOR.dialog.add( commandName, dialogFile ); }; var dialogPath = this.path + 'dialogs/'; addButtonCommand( 'Form', 'form', dialogPath + 'form.js' ); addButtonCommand( 'Checkbox', 'checkbox', dialogPath + 'checkbox.js' ); addButtonCommand( 'Radio', 'radio', dialogPath + 'radio.js' ); addButtonCommand( 'TextField', 'textfield', dialogPath + 'textfield.js' ); addButtonCommand( 'Textarea', 'textarea', dialogPath + 'textarea.js' ); addButtonCommand( 'Select', 'select', dialogPath + 'select.js' ); addButtonCommand( 'Button', 'button', dialogPath + 'button.js' ); addButtonCommand( 'ImageButton', 'imagebutton', CKEDITOR.plugins.getPath('image') + 'dialogs/image.js' ); addButtonCommand( 'HiddenField', 'hiddenfield', dialogPath + 'hiddenfield.js' ); // If the "menu" plugin is loaded, register the menu items. if ( editor.addMenuItems ) { editor.addMenuItems( { form : { label : lang.form.menu, command : 'form', group : 'form' }, checkbox : { label : lang.checkboxAndRadio.checkboxTitle, command : 'checkbox', group : 'checkbox' }, radio : { label : lang.checkboxAndRadio.radioTitle, command : 'radio', group : 'radio' }, textfield : { label : lang.textfield.title, command : 'textfield', group : 'textfield' }, hiddenfield : { label : lang.hidden.title, command : 'hiddenfield', group : 'hiddenfield' }, imagebutton : { label : lang.image.titleButton, command : 'imagebutton', group : 'imagebutton' }, button : { label : lang.button.title, command : 'button', group : 'button' }, select : { label : lang.select.title, command : 'select', group : 'select' }, textarea : { label : lang.textarea.title, command : 'textarea', group : 'textarea' } }); } // If the "contextmenu" plugin is loaded, register the listeners. if ( editor.contextMenu ) { editor.contextMenu.addListener( function( element ) { if ( element && element.hasAscendant( 'form', true ) && !element.isReadOnly() ) return { form : CKEDITOR.TRISTATE_OFF }; }); editor.contextMenu.addListener( function( element ) { if ( element && !element.isReadOnly() ) { var name = element.getName(); if ( name == 'select' ) return { select : CKEDITOR.TRISTATE_OFF }; if ( name == 'textarea' ) return { textarea : CKEDITOR.TRISTATE_OFF }; if ( name == 'input' ) { switch( element.getAttribute( 'type' ) ) { case 'button' : case 'submit' : case 'reset' : return { button : CKEDITOR.TRISTATE_OFF }; case 'checkbox' : return { checkbox : CKEDITOR.TRISTATE_OFF }; case 'radio' : return { radio : CKEDITOR.TRISTATE_OFF }; case 'image' : return { imagebutton : CKEDITOR.TRISTATE_OFF }; default : return { textfield : CKEDITOR.TRISTATE_OFF }; } } if ( name == 'img' && element.data( 'cke-real-element-type' ) == 'hiddenfield' ) return { hiddenfield : CKEDITOR.TRISTATE_OFF }; } }); } editor.on( 'doubleclick', function( evt ) { var element = evt.data.element; if ( element.is( 'form' ) ) evt.data.dialog = 'form'; else if ( element.is( 'select' ) ) evt.data.dialog = 'select'; else if ( element.is( 'textarea' ) ) evt.data.dialog = 'textarea'; else if ( element.is( 'img' ) && element.data( 'cke-real-element-type' ) == 'hiddenfield' ) evt.data.dialog = 'hiddenfield'; else if ( element.is( 'input' ) ) { switch ( element.getAttribute( 'type' ) ) { case 'button' : case 'submit' : case 'reset' : evt.data.dialog = 'button'; break; case 'checkbox' : evt.data.dialog = 'checkbox'; break; case 'radio' : evt.data.dialog = 'radio'; break; case 'image' : evt.data.dialog = 'imagebutton'; break; default : evt.data.dialog = 'textfield'; break; } } }); }, afterInit : function( editor ) { var dataProcessor = editor.dataProcessor, htmlFilter = dataProcessor && dataProcessor.htmlFilter, dataFilter = dataProcessor && dataProcessor.dataFilter; // Cleanup certain IE form elements default values. if ( CKEDITOR.env.ie ) { htmlFilter && htmlFilter.addRules( { elements : { input : function( input ) { var attrs = input.attributes, type = attrs.type; // Old IEs don't provide type for Text inputs #5522 if ( !type ) attrs.type = 'text'; if ( type == 'checkbox' || type == 'radio' ) attrs.value == 'on' && delete attrs.value; } } } ); } if ( dataFilter ) { dataFilter.addRules( { elements : { input : function( element ) { if ( element.attributes.type == 'hidden' ) return editor.createFakeParserElement( element, 'cke_hidden', 'hiddenfield' ); } } } ); } }, requires : [ 'image', 'fakeobjects' ] } ); if ( CKEDITOR.env.ie ) { CKEDITOR.dom.element.prototype.hasAttribute = CKEDITOR.tools.override( CKEDITOR.dom.element.prototype.hasAttribute, function( original ) { return function( name ) { var $attr = this.$.attributes.getNamedItem( name ); if ( this.getName() == 'input' ) { switch ( name ) { case 'class' : return this.$.className.length > 0; case 'checked' : return !!this.$.checked; case 'value' : var type = this.getAttribute( 'type' ); return type == 'checkbox' || type == 'radio' ? this.$.value != 'on' : this.$.value; } } return original.apply( this, arguments ); }; }); }
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'select', function( editor ) { // Add a new option to a SELECT object (combo or list). function addOption( combo, optionText, optionValue, documentObject, index ) { combo = getSelect( combo ); var oOption; if ( documentObject ) oOption = documentObject.createElement( "OPTION" ); else oOption = document.createElement( "OPTION" ); if ( combo && oOption && oOption.getName() == 'option' ) { if ( CKEDITOR.env.ie ) { if ( !isNaN( parseInt( index, 10) ) ) combo.$.options.add( oOption.$, index ); else combo.$.options.add( oOption.$ ); oOption.$.innerHTML = optionText.length > 0 ? optionText : ''; oOption.$.value = optionValue; } else { if ( index !== null && index < combo.getChildCount() ) combo.getChild( index < 0 ? 0 : index ).insertBeforeMe( oOption ); else combo.append( oOption ); oOption.setText( optionText.length > 0 ? optionText : '' ); oOption.setValue( optionValue ); } } else return false; return oOption; } // Remove all selected options from a SELECT object. function removeSelectedOptions( combo ) { combo = getSelect( combo ); // Save the selected index var iSelectedIndex = getSelectedIndex( combo ); // Remove all selected options. for ( var i = combo.getChildren().count() - 1 ; i >= 0 ; i-- ) { if ( combo.getChild( i ).$.selected ) combo.getChild( i ).remove(); } // Reset the selection based on the original selected index. setSelectedIndex( combo, iSelectedIndex ); } //Modify option from a SELECT object. function modifyOption( combo, index, title, value ) { combo = getSelect( combo ); if ( index < 0 ) return false; var child = combo.getChild( index ); child.setText( title ); child.setValue( value ); return child; } function removeAllOptions( combo ) { combo = getSelect( combo ); while ( combo.getChild( 0 ) && combo.getChild( 0 ).remove() ) { /*jsl:pass*/ } } // Moves the selected option by a number of steps (also negative). function changeOptionPosition( combo, steps, documentObject ) { combo = getSelect( combo ); var iActualIndex = getSelectedIndex( combo ); if ( iActualIndex < 0 ) return false; var iFinalIndex = iActualIndex + steps; iFinalIndex = ( iFinalIndex < 0 ) ? 0 : iFinalIndex; iFinalIndex = ( iFinalIndex >= combo.getChildCount() ) ? combo.getChildCount() - 1 : iFinalIndex; if ( iActualIndex == iFinalIndex ) return false; var oOption = combo.getChild( iActualIndex ), sText = oOption.getText(), sValue = oOption.getValue(); oOption.remove(); oOption = addOption( combo, sText, sValue, ( !documentObject ) ? null : documentObject, iFinalIndex ); setSelectedIndex( combo, iFinalIndex ); return oOption; } function getSelectedIndex( combo ) { combo = getSelect( combo ); return combo ? combo.$.selectedIndex : -1; } function setSelectedIndex( combo, index ) { combo = getSelect( combo ); if ( index < 0 ) return null; var count = combo.getChildren().count(); combo.$.selectedIndex = ( index >= count ) ? ( count - 1 ) : index; return combo; } function getOptions( combo ) { combo = getSelect( combo ); return combo ? combo.getChildren() : false; } function getSelect( obj ) { if ( obj && obj.domId && obj.getInputElement().$ ) // Dialog element. return obj.getInputElement(); else if ( obj && obj.$ ) return obj; return false; } return { title : editor.lang.select.title, minWidth : CKEDITOR.env.ie ? 460 : 395, minHeight : CKEDITOR.env.ie ? 320 : 300, onShow : function() { delete this.selectBox; this.setupContent( 'clear' ); var element = this.getParentEditor().getSelection().getSelectedElement(); if ( element && element.getName() == "select" ) { this.selectBox = element; this.setupContent( element.getName(), element ); // Load Options into dialog. var objOptions = getOptions( element ); for ( var i = 0 ; i < objOptions.count() ; i++ ) this.setupContent( 'option', objOptions.getItem( i ) ); } }, onOk : function() { var editor = this.getParentEditor(), element = this.selectBox, isInsertMode = !element; if ( isInsertMode ) element = editor.document.createElement( 'select' ); this.commitContent( element ); if ( isInsertMode ) { editor.insertElement( element ); if ( CKEDITOR.env.ie ) { var sel = editor.getSelection(), bms = sel.createBookmarks(); setTimeout(function() { sel.selectBookmarks( bms ); }, 0 ); } } }, contents : [ { id : 'info', label : editor.lang.select.selectInfo, title : editor.lang.select.selectInfo, accessKey : '', elements : [ { id : 'txtName', type : 'text', widths : [ '25%','75%' ], labelLayout : 'horizontal', label : editor.lang.common.name, 'default' : '', accessKey : 'N', style : 'width:350px', setup : function( name, element ) { if ( name == 'clear' ) this.setValue( this[ 'default' ] || '' ); else if ( name == 'select' ) { this.setValue( element.data( 'cke-saved-name' ) || element.getAttribute( 'name' ) || '' ); } }, commit : function( element ) { if ( this.getValue() ) element.data( 'cke-saved-name', this.getValue() ); else { element.data( 'cke-saved-name', false ); element.removeAttribute( 'name' ); } } }, { id : 'txtValue', type : 'text', widths : [ '25%','75%' ], labelLayout : 'horizontal', label : editor.lang.select.value, style : 'width:350px', 'default' : '', className : 'cke_disabled', onLoad : function() { this.getInputElement().setAttribute( 'readOnly', true ); }, setup : function( name, element ) { if ( name == 'clear' ) this.setValue( '' ); else if ( name == 'option' && element.getAttribute( 'selected' ) ) this.setValue( element.$.value ); } }, { type : 'hbox', widths : [ '175px', '170px' ], children : [ { id : 'txtSize', type : 'text', labelLayout : 'horizontal', label : editor.lang.select.size, 'default' : '', accessKey : 'S', style : 'width:175px', validate: function() { var func = CKEDITOR.dialog.validate.integer( editor.lang.common.validateNumberFailed ); return ( ( this.getValue() === '' ) || func.apply( this ) ); }, setup : function( name, element ) { if ( name == 'select' ) this.setValue( element.getAttribute( 'size' ) || '' ); if ( CKEDITOR.env.webkit ) this.getInputElement().setStyle( 'width', '86px' ); }, commit : function( element ) { if ( this.getValue() ) element.setAttribute( 'size', this.getValue() ); else element.removeAttribute( 'size' ); } }, { type : 'html', html : '<span>' + CKEDITOR.tools.htmlEncode( editor.lang.select.lines ) + '</span>' } ] }, { type : 'html', html : '<span>' + CKEDITOR.tools.htmlEncode( editor.lang.select.opAvail ) + '</span>' }, { type : 'hbox', widths : [ '115px', '115px' ,'100px' ], children : [ { type : 'vbox', children : [ { id : 'txtOptName', type : 'text', label : editor.lang.select.opText, style : 'width:115px', setup : function( name, element ) { if ( name == 'clear' ) this.setValue( "" ); } }, { type : 'select', id : 'cmbName', label : '', title : '', size : 5, style : 'width:115px;height:75px', items : [], onChange : function() { var dialog = this.getDialog(), values = dialog.getContentElement( 'info', 'cmbValue' ), optName = dialog.getContentElement( 'info', 'txtOptName' ), optValue = dialog.getContentElement( 'info', 'txtOptValue' ), iIndex = getSelectedIndex( this ); setSelectedIndex( values, iIndex ); optName.setValue( this.getValue() ); optValue.setValue( values.getValue() ); }, setup : function( name, element ) { if ( name == 'clear' ) removeAllOptions( this ); else if ( name == 'option' ) addOption( this, element.getText(), element.getText(), this.getDialog().getParentEditor().document ); }, commit : function( element ) { var dialog = this.getDialog(), optionsNames = getOptions( this ), optionsValues = getOptions( dialog.getContentElement( 'info', 'cmbValue' ) ), selectValue = dialog.getContentElement( 'info', 'txtValue' ).getValue(); removeAllOptions( element ); for ( var i = 0 ; i < optionsNames.count() ; i++ ) { var oOption = addOption( element, optionsNames.getItem( i ).getValue(), optionsValues.getItem( i ).getValue(), dialog.getParentEditor().document ); if ( optionsValues.getItem( i ).getValue() == selectValue ) { oOption.setAttribute( 'selected', 'selected' ); oOption.selected = true; } } } } ] }, { type : 'vbox', children : [ { id : 'txtOptValue', type : 'text', label : editor.lang.select.opValue, style : 'width:115px', setup : function( name, element ) { if ( name == 'clear' ) this.setValue( "" ); } }, { type : 'select', id : 'cmbValue', label : '', size : 5, style : 'width:115px;height:75px', items : [], onChange : function() { var dialog = this.getDialog(), names = dialog.getContentElement( 'info', 'cmbName' ), optName = dialog.getContentElement( 'info', 'txtOptName' ), optValue = dialog.getContentElement( 'info', 'txtOptValue' ), iIndex = getSelectedIndex( this ); setSelectedIndex( names, iIndex ); optName.setValue( names.getValue() ); optValue.setValue( this.getValue() ); }, setup : function( name, element ) { if ( name == 'clear' ) removeAllOptions( this ); else if ( name == 'option' ) { var oValue = element.getValue(); addOption( this, oValue, oValue, this.getDialog().getParentEditor().document ); if ( element.getAttribute( 'selected' ) == 'selected' ) this.getDialog().getContentElement( 'info', 'txtValue' ).setValue( oValue ); } } } ] }, { type : 'vbox', padding : 5, children : [ { type : 'button', id : 'btnAdd', style : '', label : editor.lang.select.btnAdd, title : editor.lang.select.btnAdd, style : 'width:100%;', onClick : function() { //Add new option. var dialog = this.getDialog(), parentEditor = dialog.getParentEditor(), optName = dialog.getContentElement( 'info', 'txtOptName' ), optValue = dialog.getContentElement( 'info', 'txtOptValue' ), names = dialog.getContentElement( 'info', 'cmbName' ), values = dialog.getContentElement( 'info', 'cmbValue' ); addOption(names, optName.getValue(), optName.getValue(), dialog.getParentEditor().document ); addOption(values, optValue.getValue(), optValue.getValue(), dialog.getParentEditor().document ); optName.setValue( "" ); optValue.setValue( "" ); } }, { type : 'button', id : 'btnModify', label : editor.lang.select.btnModify, title : editor.lang.select.btnModify, style : 'width:100%;', onClick : function() { //Modify selected option. var dialog = this.getDialog(), optName = dialog.getContentElement( 'info', 'txtOptName' ), optValue = dialog.getContentElement( 'info', 'txtOptValue' ), names = dialog.getContentElement( 'info', 'cmbName' ), values = dialog.getContentElement( 'info', 'cmbValue' ), iIndex = getSelectedIndex( names ); if ( iIndex >= 0 ) { modifyOption( names, iIndex, optName.getValue(), optName.getValue() ); modifyOption( values, iIndex, optValue.getValue(), optValue.getValue() ); } } }, { type : 'button', id : 'btnUp', style : 'width:100%;', label : editor.lang.select.btnUp, title : editor.lang.select.btnUp, onClick : function() { //Move up. var dialog = this.getDialog(), names = dialog.getContentElement( 'info', 'cmbName' ), values = dialog.getContentElement( 'info', 'cmbValue' ); changeOptionPosition( names, -1, dialog.getParentEditor().document ); changeOptionPosition( values, -1, dialog.getParentEditor().document ); } }, { type : 'button', id : 'btnDown', style : 'width:100%;', label : editor.lang.select.btnDown, title : editor.lang.select.btnDown, onClick : function() { //Move down. var dialog = this.getDialog(), names = dialog.getContentElement( 'info', 'cmbName' ), values = dialog.getContentElement( 'info', 'cmbValue' ); changeOptionPosition( names, 1, dialog.getParentEditor().document ); changeOptionPosition( values, 1, dialog.getParentEditor().document ); } } ] } ] }, { type : 'hbox', widths : [ '40%', '20%', '40%' ], children : [ { type : 'button', id : 'btnSetValue', label : editor.lang.select.btnSetValue, title : editor.lang.select.btnSetValue, onClick : function() { //Set as default value. var dialog = this.getDialog(), values = dialog.getContentElement( 'info', 'cmbValue' ), txtValue = dialog.getContentElement( 'info', 'txtValue' ); txtValue.setValue( values.getValue() ); } }, { type : 'button', id : 'btnDelete', label : editor.lang.select.btnDelete, title : editor.lang.select.btnDelete, onClick : function() { // Delete option. var dialog = this.getDialog(), names = dialog.getContentElement( 'info', 'cmbName' ), values = dialog.getContentElement( 'info', 'cmbValue' ), optName = dialog.getContentElement( 'info', 'txtOptName' ), optValue = dialog.getContentElement( 'info', 'txtOptValue' ); removeSelectedOptions( names ); removeSelectedOptions( values ); optName.setValue( "" ); optValue.setValue( "" ); } }, { id : 'chkMulti', type : 'checkbox', label : editor.lang.select.chkMulti, 'default' : '', accessKey : 'M', value : "checked", setup : function( name, element ) { if ( name == 'select' ) this.setValue( element.getAttribute( 'multiple' ) ); if ( CKEDITOR.env.webkit ) this.getElement().getParent().setStyle( 'vertical-align', 'middle' ); }, commit : function( element ) { if ( this.getValue() ) element.setAttribute( 'multiple', this.getValue() ); else element.removeAttribute( 'multiple' ); } } ] } ] } ] }; });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'textfield', function( editor ) { var autoAttributes = { value : 1, size : 1, maxLength : 1 }; var acceptedTypes = { text : 1, password : 1 }; return { title : editor.lang.textfield.title, minWidth : 350, minHeight : 150, onShow : function() { delete this.textField; var element = this.getParentEditor().getSelection().getSelectedElement(); if ( element && element.getName() == "input" && ( acceptedTypes[ element.getAttribute( 'type' ) ] || !element.getAttribute( 'type' ) ) ) { this.textField = element; this.setupContent( element ); } }, onOk : function() { var editor, element = this.textField, isInsertMode = !element; if ( isInsertMode ) { editor = this.getParentEditor(); element = editor.document.createElement( 'input' ); element.setAttribute( 'type', 'text' ); } if ( isInsertMode ) editor.insertElement( element ); this.commitContent( { element : element } ); }, onLoad : function() { var autoSetup = function( element ) { var value = element.hasAttribute( this.id ) && element.getAttribute( this.id ); this.setValue( value || '' ); }; var autoCommit = function( data ) { var element = data.element; var value = this.getValue(); if ( value ) element.setAttribute( this.id, value ); else element.removeAttribute( this.id ); }; this.foreach( function( contentObj ) { if ( autoAttributes[ contentObj.id ] ) { contentObj.setup = autoSetup; contentObj.commit = autoCommit; } } ); }, contents : [ { id : 'info', label : editor.lang.textfield.title, title : editor.lang.textfield.title, elements : [ { type : 'hbox', widths : [ '50%', '50%' ], children : [ { id : '_cke_saved_name', type : 'text', label : editor.lang.textfield.name, 'default' : '', accessKey : 'N', setup : function( element ) { this.setValue( element.data( 'cke-saved-name' ) || element.getAttribute( 'name' ) || '' ); }, commit : function( data ) { var element = data.element; if ( this.getValue() ) element.data( 'cke-saved-name', this.getValue() ); else { element.data( 'cke-saved-name', false ); element.removeAttribute( 'name' ); } } }, { id : 'value', type : 'text', label : editor.lang.textfield.value, 'default' : '', accessKey : 'V' } ] }, { type : 'hbox', widths : [ '50%', '50%' ], children : [ { id : 'size', type : 'text', label : editor.lang.textfield.charWidth, 'default' : '', accessKey : 'C', style : 'width:50px', validate : CKEDITOR.dialog.validate.integer( editor.lang.common.validateNumberFailed ) }, { id : 'maxLength', type : 'text', label : editor.lang.textfield.maxChars, 'default' : '', accessKey : 'M', style : 'width:50px', validate : CKEDITOR.dialog.validate.integer( editor.lang.common.validateNumberFailed ) } ], onLoad : function() { // Repaint the style for IE7 (#6068) if ( CKEDITOR.env.ie7Compat ) this.getElement().setStyle( 'zoom', '100%' ); } }, { id : 'type', type : 'select', label : editor.lang.textfield.type, 'default' : 'text', accessKey : 'M', items : [ [ editor.lang.textfield.typeText, 'text' ], [ editor.lang.textfield.typePass, 'password' ] ], setup : function( element ) { this.setValue( element.getAttribute( 'type' ) ); }, commit : function( data ) { var element = data.element; if ( CKEDITOR.env.ie ) { var elementType = element.getAttribute( 'type' ); var myType = this.getValue(); if ( elementType != myType ) { var replace = CKEDITOR.dom.element.createFromHtml( '<input type="' + myType + '"></input>', editor.document ); element.copyAttributes( replace, { type : 1 } ); replace.replace( element ); editor.getSelection().selectElement( replace ); data.element = replace; } } else element.setAttribute( 'type', this.getValue() ); } } ] } ] }; });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'hiddenfield', function( editor ) { return { title : editor.lang.hidden.title, hiddenField : null, minWidth : 350, minHeight : 110, onShow : function() { delete this.hiddenField; var editor = this.getParentEditor(), selection = editor.getSelection(), element = selection.getSelectedElement(); if ( element && element.data( 'cke-real-element-type' ) && element.data( 'cke-real-element-type' ) == 'hiddenfield' ) { this.hiddenField = element; element = editor.restoreRealElement( this.hiddenField ); this.setupContent( element ); selection.selectElement( this.hiddenField ); } }, onOk : function() { var name = this.getValueOf( 'info', '_cke_saved_name' ), value = this.getValueOf( 'info', 'value' ), editor = this.getParentEditor(), element = CKEDITOR.env.ie && !( CKEDITOR.document.$.documentMode >= 8 ) ? editor.document.createElement( '<input name="' + CKEDITOR.tools.htmlEncode( name ) + '">' ) : editor.document.createElement( 'input' ); element.setAttribute( 'type', 'hidden' ); this.commitContent( element ); var fakeElement = editor.createFakeElement( element, 'cke_hidden', 'hiddenfield' ); if ( !this.hiddenField ) editor.insertElement( fakeElement ); else { fakeElement.replace( this.hiddenField ); editor.getSelection().selectElement( fakeElement ); } return true; }, contents : [ { id : 'info', label : editor.lang.hidden.title, title : editor.lang.hidden.title, elements : [ { id : '_cke_saved_name', type : 'text', label : editor.lang.hidden.name, 'default' : '', accessKey : 'N', setup : function( element ) { this.setValue( element.data( 'cke-saved-name' ) || element.getAttribute( 'name' ) || '' ); }, commit : function( element ) { if ( this.getValue() ) element.setAttribute( 'name', this.getValue() ); else { element.removeAttribute( 'name' ); } } }, { id : 'value', type : 'text', label : editor.lang.hidden.value, 'default' : '', accessKey : 'V', setup : function( element ) { this.setValue( element.getAttribute( 'value' ) || '' ); }, commit : function( element ) { if ( this.getValue() ) element.setAttribute( 'value', this.getValue() ); else element.removeAttribute( 'value' ); } } ] } ] }; });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'button', function( editor ) { function commitAttributes( element ) { var val = this.getValue(); if ( val ) { element.attributes[ this.id ] = val; if ( this.id == 'name' ) element.attributes[ 'data-cke-saved-name' ] = val; } else { delete element.attributes[ this.id ]; if ( this.id == 'name' ) delete element.attributes[ 'data-cke-saved-name' ]; } } return { title : editor.lang.button.title, minWidth : 350, minHeight : 150, onShow : function() { delete this.button; var element = this.getParentEditor().getSelection().getSelectedElement(); if ( element && element.is( 'input' ) ) { var type = element.getAttribute( 'type' ); if ( type in { button:1, reset:1, submit:1 } ) { this.button = element; this.setupContent( element ); } } }, onOk : function() { var editor = this.getParentEditor(), element = this.button, isInsertMode = !element; var fake = element ? CKEDITOR.htmlParser.fragment.fromHtml( element.getOuterHtml() ).children[ 0 ] : new CKEDITOR.htmlParser.element( 'input' ); this.commitContent( fake ); var writer = new CKEDITOR.htmlParser.basicWriter(); fake.writeHtml( writer ); var newElement = CKEDITOR.dom.element.createFromHtml( writer.getHtml(), editor.document ); if ( isInsertMode ) editor.insertElement( newElement ); else { newElement.replace( element ); editor.getSelection().selectElement( newElement ); } }, contents : [ { id : 'info', label : editor.lang.button.title, title : editor.lang.button.title, elements : [ { id : 'name', type : 'text', label : editor.lang.common.name, 'default' : '', setup : function( element ) { this.setValue( element.data( 'cke-saved-name' ) || element.getAttribute( 'name' ) || '' ); }, commit : commitAttributes }, { id : 'value', type : 'text', label : editor.lang.button.text, accessKey : 'V', 'default' : '', setup : function( element ) { this.setValue( element.getAttribute( 'value' ) || '' ); }, commit : commitAttributes }, { id : 'type', type : 'select', label : editor.lang.button.type, 'default' : 'button', accessKey : 'T', items : [ [ editor.lang.button.typeBtn, 'button' ], [ editor.lang.button.typeSbm, 'submit' ], [ editor.lang.button.typeRst, 'reset' ] ], setup : function( element ) { this.setValue( element.getAttribute( 'type' ) || '' ); }, commit : commitAttributes } ] } ] }; });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'form', function( editor ) { var autoAttributes = { action : 1, id : 1, method : 1, enctype : 1, target : 1 }; return { title : editor.lang.form.title, minWidth : 350, minHeight : 200, onShow : function() { delete this.form; var element = this.getParentEditor().getSelection().getStartElement(); var form = element && element.getAscendant( 'form', true ); if ( form ) { this.form = form; this.setupContent( form ); } }, onOk : function() { var editor, element = this.form, isInsertMode = !element; if ( isInsertMode ) { editor = this.getParentEditor(); element = editor.document.createElement( 'form' ); !CKEDITOR.env.ie && element.append( editor.document.createElement( 'br' ) ); } if ( isInsertMode ) editor.insertElement( element ); this.commitContent( element ); }, onLoad : function() { function autoSetup( element ) { this.setValue( element.getAttribute( this.id ) || '' ); } function autoCommit( element ) { if ( this.getValue() ) element.setAttribute( this.id, this.getValue() ); else element.removeAttribute( this.id ); } this.foreach( function( contentObj ) { if ( autoAttributes[ contentObj.id ] ) { contentObj.setup = autoSetup; contentObj.commit = autoCommit; } } ); }, contents : [ { id : 'info', label : editor.lang.form.title, title : editor.lang.form.title, elements : [ { id : 'txtName', type : 'text', label : editor.lang.common.name, 'default' : '', accessKey : 'N', setup : function( element ) { this.setValue( element.data( 'cke-saved-name' ) || element.getAttribute( 'name' ) || '' ); }, commit : function( element ) { if ( this.getValue() ) element.data( 'cke-saved-name', this.getValue() ); else { element.data( 'cke-saved-name', false ); element.removeAttribute( 'name' ); } } }, { id : 'action', type : 'text', label : editor.lang.form.action, 'default' : '', accessKey : 'T' }, { type : 'hbox', widths : [ '45%', '55%' ], children : [ { id : 'id', type : 'text', label : editor.lang.common.id, 'default' : '', accessKey : 'I' }, { id : 'enctype', type : 'select', label : editor.lang.form.encoding, style : 'width:100%', accessKey : 'E', 'default' : '', items : [ [ '' ], [ 'text/plain' ], [ 'multipart/form-data' ], [ 'application/x-www-form-urlencoded' ] ] } ] }, { type : 'hbox', widths : [ '45%', '55%' ], children : [ { id : 'target', type : 'select', label : editor.lang.common.target, style : 'width:100%', accessKey : 'M', 'default' : '', items : [ [ editor.lang.common.notSet, '' ], [ editor.lang.common.targetNew, '_blank' ], [ editor.lang.common.targetTop, '_top' ], [ editor.lang.common.targetSelf, '_self' ], [ editor.lang.common.targetParent, '_parent' ] ] }, { id : 'method', type : 'select', label : editor.lang.form.method, accessKey : 'M', 'default' : 'GET', items : [ [ 'GET', 'get' ], [ 'POST', 'post' ] ] } ] } ] } ] }; });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'textarea', function( editor ) { return { title : editor.lang.textarea.title, minWidth : 350, minHeight : 220, onShow : function() { delete this.textarea; var element = this.getParentEditor().getSelection().getSelectedElement(); if ( element && element.getName() == "textarea" ) { this.textarea = element; this.setupContent( element ); } }, onOk : function() { var editor, element = this.textarea, isInsertMode = !element; if ( isInsertMode ) { editor = this.getParentEditor(); element = editor.document.createElement( 'textarea' ); } this.commitContent( element ); if ( isInsertMode ) editor.insertElement( element ); }, contents : [ { id : 'info', label : editor.lang.textarea.title, title : editor.lang.textarea.title, elements : [ { id : '_cke_saved_name', type : 'text', label : editor.lang.common.name, 'default' : '', accessKey : 'N', setup : function( element ) { this.setValue( element.data( 'cke-saved-name' ) || element.getAttribute( 'name' ) || '' ); }, commit : function( element ) { if ( this.getValue() ) element.data( 'cke-saved-name', this.getValue() ); else { element.data( 'cke-saved-name', false ); element.removeAttribute( 'name' ); } } }, { type : 'hbox', widths:['50%','50%'], children:[ { id : 'cols', type : 'text', label : editor.lang.textarea.cols, 'default' : '', accessKey : 'C', style : 'width:50px', validate : CKEDITOR.dialog.validate.integer( editor.lang.common.validateNumberFailed ), setup : function( element ) { var value = element.hasAttribute( 'cols' ) && element.getAttribute( 'cols' ); this.setValue( value || '' ); }, commit : function( element ) { if ( this.getValue() ) element.setAttribute( 'cols', this.getValue() ); else element.removeAttribute( 'cols' ); } }, { id : 'rows', type : 'text', label : editor.lang.textarea.rows, 'default' : '', accessKey : 'R', style : 'width:50px', validate : CKEDITOR.dialog.validate.integer( editor.lang.common.validateNumberFailed ), setup : function( element ) { var value = element.hasAttribute( 'rows' ) && element.getAttribute( 'rows' ); this.setValue( value || '' ); }, commit : function( element ) { if ( this.getValue() ) element.setAttribute( 'rows', this.getValue() ); else element.removeAttribute( 'rows' ); } } ] }, { id : 'value', type : 'textarea', label : editor.lang.textfield.value, 'default' : '', setup : function( element ) { this.setValue( element.$.defaultValue ); }, commit : function( element ) { element.$.value = element.$.defaultValue = this.getValue() ; } } ] } ] }; });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'radio', function( editor ) { return { title : editor.lang.checkboxAndRadio.radioTitle, minWidth : 350, minHeight : 140, onShow : function() { delete this.radioButton; var element = this.getParentEditor().getSelection().getSelectedElement(); if ( element && element.getName() == 'input' && element.getAttribute( 'type' ) == 'radio' ) { this.radioButton = element; this.setupContent( element ); } }, onOk : function() { var editor, element = this.radioButton, isInsertMode = !element; if ( isInsertMode ) { editor = this.getParentEditor(); element = editor.document.createElement( 'input' ); element.setAttribute( 'type', 'radio' ); } if ( isInsertMode ) editor.insertElement( element ); this.commitContent( { element : element } ); }, contents : [ { id : 'info', label : editor.lang.checkboxAndRadio.radioTitle, title : editor.lang.checkboxAndRadio.radioTitle, elements : [ { id : 'name', type : 'text', label : editor.lang.common.name, 'default' : '', accessKey : 'N', setup : function( element ) { this.setValue( element.data( 'cke-saved-name' ) || element.getAttribute( 'name' ) || '' ); }, commit : function( data ) { var element = data.element; if ( this.getValue() ) element.data( 'cke-saved-name', this.getValue() ); else { element.data( 'cke-saved-name', false ); element.removeAttribute( 'name' ); } } }, { id : 'value', type : 'text', label : editor.lang.checkboxAndRadio.value, 'default' : '', accessKey : 'V', setup : function( element ) { this.setValue( element.getAttribute( 'value' ) || '' ); }, commit : function( data ) { var element = data.element; if ( this.getValue() ) element.setAttribute( 'value', this.getValue() ); else element.removeAttribute( 'value' ); } }, { id : 'checked', type : 'checkbox', label : editor.lang.checkboxAndRadio.selected, 'default' : '', accessKey : 'S', value : "checked", setup : function( element ) { this.setValue( element.getAttribute( 'checked' ) ); }, commit : function( data ) { var element = data.element; if ( !( CKEDITOR.env.ie || CKEDITOR.env.opera ) ) { if ( this.getValue() ) element.setAttribute( 'checked', 'checked' ); else element.removeAttribute( 'checked' ); } else { var isElementChecked = element.getAttribute( 'checked' ); var isChecked = !!this.getValue(); if ( isElementChecked != isChecked ) { var replace = CKEDITOR.dom.element.createFromHtml( '<input type="radio"' + ( isChecked ? ' checked="checked"' : '' ) + '></input>', editor.document ); element.copyAttributes( replace, { type : 1, checked : 1 } ); replace.replace( element ); editor.getSelection().selectElement( replace ); data.element = replace; } } } } ] } ] }; });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'checkbox', function( editor ) { return { title : editor.lang.checkboxAndRadio.checkboxTitle, minWidth : 350, minHeight : 140, onShow : function() { delete this.checkbox; var element = this.getParentEditor().getSelection().getSelectedElement(); if ( element && element.getAttribute( 'type' ) == 'checkbox' ) { this.checkbox = element; this.setupContent( element ); } }, onOk : function() { var editor, element = this.checkbox, isInsertMode = !element; if ( isInsertMode ) { editor = this.getParentEditor(); element = editor.document.createElement( 'input' ); element.setAttribute( 'type', 'checkbox' ); editor.insertElement( element ); } this.commitContent( { element : element } ); }, contents : [ { id : 'info', label : editor.lang.checkboxAndRadio.checkboxTitle, title : editor.lang.checkboxAndRadio.checkboxTitle, startupFocus : 'txtName', elements : [ { id : 'txtName', type : 'text', label : editor.lang.common.name, 'default' : '', accessKey : 'N', setup : function( element ) { this.setValue( element.data( 'cke-saved-name' ) || element.getAttribute( 'name' ) || '' ); }, commit : function( data ) { var element = data.element; // IE failed to update 'name' property on input elements, protect it now. if ( this.getValue() ) element.data( 'cke-saved-name', this.getValue() ); else { element.data( 'cke-saved-name', false ); element.removeAttribute( 'name' ); } } }, { id : 'txtValue', type : 'text', label : editor.lang.checkboxAndRadio.value, 'default' : '', accessKey : 'V', setup : function( element ) { var value = element.getAttribute( 'value' ); // IE Return 'on' as default attr value. this.setValue( CKEDITOR.env.ie && value == 'on' ? '' : value ); }, commit : function( data ) { var element = data.element, value = this.getValue(); if ( value && !( CKEDITOR.env.ie && value == 'on' ) ) element.setAttribute( 'value', value ); else { if ( CKEDITOR.env.ie ) { // Remove attribute 'value' of checkbox (#4721). var checkbox = new CKEDITOR.dom.element( 'input', element.getDocument() ); element.copyAttributes( checkbox, { value: 1 } ); checkbox.replace( element ); editor.getSelection().selectElement( checkbox ); data.element = checkbox; } else element.removeAttribute( 'value' ); } } }, { id : 'cmbSelected', type : 'checkbox', label : editor.lang.checkboxAndRadio.selected, 'default' : '', accessKey : 'S', value : "checked", setup : function( element ) { this.setValue( element.getAttribute( 'checked' ) ); }, commit : function( data ) { var element = data.element; if ( CKEDITOR.env.ie ) { var isElementChecked = !!element.getAttribute( 'checked' ), isChecked = !!this.getValue(); if ( isElementChecked != isChecked ) { var replace = CKEDITOR.dom.element.createFromHtml( '<input type="checkbox"' + ( isChecked ? ' checked="checked"' : '' ) + '/>', editor.document ); element.copyAttributes( replace, { type : 1, checked : 1 } ); replace.replace( element ); editor.getSelection().selectElement( replace ); data.element = replace; } } else { var value = this.getValue(); if ( value ) element.setAttribute( 'checked', 'checked' ); else element.removeAttribute( 'checked' ); } } } ] } ] }; });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ // Register a plugin named "sample". CKEDITOR.plugins.add( 'keystrokes', { beforeInit : function( editor ) { /** * Controls keystrokes typing in this editor instance. * @name CKEDITOR.editor.prototype.keystrokeHandler * @type CKEDITOR.keystrokeHandler * @example */ editor.keystrokeHandler = new CKEDITOR.keystrokeHandler( editor ); editor.specialKeys = {}; }, init : function( editor ) { var keystrokesConfig = editor.config.keystrokes, blockedConfig = editor.config.blockedKeystrokes; var keystrokes = editor.keystrokeHandler.keystrokes, blockedKeystrokes = editor.keystrokeHandler.blockedKeystrokes; for ( var i = 0 ; i < keystrokesConfig.length ; i++ ) keystrokes[ keystrokesConfig[i][0] ] = keystrokesConfig[i][1]; for ( i = 0 ; i < blockedConfig.length ; i++ ) blockedKeystrokes[ blockedConfig[i] ] = 1; } }); /** * Controls keystrokes typing in an editor instance. * @constructor * @param {CKEDITOR.editor} editor The editor instance. * @example */ CKEDITOR.keystrokeHandler = function( editor ) { if ( editor.keystrokeHandler ) return editor.keystrokeHandler; /** * List of keystrokes associated to commands. Each entry points to the * command to be executed. * @type Object * @example */ this.keystrokes = {}; /** * List of keystrokes that should be blocked if not defined at * {@link keystrokes}. In this way it is possible to block the default * browser behavior for those keystrokes. * @type Object * @example */ this.blockedKeystrokes = {}; this._ = { editor : editor }; return this; }; (function() { var cancel; var onKeyDown = function( event ) { // The DOM event object is passed by the "data" property. event = event.data; var keyCombination = event.getKeystroke(); var command = this.keystrokes[ keyCombination ]; var editor = this._.editor; cancel = ( editor.fire( 'key', { keyCode : keyCombination } ) === true ); if ( !cancel ) { if ( command ) { var data = { from : 'keystrokeHandler' }; cancel = ( editor.execCommand( command, data ) !== false ); } if ( !cancel ) { var handler = editor.specialKeys[ keyCombination ]; cancel = ( handler && handler( editor ) === true ); if ( !cancel ) cancel = !!this.blockedKeystrokes[ keyCombination ]; } } if ( cancel ) event.preventDefault( true ); return !cancel; }; var onKeyPress = function( event ) { if ( cancel ) { cancel = false; event.data.preventDefault( true ); } }; CKEDITOR.keystrokeHandler.prototype = { /** * Attaches this keystroke handle to a DOM object. Keystrokes typed ** over this object will get handled by this keystrokeHandler. * @param {CKEDITOR.dom.domObject} domObject The DOM object to attach * to. * @example */ attach : function( domObject ) { // For most browsers, it is enough to listen to the keydown event // only. domObject.on( 'keydown', onKeyDown, this ); // Some browsers instead, don't cancel key events in the keydown, but in the // keypress. So we must do a longer trip in those cases. if ( CKEDITOR.env.opera || ( CKEDITOR.env.gecko && CKEDITOR.env.mac ) ) domObject.on( 'keypress', onKeyPress, this ); } }; })(); /** * A list of keystrokes to be blocked if not defined in the {@link CKEDITOR.config.keystrokes} * setting. In this way it is possible to block the default browser behavior * for those keystrokes. * @type Array * @default (see example) * @example * // This is actually the default value. * config.blockedKeystrokes = * [ * CKEDITOR.CTRL + 66 &#47;*B*&#47;, * CKEDITOR.CTRL + 73 &#47;*I*&#47;, * CKEDITOR.CTRL + 85 &#47;*U*&#47; * ]; */ CKEDITOR.config.blockedKeystrokes = [ CKEDITOR.CTRL + 66 /*B*/, CKEDITOR.CTRL + 73 /*I*/, CKEDITOR.CTRL + 85 /*U*/ ]; /** * A list associating keystrokes to editor commands. Each element in the list * is an array where the first item is the keystroke, and the second is the * name of the command to be executed. * @type Array * @default (see example) * @example * // This is actually the default value. * config.keystrokes = * [ * [ CKEDITOR.ALT + 121 &#47;*F10*&#47;, 'toolbarFocus' ], * [ CKEDITOR.ALT + 122 &#47;*F11*&#47;, 'elementsPathFocus' ], * * [ CKEDITOR.SHIFT + 121 &#47;*F10*&#47;, 'contextMenu' ], * * [ CKEDITOR.CTRL + 90 &#47;*Z*&#47;, 'undo' ], * [ CKEDITOR.CTRL + 89 &#47;*Y*&#47;, 'redo' ], * [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 90 &#47;*Z*&#47;, 'redo' ], * * [ CKEDITOR.CTRL + 76 &#47;*L*&#47;, 'link' ], * * [ CKEDITOR.CTRL + 66 &#47;*B*&#47;, 'bold' ], * [ CKEDITOR.CTRL + 73 &#47;*I*&#47;, 'italic' ], * [ CKEDITOR.CTRL + 85 &#47;*U*&#47;, 'underline' ], * * [ CKEDITOR.ALT + 109 &#47;*-*&#47;, 'toolbarCollapse' ] * ]; */ CKEDITOR.config.keystrokes = [ [ CKEDITOR.ALT + 121 /*F10*/, 'toolbarFocus' ], [ CKEDITOR.ALT + 122 /*F11*/, 'elementsPathFocus' ], [ CKEDITOR.SHIFT + 121 /*F10*/, 'contextMenu' ], [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 121 /*F10*/, 'contextMenu' ], [ CKEDITOR.CTRL + 90 /*Z*/, 'undo' ], [ CKEDITOR.CTRL + 89 /*Y*/, 'redo' ], [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 90 /*Z*/, 'redo' ], [ CKEDITOR.CTRL + 76 /*L*/, 'link' ], [ CKEDITOR.CTRL + 66 /*B*/, 'bold' ], [ CKEDITOR.CTRL + 73 /*I*/, 'italic' ], [ CKEDITOR.CTRL + 85 /*U*/, 'underline' ], [ CKEDITOR.ALT + ( CKEDITOR.env.ie || CKEDITOR.env.webkit ? 189 : 109 ) /*-*/, 'toolbarCollapse' ], [ CKEDITOR.ALT + 48 /*0*/, 'a11yHelp' ] ]; /** * Fired when any keyboard key (or combination) is pressed into the editing area. * @name CKEDITOR.editor#key * @event * @param {Number} data.keyCode A number representing the key code (or * combination). It is the sum of the current key code and the * {@link CKEDITOR.CTRL}, {@link CKEDITOR.SHIFT} and {@link CKEDITOR.ALT} * constants, if those are pressed. */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @file DOM iterator, which iterates over list items, lines and paragraphs. */ CKEDITOR.plugins.add( 'domiterator' ); (function() { /** * @name CKEDITOR.dom.iterator */ function iterator( range ) { if ( arguments.length < 1 ) return; this.range = range; this.forceBrBreak = 0; // Whether include <br>s into the enlarged range.(#3730). this.enlargeBr = 1; this.enforceRealBlocks = 0; this._ || ( this._ = {} ); } var beginWhitespaceRegex = /^[\r\n\t ]+$/, // Ignore bookmark nodes.(#3783) bookmarkGuard = CKEDITOR.dom.walker.bookmark( false, true ), whitespacesGuard = CKEDITOR.dom.walker.whitespaces( true ), skipGuard = function( node ) { return bookmarkGuard( node ) && whitespacesGuard( node ); }; // Get a reference for the next element, bookmark nodes are skipped. function getNextSourceNode( node, startFromSibling, lastNode ) { var next = node.getNextSourceNode( startFromSibling, null, lastNode ); while ( !bookmarkGuard( next ) ) next = next.getNextSourceNode( startFromSibling, null, lastNode ); return next; } iterator.prototype = { getNextParagraph : function( blockTag ) { // The block element to be returned. var block; // The range object used to identify the paragraph contents. var range; // Indicats that the current element in the loop is the last one. var isLast; // Indicate at least one of the range boundaries is inside a preformat block. var touchPre; // Instructs to cleanup remaining BRs. var removePreviousBr, removeLastBr; // This is the first iteration. Let's initialize it. if ( !this._.lastNode ) { range = this.range.clone(); // Shrink the range to exclude harmful "noises" (#4087, #4450, #5435). range.shrink( CKEDITOR.NODE_ELEMENT, true ); touchPre = range.endContainer.hasAscendant( 'pre', true ) || range.startContainer.hasAscendant( 'pre', true ); range.enlarge( this.forceBrBreak && !touchPre || !this.enlargeBr ? CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS : CKEDITOR.ENLARGE_BLOCK_CONTENTS ); var walker = new CKEDITOR.dom.walker( range ), ignoreBookmarkTextEvaluator = CKEDITOR.dom.walker.bookmark( true, true ); // Avoid anchor inside bookmark inner text. walker.evaluator = ignoreBookmarkTextEvaluator; this._.nextNode = walker.next(); // TODO: It's better to have walker.reset() used here. walker = new CKEDITOR.dom.walker( range ); walker.evaluator = ignoreBookmarkTextEvaluator; var lastNode = walker.previous(); this._.lastNode = lastNode.getNextSourceNode( true ); // We may have an empty text node at the end of block due to [3770]. // If that node is the lastNode, it would cause our logic to leak to the // next block.(#3887) if ( this._.lastNode && this._.lastNode.type == CKEDITOR.NODE_TEXT && !CKEDITOR.tools.trim( this._.lastNode.getText() ) && this._.lastNode.getParent().isBlockBoundary() ) { var testRange = new CKEDITOR.dom.range( range.document ); testRange.moveToPosition( this._.lastNode, CKEDITOR.POSITION_AFTER_END ); if ( testRange.checkEndOfBlock() ) { var path = new CKEDITOR.dom.elementPath( testRange.endContainer ); var lastBlock = path.block || path.blockLimit; this._.lastNode = lastBlock.getNextSourceNode( true ); } } // Probably the document end is reached, we need a marker node. if ( !this._.lastNode ) { this._.lastNode = this._.docEndMarker = range.document.createText( '' ); this._.lastNode.insertAfter( lastNode ); } // Let's reuse this variable. range = null; } var currentNode = this._.nextNode; lastNode = this._.lastNode; this._.nextNode = null; while ( currentNode ) { // closeRange indicates that a paragraph boundary has been found, // so the range can be closed. var closeRange = 0, parentPre = currentNode.hasAscendant( 'pre' ); // includeNode indicates that the current node is good to be part // of the range. By default, any non-element node is ok for it. var includeNode = ( currentNode.type != CKEDITOR.NODE_ELEMENT ), continueFromSibling = 0; // If it is an element node, let's check if it can be part of the // range. if ( !includeNode ) { var nodeName = currentNode.getName(); if ( currentNode.isBlockBoundary( this.forceBrBreak && !parentPre && { br : 1 } ) ) { // <br> boundaries must be part of the range. It will // happen only if ForceBrBreak. if ( nodeName == 'br' ) includeNode = 1; else if ( !range && !currentNode.getChildCount() && nodeName != 'hr' ) { // If we have found an empty block, and haven't started // the range yet, it means we must return this block. block = currentNode; isLast = currentNode.equals( lastNode ); break; } // The range must finish right before the boundary, // including possibly skipped empty spaces. (#1603) if ( range ) { range.setEndAt( currentNode, CKEDITOR.POSITION_BEFORE_START ); // The found boundary must be set as the next one at this // point. (#1717) if ( nodeName != 'br' ) this._.nextNode = currentNode; } closeRange = 1; } else { // If we have child nodes, let's check them. if ( currentNode.getFirst() ) { // If we don't have a range yet, let's start it. if ( !range ) { range = new CKEDITOR.dom.range( this.range.document ); range.setStartAt( currentNode, CKEDITOR.POSITION_BEFORE_START ); } currentNode = currentNode.getFirst(); continue; } includeNode = 1; } } else if ( currentNode.type == CKEDITOR.NODE_TEXT ) { // Ignore normal whitespaces (i.e. not including &nbsp; or // other unicode whitespaces) before/after a block node. if ( beginWhitespaceRegex.test( currentNode.getText() ) ) includeNode = 0; } // The current node is good to be part of the range and we are // starting a new range, initialize it first. if ( includeNode && !range ) { range = new CKEDITOR.dom.range( this.range.document ); range.setStartAt( currentNode, CKEDITOR.POSITION_BEFORE_START ); } // The last node has been found. isLast = ( ( !closeRange || includeNode ) && currentNode.equals( lastNode ) ); // If we are in an element boundary, let's check if it is time // to close the range, otherwise we include the parent within it. if ( range && !closeRange ) { while ( !currentNode.getNext( skipGuard ) && !isLast ) { var parentNode = currentNode.getParent(); if ( parentNode.isBlockBoundary( this.forceBrBreak && !parentPre && { br : 1 } ) ) { closeRange = 1; includeNode = 0; isLast = isLast || ( parentNode.equals( lastNode) ); // Make sure range includes bookmarks at the end of the block. (#7359) range.setEndAt( parentNode, CKEDITOR.POSITION_BEFORE_END ); break; } currentNode = parentNode; includeNode = 1; isLast = ( currentNode.equals( lastNode ) ); continueFromSibling = 1; } } // Now finally include the node. if ( includeNode ) range.setEndAt( currentNode, CKEDITOR.POSITION_AFTER_END ); currentNode = getNextSourceNode ( currentNode, continueFromSibling, lastNode ); isLast = !currentNode; // We have found a block boundary. Let's close the range and move out of the // loop. if ( isLast || ( closeRange && range ) ) break; } // Now, based on the processed range, look for (or create) the block to be returned. if ( !block ) { // If no range has been found, this is the end. if ( !range ) { this._.docEndMarker && this._.docEndMarker.remove(); this._.nextNode = null; return null; } var startPath = new CKEDITOR.dom.elementPath( range.startContainer ); var startBlockLimit = startPath.blockLimit, checkLimits = { div : 1, th : 1, td : 1 }; block = startPath.block; if ( !block && !this.enforceRealBlocks && checkLimits[ startBlockLimit.getName() ] && range.checkStartOfBlock() && range.checkEndOfBlock() ) block = startBlockLimit; else if ( !block || ( this.enforceRealBlocks && block.getName() == 'li' ) ) { // Create the fixed block. block = this.range.document.createElement( blockTag || 'p' ); // Move the contents of the temporary range to the fixed block. range.extractContents().appendTo( block ); block.trim(); // Insert the fixed block into the DOM. range.insertNode( block ); removePreviousBr = removeLastBr = true; } else if ( block.getName() != 'li' ) { // If the range doesn't includes the entire contents of the // block, we must split it, isolating the range in a dedicated // block. if ( !range.checkStartOfBlock() || !range.checkEndOfBlock() ) { // The resulting block will be a clone of the current one. block = block.clone( false ); // Extract the range contents, moving it to the new block. range.extractContents().appendTo( block ); block.trim(); // Split the block. At this point, the range will be in the // right position for our intents. var splitInfo = range.splitBlock(); removePreviousBr = !splitInfo.wasStartOfBlock; removeLastBr = !splitInfo.wasEndOfBlock; // Insert the new block into the DOM. range.insertNode( block ); } } else if ( !isLast ) { // LIs are returned as is, with all their children (due to the // nested lists). But, the next node is the node right after // the current range, which could be an <li> child (nested // lists) or the next sibling <li>. this._.nextNode = ( block.equals( lastNode ) ? null : getNextSourceNode( range.getBoundaryNodes().endNode, 1, lastNode ) ); } } if ( removePreviousBr ) { var previousSibling = block.getPrevious(); if ( previousSibling && previousSibling.type == CKEDITOR.NODE_ELEMENT ) { if ( previousSibling.getName() == 'br' ) previousSibling.remove(); else if ( previousSibling.getLast() && previousSibling.getLast().$.nodeName.toLowerCase() == 'br' ) previousSibling.getLast().remove(); } } if ( removeLastBr ) { var lastChild = block.getLast(); if ( lastChild && lastChild.type == CKEDITOR.NODE_ELEMENT && lastChild.getName() == 'br' ) { // Take care not to remove the block expanding <br> in non-IE browsers. if ( CKEDITOR.env.ie || lastChild.getPrevious( bookmarkGuard ) || lastChild.getNext( bookmarkGuard ) ) lastChild.remove(); } } // Get a reference for the next element. This is important because the // above block can be removed or changed, so we can rely on it for the // next interation. if ( !this._.nextNode ) { this._.nextNode = ( isLast || block.equals( lastNode ) ) ? null : getNextSourceNode( block, 1, lastNode ); } return block; } }; CKEDITOR.dom.range.prototype.createIterator = function() { return new iterator( this ); }; })();
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.add( 'table', { init : function( editor ) { var table = CKEDITOR.plugins.table, lang = editor.lang.table; editor.addCommand( 'table', new CKEDITOR.dialogCommand( 'table' ) ); editor.addCommand( 'tableProperties', new CKEDITOR.dialogCommand( 'tableProperties' ) ); editor.ui.addButton( 'Table', { label : lang.toolbar, command : 'table' }); CKEDITOR.dialog.add( 'table', this.path + 'dialogs/table.js' ); CKEDITOR.dialog.add( 'tableProperties', this.path + 'dialogs/table.js' ); // If the "menu" plugin is loaded, register the menu items. if ( editor.addMenuItems ) { editor.addMenuItems( { table : { label : lang.menu, command : 'tableProperties', group : 'table', order : 5 }, tabledelete : { label : lang.deleteTable, command : 'tableDelete', group : 'table', order : 1 } } ); } editor.on( 'doubleclick', function( evt ) { var element = evt.data.element; if ( element.is( 'table' ) ) evt.data.dialog = 'tableProperties'; }); // If the "contextmenu" plugin is loaded, register the listeners. if ( editor.contextMenu ) { editor.contextMenu.addListener( function( element, selection ) { if ( !element || element.isReadOnly() ) return null; var isTable = element.hasAscendant( 'table', 1 ); if ( isTable ) { return { tabledelete : CKEDITOR.TRISTATE_OFF, table : CKEDITOR.TRISTATE_OFF }; } return null; } ); } } } );
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { var defaultToPixel = CKEDITOR.tools.cssLength; var commitValue = function( data ) { var id = this.id; if ( !data.info ) data.info = {}; data.info[id] = this.getValue(); }; function tableColumns( table ) { var cols = 0, maxCols = 0; for ( var i = 0, row, rows = table.$.rows.length; i < rows; i++ ) { row = table.$.rows[ i ], cols = 0; for ( var j = 0, cell, cells = row.cells.length; j < cells; j++ ) { cell = row.cells[ j ]; cols += cell.colSpan; } cols > maxCols && ( maxCols = cols ); } return maxCols; } function tableDialog( editor, command ) { var makeElement = function( name ) { return new CKEDITOR.dom.element( name, editor.document ); }; var dialogadvtab = editor.plugins.dialogadvtab; return { title : editor.lang.table.title, minWidth : 310, minHeight : CKEDITOR.env.ie ? 310 : 280, onLoad : function() { var dialog = this; var styles = dialog.getContentElement( 'advanced', 'advStyles' ); if ( styles ) { styles.on( 'change', function( evt ) { // Synchronize width value. var width = this.getStyle( 'width', '' ), txtWidth = dialog.getContentElement( 'info', 'txtWidth' ); txtWidth && txtWidth.setValue( width, true ); // Synchronize height value. var height = this.getStyle( 'height', '' ), txtHeight = dialog.getContentElement( 'info', 'txtHeight' ); txtHeight && txtHeight.setValue( height, true ); }); } }, onShow : function() { // Detect if there's a selected table. var selection = editor.getSelection(), ranges = selection.getRanges(), selectedTable = null; var rowsInput = this.getContentElement( 'info', 'txtRows' ), colsInput = this.getContentElement( 'info', 'txtCols' ), widthInput = this.getContentElement( 'info', 'txtWidth' ), heightInput = this.getContentElement( 'info', 'txtHeight' ); if ( command == 'tableProperties' ) { if ( ( selectedTable = selection.getSelectedElement() ) ) selectedTable = selectedTable.getAscendant( 'table', true ); else if ( ranges.length > 0 ) { // Webkit could report the following range on cell selection (#4948): // <table><tr><td>[&nbsp;</td></tr></table>] if ( CKEDITOR.env.webkit ) ranges[ 0 ].shrink( CKEDITOR.NODE_ELEMENT ); var rangeRoot = ranges[0].getCommonAncestor( true ); selectedTable = rangeRoot.getAscendant( 'table', true ); } // Save a reference to the selected table, and push a new set of default values. this._.selectedElement = selectedTable; } // Enable or disable the row, cols, width fields. if ( selectedTable ) { this.setupContent( selectedTable ); rowsInput && rowsInput.disable(); colsInput && colsInput.disable(); } else { rowsInput && rowsInput.enable(); colsInput && colsInput.enable(); } // Call the onChange method for the widht and height fields so // they get reflected into the Advanced tab. widthInput && widthInput.onChange(); heightInput && heightInput.onChange(); }, onOk : function() { var selection = editor.getSelection(), bms = this._.selectedElement && selection.createBookmarks(); var table = this._.selectedElement || makeElement( 'table' ), me = this, data = {}; this.commitContent( data, table ); if ( data.info ) { var info = data.info; // Generate the rows and cols. if ( !this._.selectedElement ) { var tbody = table.append( makeElement( 'tbody' ) ), rows = parseInt( info.txtRows, 10 ) || 0, cols = parseInt( info.txtCols, 10 ) || 0; for ( var i = 0 ; i < rows ; i++ ) { var row = tbody.append( makeElement( 'tr' ) ); for ( var j = 0 ; j < cols ; j++ ) { var cell = row.append( makeElement( 'td' ) ); if ( !CKEDITOR.env.ie ) cell.append( makeElement( 'br' ) ); } } } // Modify the table headers. Depends on having rows and cols generated // correctly so it can't be done in commit functions. // Should we make a <thead>? var headers = info.selHeaders; if ( !table.$.tHead && ( headers == 'row' || headers == 'both' ) ) { var thead = new CKEDITOR.dom.element( table.$.createTHead() ); tbody = table.getElementsByTag( 'tbody' ).getItem( 0 ); var theRow = tbody.getElementsByTag( 'tr' ).getItem( 0 ); // Change TD to TH: for ( i = 0 ; i < theRow.getChildCount() ; i++ ) { var th = theRow.getChild( i ); // Skip bookmark nodes. (#6155) if ( th.type == CKEDITOR.NODE_ELEMENT && !th.data( 'cke-bookmark' ) ) { th.renameNode( 'th' ); th.setAttribute( 'scope', 'col' ); } } thead.append( theRow.remove() ); } if ( table.$.tHead !== null && !( headers == 'row' || headers == 'both' ) ) { // Move the row out of the THead and put it in the TBody: thead = new CKEDITOR.dom.element( table.$.tHead ); tbody = table.getElementsByTag( 'tbody' ).getItem( 0 ); var previousFirstRow = tbody.getFirst(); while ( thead.getChildCount() > 0 ) { theRow = thead.getFirst(); for ( i = 0; i < theRow.getChildCount() ; i++ ) { var newCell = theRow.getChild( i ); if ( newCell.type == CKEDITOR.NODE_ELEMENT ) { newCell.renameNode( 'td' ); newCell.removeAttribute( 'scope' ); } } theRow.insertBefore( previousFirstRow ); } thead.remove(); } // Should we make all first cells in a row TH? if ( !this.hasColumnHeaders && ( headers == 'col' || headers == 'both' ) ) { for ( row = 0 ; row < table.$.rows.length ; row++ ) { newCell = new CKEDITOR.dom.element( table.$.rows[ row ].cells[ 0 ] ); newCell.renameNode( 'th' ); newCell.setAttribute( 'scope', 'row' ); } } // Should we make all first TH-cells in a row make TD? If 'yes' we do it the other way round :-) if ( ( this.hasColumnHeaders ) && !( headers == 'col' || headers == 'both' ) ) { for ( i = 0 ; i < table.$.rows.length ; i++ ) { row = new CKEDITOR.dom.element( table.$.rows[i] ); if ( row.getParent().getName() == 'tbody' ) { newCell = new CKEDITOR.dom.element( row.$.cells[0] ); newCell.renameNode( 'td' ); newCell.removeAttribute( 'scope' ); } } } // Set the width and height. info.txtHeight ? table.setStyle( 'height', info.txtHeight ) : table.removeStyle( 'height' ); info.txtWidth ? table.setStyle( 'width', info.txtWidth ) : table.removeStyle( 'width' ); if ( !table.getAttribute( 'style' ) ) table.removeAttribute( 'style' ); } // Insert the table element if we're creating one. if ( !this._.selectedElement ) { editor.insertElement( table ); // Override the default cursor position after insertElement to place // cursor inside the first cell (#7959), IE needs a while. setTimeout( function() { var firstCell = new CKEDITOR.dom.element( table.$.rows[ 0 ].cells[ 0 ] ); var range = new CKEDITOR.dom.range( editor.document ); range.moveToPosition( firstCell, CKEDITOR.POSITION_AFTER_START ); range.select( 1 ); }, 0 ); } // Properly restore the selection, (#4822) but don't break // because of this, e.g. updated table caption. else try { selection.selectBookmarks( bms ); } catch( er ){} }, contents : [ { id : 'info', label : editor.lang.table.title, elements : [ { type : 'hbox', widths : [ null, null ], styles : [ 'vertical-align:top' ], children : [ { type : 'vbox', padding : 0, children : [ { type : 'text', id : 'txtRows', 'default' : 3, label : editor.lang.table.rows, required : true, controlStyle : 'width:5em', validate : function() { var pass = true, value = this.getValue(); pass = pass && CKEDITOR.dialog.validate.integer()( value ) && value > 0; if ( !pass ) { alert( editor.lang.table.invalidRows ); this.select(); } return pass; }, setup : function( selectedElement ) { this.setValue( selectedElement.$.rows.length ); }, commit : commitValue }, { type : 'text', id : 'txtCols', 'default' : 2, label : editor.lang.table.columns, required : true, controlStyle : 'width:5em', validate : function() { var pass = true, value = this.getValue(); pass = pass && CKEDITOR.dialog.validate.integer()( value ) && value > 0; if ( !pass ) { alert( editor.lang.table.invalidCols ); this.select(); } return pass; }, setup : function( selectedTable ) { this.setValue( tableColumns( selectedTable ) ); }, commit : commitValue }, { type : 'html', html : '&nbsp;' }, { type : 'select', id : 'selHeaders', 'default' : '', label : editor.lang.table.headers, items : [ [ editor.lang.table.headersNone, '' ], [ editor.lang.table.headersRow, 'row' ], [ editor.lang.table.headersColumn, 'col' ], [ editor.lang.table.headersBoth, 'both' ] ], setup : function( selectedTable ) { // Fill in the headers field. var dialog = this.getDialog(); dialog.hasColumnHeaders = true; // Check if all the first cells in every row are TH for ( var row = 0 ; row < selectedTable.$.rows.length ; row++ ) { // If just one cell isn't a TH then it isn't a header column var headCell = selectedTable.$.rows[row].cells[0]; if ( headCell && headCell.nodeName.toLowerCase() != 'th' ) { dialog.hasColumnHeaders = false; break; } } // Check if the table contains <thead>. if ( ( selectedTable.$.tHead !== null) ) this.setValue( dialog.hasColumnHeaders ? 'both' : 'row' ); else this.setValue( dialog.hasColumnHeaders ? 'col' : '' ); }, commit : commitValue }, { type : 'text', id : 'txtBorder', 'default' : 1, label : editor.lang.table.border, controlStyle : 'width:3em', validate : CKEDITOR.dialog.validate['number']( editor.lang.table.invalidBorder ), setup : function( selectedTable ) { this.setValue( selectedTable.getAttribute( 'border' ) || '' ); }, commit : function( data, selectedTable ) { if ( this.getValue() ) selectedTable.setAttribute( 'border', this.getValue() ); else selectedTable.removeAttribute( 'border' ); } }, { id : 'cmbAlign', type : 'select', 'default' : '', label : editor.lang.common.align, items : [ [ editor.lang.common.notSet , ''], [ editor.lang.common.alignLeft , 'left'], [ editor.lang.common.alignCenter , 'center'], [ editor.lang.common.alignRight , 'right'] ], setup : function( selectedTable ) { this.setValue( selectedTable.getAttribute( 'align' ) || '' ); }, commit : function( data, selectedTable ) { if ( this.getValue() ) selectedTable.setAttribute( 'align', this.getValue() ); else selectedTable.removeAttribute( 'align' ); } } ] }, { type : 'vbox', padding : 0, children : [ { type : 'hbox', widths : [ '5em' ], children : [ { type : 'text', id : 'txtWidth', controlStyle : 'width:5em', label : editor.lang.common.width, title : editor.lang.common.cssLengthTooltip, 'default' : 500, getValue : defaultToPixel, validate : CKEDITOR.dialog.validate.cssLength( editor.lang.common.invalidCssLength.replace( '%1', editor.lang.common.width ) ), onChange : function() { var styles = this.getDialog().getContentElement( 'advanced', 'advStyles' ); styles && styles.updateStyle( 'width', this.getValue() ); }, setup : function( selectedTable ) { var val = selectedTable.getStyle( 'width' ); val && this.setValue( val ); }, commit : commitValue } ] }, { type : 'hbox', widths : [ '5em' ], children : [ { type : 'text', id : 'txtHeight', controlStyle : 'width:5em', label : editor.lang.common.height, title : editor.lang.common.cssLengthTooltip, 'default' : '', getValue : defaultToPixel, validate : CKEDITOR.dialog.validate.cssLength( editor.lang.common.invalidCssLength.replace( '%1', editor.lang.common.height ) ), onChange : function() { var styles = this.getDialog().getContentElement( 'advanced', 'advStyles' ); styles && styles.updateStyle( 'height', this.getValue() ); }, setup : function( selectedTable ) { var val = selectedTable.getStyle( 'width' ); val && this.setValue( val ); }, commit : commitValue } ] }, { type : 'html', html : '&nbsp;' }, { type : 'text', id : 'txtCellSpace', controlStyle : 'width:3em', label : editor.lang.table.cellSpace, 'default' : 1, validate : CKEDITOR.dialog.validate.number( editor.lang.table.invalidCellSpacing ), setup : function( selectedTable ) { this.setValue( selectedTable.getAttribute( 'cellSpacing' ) || '' ); }, commit : function( data, selectedTable ) { if ( this.getValue() ) selectedTable.setAttribute( 'cellSpacing', this.getValue() ); else selectedTable.removeAttribute( 'cellSpacing' ); } }, { type : 'text', id : 'txtCellPad', controlStyle : 'width:3em', label : editor.lang.table.cellPad, 'default' : 1, validate : CKEDITOR.dialog.validate.number( editor.lang.table.invalidCellPadding ), setup : function( selectedTable ) { this.setValue( selectedTable.getAttribute( 'cellPadding' ) || '' ); }, commit : function( data, selectedTable ) { if ( this.getValue() ) selectedTable.setAttribute( 'cellPadding', this.getValue() ); else selectedTable.removeAttribute( 'cellPadding' ); } } ] } ] }, { type : 'html', align : 'right', html : '' }, { type : 'vbox', padding : 0, children : [ { type : 'text', id : 'txtCaption', label : editor.lang.table.caption, setup : function( selectedTable ) { this.enable(); var nodeList = selectedTable.getElementsByTag( 'caption' ); if ( nodeList.count() > 0 ) { var caption = nodeList.getItem( 0 ); var firstElementChild = caption.getFirst( CKEDITOR.dom.walker.nodeType( CKEDITOR.NODE_ELEMENT ) ); if ( firstElementChild && !firstElementChild.equals( caption.getBogus() ) ) { this.disable(); this.setValue( caption.getText() ); return; } caption = CKEDITOR.tools.trim( caption.getText() ); this.setValue( caption ); } }, commit : function( data, table ) { if ( !this.isEnabled() ) return; var caption = this.getValue(), captionElement = table.getElementsByTag( 'caption' ); if ( caption ) { if ( captionElement.count() > 0 ) { captionElement = captionElement.getItem( 0 ); captionElement.setHtml( '' ); } else { captionElement = new CKEDITOR.dom.element( 'caption', editor.document ); if ( table.getChildCount() ) captionElement.insertBefore( table.getFirst() ); else captionElement.appendTo( table ); } captionElement.append( new CKEDITOR.dom.text( caption, editor.document ) ); } else if ( captionElement.count() > 0 ) { for ( var i = captionElement.count() - 1 ; i >= 0 ; i-- ) captionElement.getItem( i ).remove(); } } }, { type : 'text', id : 'txtSummary', label : editor.lang.table.summary, setup : function( selectedTable ) { this.setValue( selectedTable.getAttribute( 'summary' ) || '' ); }, commit : function( data, selectedTable ) { if ( this.getValue() ) selectedTable.setAttribute( 'summary', this.getValue() ); else selectedTable.removeAttribute( 'summary' ); } } ] } ] }, dialogadvtab && dialogadvtab.createAdvancedTab( editor ) ] }; } CKEDITOR.dialog.add( 'table', function( editor ) { return tableDialog( editor, 'table' ); } ); CKEDITOR.dialog.add( 'tableProperties', function( editor ) { return tableDialog( editor, 'tableProperties' ); } ); })();
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @file Horizontal Page Break */ // Register a plugin named "newpage". CKEDITOR.plugins.add( 'newpage', { init : function( editor ) { editor.addCommand( 'newpage', { modes : { wysiwyg:1, source:1 }, exec : function( editor ) { var command = this; editor.setData( editor.config.newpage_html || '', function() { // Save the undo snapshot after all document changes are affected. (#4889) setTimeout( function () { editor.fire( 'afterCommandExec', { name: command.name, command: command } ); editor.selectionChange(); }, 200 ); } ); editor.focus(); }, async : true }); editor.ui.addButton( 'NewPage', { label : editor.lang.newPage, command : 'newpage' }); } }); /** * The HTML to load in the editor when the "new page" command is executed. * @name CKEDITOR.config.newpage_html * @type String * @default '' * @example * config.newpage_html = '&lt;p&gt;Type your text here.&lt;/p&gt;'; */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.add( 'format', { requires : [ 'richcombo', 'styles' ], init : function( editor ) { var config = editor.config, lang = editor.lang.format; // Gets the list of tags from the settings. var tags = config.format_tags.split( ';' ); // Create style objects for all defined styles. var styles = {}; for ( var i = 0 ; i < tags.length ; i++ ) { var tag = tags[ i ]; styles[ tag ] = new CKEDITOR.style( config[ 'format_' + tag ] ); styles[ tag ]._.enterMode = editor.config.enterMode; } editor.ui.addRichCombo( 'Format', { label : lang.label, title : lang.panelTitle, className : 'cke_format', panel : { css : editor.skin.editor.css.concat( config.contentsCss ), multiSelect : false, attributes : { 'aria-label' : lang.panelTitle } }, init : function() { this.startGroup( lang.panelTitle ); for ( var tag in styles ) { var label = lang[ 'tag_' + tag ]; // Add the tag entry to the panel list. this.add( tag, styles[tag].buildPreview( label ), label ); } }, onClick : function( value ) { editor.focus(); editor.fire( 'saveSnapshot' ); var style = styles[ value ], elementPath = new CKEDITOR.dom.elementPath( editor.getSelection().getStartElement() ); style[ style.checkActive( elementPath ) ? 'remove' : 'apply' ]( editor.document ); // Save the undo snapshot after all changes are affected. (#4899) setTimeout( function() { editor.fire( 'saveSnapshot' ); }, 0 ); }, onRender : function() { editor.on( 'selectionChange', function( ev ) { var currentTag = this.getValue(); var elementPath = ev.data.path; for ( var tag in styles ) { if ( styles[ tag ].checkActive( elementPath ) ) { if ( tag != currentTag ) this.setValue( tag, editor.lang.format[ 'tag_' + tag ] ); return; } } // If no styles match, just empty it. this.setValue( '' ); }, this); } }); } }); /** * A list of semi colon separated style names (by default tags) representing * the style definition for each entry to be displayed in the Format combo in * the toolbar. Each entry must have its relative definition configuration in a * setting named "format_(tagName)". For example, the "p" entry has its * definition taken from config.format_p. * @type String * @default 'p;h1;h2;h3;h4;h5;h6;pre;address;div' * @example * config.format_tags = 'p;h2;h3;pre' */ CKEDITOR.config.format_tags = 'p;h1;h2;h3;h4;h5;h6;pre;address;div'; /** * The style definition to be used to apply the "Normal" format. * @type Object * @default { element : 'p' } * @example * config.format_p = { element : 'p', attributes : { 'class' : 'normalPara' } }; */ CKEDITOR.config.format_p = { element : 'p' }; /** * The style definition to be used to apply the "Normal (DIV)" format. * @type Object * @default { element : 'div' } * @example * config.format_div = { element : 'div', attributes : { 'class' : 'normalDiv' } }; */ CKEDITOR.config.format_div = { element : 'div' }; /** * The style definition to be used to apply the "Formatted" format. * @type Object * @default { element : 'pre' } * @example * config.format_pre = { element : 'pre', attributes : { 'class' : 'code' } }; */ CKEDITOR.config.format_pre = { element : 'pre' }; /** * The style definition to be used to apply the "Address" format. * @type Object * @default { element : 'address' } * @example * config.format_address = { element : 'address', attributes : { 'class' : 'styledAddress' } }; */ CKEDITOR.config.format_address = { element : 'address' }; /** * The style definition to be used to apply the "Heading 1" format. * @type Object * @default { element : 'h1' } * @example * config.format_h1 = { element : 'h1', attributes : { 'class' : 'contentTitle1' } }; */ CKEDITOR.config.format_h1 = { element : 'h1' }; /** * The style definition to be used to apply the "Heading 1" format. * @type Object * @default { element : 'h2' } * @example * config.format_h2 = { element : 'h2', attributes : { 'class' : 'contentTitle2' } }; */ CKEDITOR.config.format_h2 = { element : 'h2' }; /** * The style definition to be used to apply the "Heading 1" format. * @type Object * @default { element : 'h3' } * @example * config.format_h3 = { element : 'h3', attributes : { 'class' : 'contentTitle3' } }; */ CKEDITOR.config.format_h3 = { element : 'h3' }; /** * The style definition to be used to apply the "Heading 1" format. * @type Object * @default { element : 'h4' } * @example * config.format_h4 = { element : 'h4', attributes : { 'class' : 'contentTitle4' } }; */ CKEDITOR.config.format_h4 = { element : 'h4' }; /** * The style definition to be used to apply the "Heading 1" format. * @type Object * @default { element : 'h5' } * @example * config.format_h5 = { element : 'h5', attributes : { 'class' : 'contentTitle5' } }; */ CKEDITOR.config.format_h5 = { element : 'h5' }; /** * The style definition to be used to apply the "Heading 1" format. * @type Object * @default { element : 'h6' } * @example * config.format_h6 = { element : 'h6', attributes : { 'class' : 'contentTitle6' } }; */ CKEDITOR.config.format_h6 = { element : 'h6' };
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @file Special Character plugin */ CKEDITOR.plugins.add( 'specialchar', { // List of available localizations. availableLangs : { en:1 }, init : function( editor ) { var pluginName = 'specialchar', plugin = this; // Register the dialog. CKEDITOR.dialog.add( pluginName, this.path + 'dialogs/specialchar.js' ); editor.addCommand( pluginName, { exec : function() { var langCode = editor.langCode; langCode = plugin.availableLangs[ langCode ] ? langCode : 'en'; CKEDITOR.scriptLoader.load( CKEDITOR.getUrl( plugin.path + 'lang/' + langCode + '.js' ), function() { CKEDITOR.tools.extend( editor.lang.specialChar, plugin.langEntries[ langCode ] ); editor.openDialog( pluginName ); }); }, modes : { wysiwyg:1 }, canUndo : false }); // Register the toolbar button. editor.ui.addButton( 'SpecialChar', { label : editor.lang.specialChar.toolbar, command : pluginName }); } } ); /** * The list of special characters visible in the Special Character dialog window. * @type Array * @example * config.specialChars = [ '&quot;', '&rsquo;', [ '&custom;', 'Custom label' ] ]; * config.specialChars = config.specialChars.concat( [ '&quot;', [ '&rsquo;', 'Custom label' ] ] ); */ CKEDITOR.config.specialChars = [ '!','&quot;','#','$','%','&amp;',"'",'(',')','*','+','-','.','/', '0','1','2','3','4','5','6','7','8','9',':',';', '&lt;','=','&gt;','?','@', 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', 'P','Q','R','S','T','U','V','W','X','Y','Z', '[',']','^','_','`', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p', 'q','r','s','t','u','v','w','x','y','z', '{','|','}','~', "&euro;", "&lsquo;", "&rsquo;", "&ldquo;", "&rdquo;", "&ndash;", "&mdash;", "&iexcl;", "&cent;", "&pound;", "&curren;", "&yen;", "&brvbar;", "&sect;", "&uml;", "&copy;", "&ordf;", "&laquo;", "&not;", "&reg;", "&macr;", "&deg;", "&sup2;", "&sup3;", "&acute;", "&micro;", "&para;", "&middot;", "&cedil;", "&sup1;", "&ordm;", "&raquo;", "&frac14;", "&frac12;", "&frac34;", "&iquest;", "&Agrave;", "&Aacute;", "&Acirc;", "&Atilde;", "&Auml;", "&Aring;", "&AElig;", "&Ccedil;", "&Egrave;", "&Eacute;", "&Ecirc;", "&Euml;", "&Igrave;", "&Iacute;", "&Icirc;", "&Iuml;", "&ETH;", "&Ntilde;", "&Ograve;", "&Oacute;", "&Ocirc;", "&Otilde;", "&Ouml;", "&times;", "&Oslash;", "&Ugrave;", "&Uacute;", "&Ucirc;", "&Uuml;", "&Yacute;", "&THORN;", "&szlig;", "&agrave;", "&aacute;", "&acirc;", "&atilde;", "&auml;", "&aring;", "&aelig;", "&ccedil;", "&egrave;", "&eacute;", "&ecirc;", "&euml;", "&igrave;", "&iacute;", "&icirc;", "&iuml;", "&eth;", "&ntilde;", "&ograve;", "&oacute;", "&ocirc;", "&otilde;", "&ouml;", "&divide;", "&oslash;", "&ugrave;", "&uacute;", "&ucirc;", "&uuml;", "&yacute;", "&thorn;", "&yuml;", "&OElig;", "&oelig;", "&#372;", "&#374", "&#373", "&#375;", "&sbquo;", "&#8219;", "&bdquo;", "&hellip;", "&trade;", "&#9658;", "&bull;", "&rarr;", "&rArr;", "&hArr;", "&diams;", "&asymp;" ];
JavaScript
 CKEDITOR.plugins.setLang( 'specialchar', 'en', { euro: "Euro sign", lsquo: "Left single quotation mark", rsquo: "Right single quotation mark", ldquo: "Left double quotation mark", rdquo: "Right double quotation mark", ndash: "En dash", mdash: "Em dash", iexcl: "Inverted exclamation mark", cent: "Cent sign", pound: "Pound sign", curren: "Currency sign", yen: "Yen sign", brvbar: "Broken bar", sect: "Section sign", uml: "Diaeresis", copy: "Copyright sign", ordf: "Feminine ordinal indicator", laquo: "Left-pointing double angle quotation mark", not: "Not sign", reg: "Registered sign", macr: "Macron", deg: "Degree sign", sup2: "Superscript two", sup3: "Superscript three", acute: "Acute accent", micro: "Micro sign", para: "Pilcrow sign", middot: "Middle dot", cedil: "Cedilla", sup1: "Superscript one", ordm: "Masculine ordinal indicator", raquo: "Right-pointing double angle quotation mark", frac14: "Vulgar fraction one quarter", frac12: "Vulgar fraction one half", frac34: "Vulgar fraction three quarters", iquest: "Inverted question mark", Agrave: "Latin capital letter A with grave accent", Aacute: "Latin capital letter A with acute accent", Acirc: "Latin capital letter A with circumflex", Atilde: "Latin capital letter A with tilde", Auml: "Latin capital letter A with diaeresis", Aring: "Latin capital letter A with ring above", AElig: "Latin Capital letter Æ", Ccedil: "Latin capital letter C with cedilla", Egrave: "Latin capital letter E with grave accent", Eacute: "Latin capital letter E with acute accent", Ecirc: "Latin capital letter E with circumflex", Euml: "Latin capital letter E with diaeresis", Igrave: "Latin capital letter I with grave accent", Iacute: "Latin capital letter I with acute accent", Icirc: "Latin capital letter I with circumflex", Iuml: "Latin capital letter I with diaeresis", ETH: "Latin capital letter Eth", Ntilde: "Latin capital letter N with tilde", Ograve: "Latin capital letter O with grave accent", Oacute: "Latin capital letter O with acute accent", Ocirc: "Latin capital letter O with circumflex", Otilde: "Latin capital letter O with tilde", Ouml: "Latin capital letter O with diaeresis", times: "Multiplication sign", Oslash: "Latin capital letter O with stroke", Ugrave: "Latin capital letter U with grave accent", Uacute: "Latin capital letter U with acute accent", Ucirc: "Latin capital letter U with circumflex", Uuml: "Latin capital letter U with diaeresis", Yacute: "Latin capital letter Y with acute accent", THORN: "Latin capital letter Thorn", szlig: "Latin small letter sharp s", agrave: "Latin small letter a with grave accent", aacute: "Latin small letter a with acute accent", acirc: "Latin small letter a with circumflex", atilde: "Latin small letter a with tilde", auml: "Latin small letter a with diaeresis", aring: "Latin small letter a with ring above", aelig: "Latin small letter æ", ccedil: "Latin small letter c with cedilla", egrave: "Latin small letter e with grave accent", eacute: "Latin small letter e with acute accent", ecirc: "Latin small letter e with circumflex", euml: "Latin small letter e with diaeresis", igrave: "Latin small letter i with grave accent", iacute: "Latin small letter i with acute accent", icirc: "Latin small letter i with circumflex", iuml: "Latin small letter i with diaeresis", eth: "Latin small letter eth", ntilde: "Latin small letter n with tilde", ograve: "Latin small letter o with grave accent", oacute: "Latin small letter o with acute accent", ocirc: "Latin small letter o with circumflex", otilde: "Latin small letter o with tilde", ouml: "Latin small letter o with diaeresis", divide: "Division sign", oslash: "Latin small letter o with stroke", ugrave: "Latin small letter u with grave accent", uacute: "Latin small letter u with acute accent", ucirc: "Latin small letter u with circumflex", uuml: "Latin small letter u with diaeresis", yacute: "Latin small letter y with acute accent", thorn: "Latin small letter thorn", yuml: "Latin small letter y with diaeresis", OElig: "Latin capital ligature OE", oelig: "Latin small ligature oe", '372': "Latin capital letter W with circumflex", '374': "Latin capital letter Y with circumflex", '373': "Latin small letter w with circumflex", '375': "Latin small letter y with circumflex", sbquo: "Single low-9 quotation mark", '8219': "Single high-reversed-9 quotation mark", bdquo: "Double low-9 quotation mark", hellip: "Horizontal ellipsis", trade: "Trade mark sign", '9658': "Black right-pointing pointer", bull: "Bullet", rarr: "Rightwards arrow", rArr: "Rightwards double arrow", hArr: "Left right double arrow", diams: "Black diamond suit", asymp: "Almost equal to" });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'specialchar', function( editor ) { /** * Simulate "this" of a dialog for non-dialog events. * @type {CKEDITOR.dialog} */ var dialog, lang = editor.lang.specialChar; var onChoice = function( evt ) { var target, value; if ( evt.data ) target = evt.data.getTarget(); else target = new CKEDITOR.dom.element( evt ); if ( target.getName() == 'a' && ( value = target.getChild( 0 ).getHtml() ) ) { target.removeClass( "cke_light_background" ); dialog.hide(); // We must use "insertText" here to keep text styled. var span = editor.document.createElement( 'span' ); span.setHtml( value ); editor.insertText( span.getText() ); } }; var onClick = CKEDITOR.tools.addFunction( onChoice ); var focusedNode; var onFocus = function( evt, target ) { var value; target = target || evt.data.getTarget(); if ( target.getName() == 'span' ) target = target.getParent(); if ( target.getName() == 'a' && ( value = target.getChild( 0 ).getHtml() ) ) { // Trigger blur manually if there is focused node. if ( focusedNode ) onBlur( null, focusedNode ); var htmlPreview = dialog.getContentElement( 'info', 'htmlPreview' ).getElement(); dialog.getContentElement( 'info', 'charPreview' ).getElement().setHtml( value ); htmlPreview.setHtml( CKEDITOR.tools.htmlEncode( value ) ); target.getParent().addClass( "cke_light_background" ); // Memorize focused node. focusedNode = target; } }; var onBlur = function( evt, target ) { target = target || evt.data.getTarget(); if ( target.getName() == 'span' ) target = target.getParent(); if ( target.getName() == 'a' ) { dialog.getContentElement( 'info', 'charPreview' ).getElement().setHtml( '&nbsp;' ); dialog.getContentElement( 'info', 'htmlPreview' ).getElement().setHtml( '&nbsp;' ); target.getParent().removeClass( "cke_light_background" ); focusedNode = undefined; } }; var onKeydown = CKEDITOR.tools.addFunction( function( ev ) { ev = new CKEDITOR.dom.event( ev ); // Get an Anchor element. var element = ev.getTarget(); var relative, nodeToMove; var keystroke = ev.getKeystroke(), rtl = editor.lang.dir == 'rtl'; switch ( keystroke ) { // UP-ARROW case 38 : // relative is TR if ( ( relative = element.getParent().getParent().getPrevious() ) ) { nodeToMove = relative.getChild( [element.getParent().getIndex(), 0] ); nodeToMove.focus(); onBlur( null, element ); onFocus( null, nodeToMove ); } ev.preventDefault(); break; // DOWN-ARROW case 40 : // relative is TR if ( ( relative = element.getParent().getParent().getNext() ) ) { nodeToMove = relative.getChild( [ element.getParent().getIndex(), 0 ] ); if ( nodeToMove && nodeToMove.type == 1 ) { nodeToMove.focus(); onBlur( null, element ); onFocus( null, nodeToMove ); } } ev.preventDefault(); break; // SPACE // ENTER is already handled as onClick case 32 : onChoice( { data: ev } ); ev.preventDefault(); break; // RIGHT-ARROW case rtl ? 37 : 39 : // TAB case 9 : // relative is TD if ( ( relative = element.getParent().getNext() ) ) { nodeToMove = relative.getChild( 0 ); if ( nodeToMove.type == 1 ) { nodeToMove.focus(); onBlur( null, element ); onFocus( null, nodeToMove ); ev.preventDefault( true ); } else onBlur( null, element ); } // relative is TR else if ( ( relative = element.getParent().getParent().getNext() ) ) { nodeToMove = relative.getChild( [ 0, 0 ] ); if ( nodeToMove && nodeToMove.type == 1 ) { nodeToMove.focus(); onBlur( null, element ); onFocus( null, nodeToMove ); ev.preventDefault( true ); } else onBlur( null, element ); } break; // LEFT-ARROW case rtl ? 39 : 37 : // SHIFT + TAB case CKEDITOR.SHIFT + 9 : // relative is TD if ( ( relative = element.getParent().getPrevious() ) ) { nodeToMove = relative.getChild( 0 ); nodeToMove.focus(); onBlur( null, element ); onFocus( null, nodeToMove ); ev.preventDefault( true ); } // relative is TR else if ( ( relative = element.getParent().getParent().getPrevious() ) ) { nodeToMove = relative.getLast().getChild( 0 ); nodeToMove.focus(); onBlur( null, element ); onFocus( null, nodeToMove ); ev.preventDefault( true ); } else onBlur( null, element ); break; default : // Do not stop not handled events. return; } }); return { title : lang.title, minWidth : 430, minHeight : 280, buttons : [ CKEDITOR.dialog.cancelButton ], charColumns : 17, onLoad : function() { var columns = this.definition.charColumns, extraChars = editor.config.extraSpecialChars, chars = editor.config.specialChars; var charsTableLabel = CKEDITOR.tools.getNextId() + '_specialchar_table_label'; var html = [ '<table role="listbox" aria-labelledby="' + charsTableLabel + '"' + ' style="width: 320px; height: 100%; border-collapse: separate;"' + ' align="center" cellspacing="2" cellpadding="2" border="0">' ]; var i = 0, size = chars.length, character, charDesc; while ( i < size ) { html.push( '<tr>' ) ; for ( var j = 0 ; j < columns ; j++, i++ ) { if ( ( character = chars[ i ] ) ) { charDesc = ''; if ( character instanceof Array ) { charDesc = character[ 1 ]; character = character[ 0 ]; } else { var _tmpName = character.replace( '&', '' ).replace( ';', '' ).replace( '#', '' ); // Use character in case description unavailable. charDesc = lang[ _tmpName ] || character; } var charLabelId = 'cke_specialchar_label_' + i + '_' + CKEDITOR.tools.getNextNumber(); html.push( '<td class="cke_dark_background" style="cursor: default" role="presentation">' + '<a href="javascript: void(0);" role="option"' + ' aria-posinset="' + ( i +1 ) + '"', ' aria-setsize="' + size + '"', ' aria-labelledby="' + charLabelId + '"', ' style="cursor: inherit; display: block; height: 1.25em; margin-top: 0.25em; text-align: center;" title="', CKEDITOR.tools.htmlEncode( charDesc ), '"' + ' onkeydown="CKEDITOR.tools.callFunction( ' + onKeydown + ', event, this )"' + ' onclick="CKEDITOR.tools.callFunction(' + onClick + ', this); return false;"' + ' tabindex="-1">' + '<span style="margin: 0 auto;cursor: inherit">' + character + '</span>' + '<span class="cke_voice_label" id="' + charLabelId + '">' + charDesc + '</span></a>'); } else html.push( '<td class="cke_dark_background">&nbsp;' ); html.push( '</td>' ); } html.push( '</tr>' ); } html.push( '</tbody></table>', '<span id="' + charsTableLabel + '" class="cke_voice_label">' + lang.options +'</span>' ); this.getContentElement( 'info', 'charContainer' ).getElement().setHtml( html.join( '' ) ); }, contents : [ { id : 'info', label : editor.lang.common.generalTab, title : editor.lang.common.generalTab, padding : 0, align : 'top', elements : [ { type : 'hbox', align : 'top', widths : [ '320px', '90px' ], children : [ { type : 'html', id : 'charContainer', html : '', onMouseover : onFocus, onMouseout : onBlur, focus : function() { var firstChar = this.getElement().getElementsByTag( 'a' ).getItem( 0 ); setTimeout( function() { firstChar.focus(); onFocus( null, firstChar ); }, 0 ); }, onShow : function() { var firstChar = this.getElement().getChild( [ 0, 0, 0, 0, 0 ] ); setTimeout( function() { firstChar.focus(); onFocus( null, firstChar ); }, 0 ); }, onLoad : function( event ) { dialog = event.sender; } }, { type : 'hbox', align : 'top', widths : [ '100%' ], children : [ { type : 'vbox', align : 'top', children : [ { type : 'html', html : '<div></div>' }, { type : 'html', id : 'charPreview', className : 'cke_dark_background', style : 'border:1px solid #eeeeee;font-size:28px;height:40px;width:70px;padding-top:9px;font-family:\'Microsoft Sans Serif\',Arial,Helvetica,Verdana;text-align:center;', html : '<div>&nbsp;</div>' }, { type : 'html', id : 'htmlPreview', className : 'cke_dark_background', style : 'border:1px solid #eeeeee;font-size:14px;height:20px;width:70px;padding-top:2px;font-family:\'Microsoft Sans Serif\',Arial,Helvetica,Verdana;text-align:center;', html : '<div>&nbsp;</div>' } ] } ] } ] } ] } ] }; } );
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @file Spell checker */ // Register a plugin named "wsc". CKEDITOR.plugins.add( 'wsc', { requires : [ 'dialog' ], init : function( editor ) { var commandName = 'checkspell'; var command = editor.addCommand( commandName, new CKEDITOR.dialogCommand( commandName ) ); // SpellChecker doesn't work in Opera and with custom domain command.modes = { wysiwyg : ( !CKEDITOR.env.opera && !CKEDITOR.env.air && document.domain == window.location.hostname ) }; editor.ui.addButton( 'SpellChecker', { label : editor.lang.spellCheck.toolbar, command : commandName }); CKEDITOR.dialog.add( commandName, this.path + 'dialogs/wsc.js' ); } }); CKEDITOR.config.wsc_customerId = CKEDITOR.config.wsc_customerId || '1:ua3xw1-2XyGJ3-GWruD3-6OFNT1-oXcuB1-nR6Bp4-hgQHc-EcYng3-sdRXG3-NOfFk' ; CKEDITOR.config.wsc_customLoaderScript = CKEDITOR.config.wsc_customLoaderScript || null;
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'checkspell', function( editor ) { var number = CKEDITOR.tools.getNextNumber(), iframeId = 'cke_frame_' + number, textareaId = 'cke_data_' + number, errorBoxId = 'cke_error_' + number, interval, protocol = document.location.protocol || 'http:', errorMsg = editor.lang.spellCheck.notAvailable; var pasteArea = '<textarea'+ ' style="display: none"' + ' id="' + textareaId + '"' + ' rows="10"' + ' cols="40">' + ' </textarea><div' + ' id="' + errorBoxId + '"' + ' style="display:none;color:red;font-size:16px;font-weight:bold;padding-top:160px;text-align:center;z-index:11;">' + '</div><iframe' + ' src=""' + ' style="width:100%;background-color:#f1f1e3;"' + ' frameborder="0"' + ' name="' + iframeId + '"' + ' id="' + iframeId + '"' + ' allowtransparency="1">' + '</iframe>'; var wscCoreUrl = editor.config.wsc_customLoaderScript || ( protocol + '//loader.webspellchecker.net/sproxy_fck/sproxy.php' + '?plugin=fck2' + '&customerid=' + editor.config.wsc_customerId + '&cmd=script&doc=wsc&schema=22' ); if ( editor.config.wsc_customLoaderScript ) errorMsg += '<p style="color:#000;font-size:11px;font-weight: normal;text-align:center;padding-top:10px">' + editor.lang.spellCheck.errorLoading.replace( /%s/g, editor.config.wsc_customLoaderScript ) + '</p>'; function burnSpelling( dialog, errorMsg ) { var i = 0; return function () { if ( typeof( window.doSpell ) == 'function' ) { //Call from window.setInteval expected at once. if ( typeof( interval ) != 'undefined' ) window.clearInterval( interval ); initAndSpell( dialog ); } else if ( i++ == 180 ) // Timeout: 180 * 250ms = 45s. window._cancelOnError( errorMsg ); }; } window._cancelOnError = function( m ) { if ( typeof( window.WSC_Error ) == 'undefined' ) { CKEDITOR.document.getById( iframeId ).setStyle( 'display', 'none' ); var errorBox = CKEDITOR.document.getById( errorBoxId ); errorBox.setStyle( 'display', 'block' ); errorBox.setHtml( m || editor.lang.spellCheck.notAvailable ); } }; function initAndSpell( dialog ) { var LangComparer = new window._SP_FCK_LangCompare(), // Language abbr standarts comparer. pluginPath = CKEDITOR.getUrl( editor.plugins.wsc.path + 'dialogs/' ), // Service paths corecting/preparing. framesetPath = pluginPath + 'tmpFrameset.html'; // global var is used in FCK specific core // change on equal var used in fckplugin.js window.gFCKPluginName = 'wsc'; LangComparer.setDefaulLangCode( editor.config.defaultLanguage ); window.doSpell({ ctrl : textareaId, lang : editor.config.wsc_lang || LangComparer.getSPLangCode(editor.langCode ), intLang: editor.config.wsc_uiLang || LangComparer.getSPLangCode(editor.langCode ), winType : iframeId, // If not defined app will run on winpopup. // Callback binding section. onCancel : function() { dialog.hide(); }, onFinish : function( dT ) { editor.focus(); dialog.getParentEditor().setData( dT.value ); dialog.hide(); }, // Some manipulations with client static pages. staticFrame : framesetPath, framesetPath : framesetPath, iframePath : pluginPath + 'ciframe.html', // Styles defining. schemaURI : pluginPath + 'wsc.css', userDictionaryName: editor.config.wsc_userDictionaryName, customDictionaryName: editor.config.wsc_customDictionaryIds && editor.config.wsc_customDictionaryIds.split(","), domainName: editor.config.wsc_domainName }); // Hide user message console (if application was loaded more then after timeout). CKEDITOR.document.getById( errorBoxId ).setStyle( 'display', 'none' ); CKEDITOR.document.getById( iframeId ).setStyle( 'display', 'block' ); } return { title : editor.config.wsc_dialogTitle || editor.lang.spellCheck.title, minWidth : 485, minHeight : 380, buttons : [ CKEDITOR.dialog.cancelButton ], onShow : function() { var contentArea = this.getContentElement( 'general', 'content' ).getElement(); contentArea.setHtml( pasteArea ); contentArea.getChild( 2 ).setStyle( 'height', this._.contentSize.height + 'px' ); if ( typeof( window.doSpell ) != 'function' ) { // Load script. CKEDITOR.document.getHead().append( CKEDITOR.document.createElement( 'script', { attributes : { type : 'text/javascript', src : wscCoreUrl } }) ); } var sData = editor.getData(); // Get the data to be checked. CKEDITOR.document.getById( textareaId ).setValue( sData ); interval = window.setInterval( burnSpelling( this, errorMsg ), 250 ); }, onHide : function() { window.ooo = undefined; window.int_framsetLoaded = undefined; window.framesetLoaded = undefined; window.is_window_opened = false; }, contents : [ { id : 'general', label : editor.config.wsc_dialogTitle || editor.lang.spellCheck.title, padding : 0, elements : [ { type : 'html', id : 'content', html : '' } ] } ] }; }); // Expand the spell-check frame when dialog resized. (#6829) CKEDITOR.dialog.on( 'resize', function( evt ) { var data = evt.data, dialog = data.dialog; if ( dialog._.name == 'checkspell' ) { var content = dialog.getContentElement( 'general', 'content' ).getElement(), iframe = content && content.getChild( 2 ); iframe && iframe.setSize( 'height', data.height ); iframe && iframe.setSize( 'width', data.width ); } });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview The "filebrowser" plugin that adds support for file uploads and * browsing. * * When a file is uploaded or selected inside the file browser, its URL is * inserted automatically into a field defined in the <code>filebrowser</code> * attribute. In order to specify a field that should be updated, pass the tab ID and * the element ID, separated with a colon.<br /><br /> * * <strong>Example 1: (Browse)</strong> * * <pre> * { * type : 'button', * id : 'browse', * filebrowser : 'tabId:elementId', * label : editor.lang.common.browseServer * } * </pre> * * If you set the <code>filebrowser</code> attribute for an element other than * the <code>fileButton</code>, the <code>Browse</code> action will be triggered.<br /><br /> * * <strong>Example 2: (Quick Upload)</strong> * * <pre> * { * type : 'fileButton', * id : 'uploadButton', * filebrowser : 'tabId:elementId', * label : editor.lang.common.uploadSubmit, * 'for' : [ 'upload', 'upload' ] * } * </pre> * * If you set the <code>filebrowser</code> attribute for a <code>fileButton</code> * element, the <code>QuickUpload</code> action will be executed.<br /><br /> * * The filebrowser plugin also supports more advanced configuration performed through * a JavaScript object. * * The following settings are supported: * * <ul> * <li><code>action</code> &ndash; <code>Browse</code> or <code>QuickUpload</code>.</li> * <li><code>target</code> &ndash; the field to update in the <code><em>tabId:elementId</em></code> format.</li> * <li><code>params</code> &ndash; additional arguments to be passed to the server connector (optional).</li> * <li><code>onSelect</code> &ndash; a function to execute when the file is selected/uploaded (optional).</li> * <li><code>url</code> &ndash; the URL to be called (optional).</li> * </ul> * * <strong>Example 3: (Quick Upload)</strong> * * <pre> * { * type : 'fileButton', * label : editor.lang.common.uploadSubmit, * id : 'buttonId', * filebrowser : * { * action : 'QuickUpload', // required * target : 'tab1:elementId', // required * params : // optional * { * type : 'Files', * currentFolder : '/folder/' * }, * onSelect : function( fileUrl, errorMessage ) // optional * { * // Do not call the built-in selectFuntion. * // return false; * } * }, * 'for' : [ 'tab1', 'myFile' ] * } * </pre> * * Suppose you have a file element with an ID of <code>myFile</code>, a text * field with an ID of <code>elementId</code> and a <code>fileButton</code>. * If the <code>filebowser.url</code> attribute is not specified explicitly, * the form action will be set to <code>filebrowser[<em>DialogWindowName</em>]UploadUrl</code> * or, if not specified, to <code>filebrowserUploadUrl</code>. Additional parameters * from the <code>params</code> object will be added to the query string. It is * possible to create your own <code>uploadHandler</code> and cancel the built-in * <code>updateTargetElement</code> command.<br /><br /> * * <strong>Example 4: (Browse)</strong> * * <pre> * { * type : 'button', * id : 'buttonId', * label : editor.lang.common.browseServer, * filebrowser : * { * action : 'Browse', * url : '/ckfinder/ckfinder.html&amp;type=Images', * target : 'tab1:elementId' * } * } * </pre> * * In this example, when the button is pressed, the file browser will be opened in a * popup window. If you do not specify the <code>filebrowser.url</code> attribute, * <code>filebrowser[<em>DialogName</em>]BrowseUrl</code> or * <code>filebrowserBrowseUrl</code> will be used. After selecting a file in the file * browser, an element with an ID of <code>elementId</code> will be updated. Just * like in the third example, a custom <code>onSelect</code> function may be defined. */ ( function() { /* * Adds (additional) arguments to given url. * * @param {String} * url The url. * @param {Object} * params Additional parameters. */ function addQueryString( url, params ) { var queryString = []; if ( !params ) return url; else { for ( var i in params ) queryString.push( i + "=" + encodeURIComponent( params[ i ] ) ); } return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" ); } /* * Make a string's first character uppercase. * * @param {String} * str String. */ function ucFirst( str ) { str += ''; var f = str.charAt( 0 ).toUpperCase(); return f + str.substr( 1 ); } /* * The onlick function assigned to the 'Browse Server' button. Opens the * file browser and updates target field when file is selected. * * @param {CKEDITOR.event} * evt The event object. */ function browseServer( evt ) { var dialog = this.getDialog(); var editor = dialog.getParentEditor(); editor._.filebrowserSe = this; var width = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowWidth' ] || editor.config.filebrowserWindowWidth || '80%'; var height = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowHeight' ] || editor.config.filebrowserWindowHeight || '70%'; var params = this.filebrowser.params || {}; params.CKEditor = editor.name; params.CKEditorFuncNum = editor._.filebrowserFn; if ( !params.langCode ) params.langCode = editor.langCode; var url = addQueryString( this.filebrowser.url, params ); // TODO: V4: Remove backward compatibility (#8163). editor.popup( url, width, height, editor.config.filebrowserWindowFeatures || editor.config.fileBrowserWindowFeatures ); } /* * The onlick function assigned to the 'Upload' button. Makes the final * decision whether form is really submitted and updates target field when * file is uploaded. * * @param {CKEDITOR.event} * evt The event object. */ function uploadFile( evt ) { var dialog = this.getDialog(); var editor = dialog.getParentEditor(); editor._.filebrowserSe = this; // If user didn't select the file, stop the upload. if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getInputElement().$.value ) return false; if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getAction() ) return false; return true; } /* * Setups the file element. * * @param {CKEDITOR.ui.dialog.file} * fileInput The file element used during file upload. * @param {Object} * filebrowser Object containing filebrowser settings assigned to * the fileButton associated with this file element. */ function setupFileElement( editor, fileInput, filebrowser ) { var params = filebrowser.params || {}; params.CKEditor = editor.name; params.CKEditorFuncNum = editor._.filebrowserFn; if ( !params.langCode ) params.langCode = editor.langCode; fileInput.action = addQueryString( filebrowser.url, params ); fileInput.filebrowser = filebrowser; } /* * Traverse through the content definition and attach filebrowser to * elements with 'filebrowser' attribute. * * @param String * dialogName Dialog name. * @param {CKEDITOR.dialog.definitionObject} * definition Dialog definition. * @param {Array} * elements Array of {@link CKEDITOR.dialog.definition.content} * objects. */ function attachFileBrowser( editor, dialogName, definition, elements ) { var element, fileInput; for ( var i in elements ) { element = elements[ i ]; if ( element.type == 'hbox' || element.type == 'vbox' ) attachFileBrowser( editor, dialogName, definition, element.children ); if ( !element.filebrowser ) continue; if ( typeof element.filebrowser == 'string' ) { var fb = { action : ( element.type == 'fileButton' ) ? 'QuickUpload' : 'Browse', target : element.filebrowser }; element.filebrowser = fb; } if ( element.filebrowser.action == 'Browse' ) { var url = element.filebrowser.url; if ( url === undefined ) { url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'BrowseUrl' ]; if ( url === undefined ) url = editor.config.filebrowserBrowseUrl; } if ( url ) { element.onClick = browseServer; element.filebrowser.url = url; element.hidden = false; } } else if ( element.filebrowser.action == 'QuickUpload' && element[ 'for' ] ) { url = element.filebrowser.url; if ( url === undefined ) { url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'UploadUrl' ]; if ( url === undefined ) url = editor.config.filebrowserUploadUrl; } if ( url ) { var onClick = element.onClick; element.onClick = function( evt ) { // "element" here means the definition object, so we need to find the correct // button to scope the event call var sender = evt.sender; if ( onClick && onClick.call( sender, evt ) === false ) return false; return uploadFile.call( sender, evt ); }; element.filebrowser.url = url; element.hidden = false; setupFileElement( editor, definition.getContents( element[ 'for' ][ 0 ] ).get( element[ 'for' ][ 1 ] ), element.filebrowser ); } } } } /* * Updates the target element with the url of uploaded/selected file. * * @param {String} * url The url of a file. */ function updateTargetElement( url, sourceElement ) { var dialog = sourceElement.getDialog(); var targetElement = sourceElement.filebrowser.target || null; url = url.replace( /#/g, '%23' ); // If there is a reference to targetElement, update it. if ( targetElement ) { var target = targetElement.split( ':' ); var element = dialog.getContentElement( target[ 0 ], target[ 1 ] ); if ( element ) { element.setValue( url ); dialog.selectPage( target[ 0 ] ); } } } /* * Returns true if filebrowser is configured in one of the elements. * * @param {CKEDITOR.dialog.definitionObject} * definition Dialog definition. * @param String * tabId The tab id where element(s) can be found. * @param String * elementId The element id (or ids, separated with a semicolon) to check. */ function isConfigured( definition, tabId, elementId ) { if ( elementId.indexOf( ";" ) !== -1 ) { var ids = elementId.split( ";" ); for ( var i = 0 ; i < ids.length ; i++ ) { if ( isConfigured( definition, tabId, ids[i] ) ) return true; } return false; } var elementFileBrowser = definition.getContents( tabId ).get( elementId ).filebrowser; return ( elementFileBrowser && elementFileBrowser.url ); } function setUrl( fileUrl, data ) { var dialog = this._.filebrowserSe.getDialog(), targetInput = this._.filebrowserSe[ 'for' ], onSelect = this._.filebrowserSe.filebrowser.onSelect; if ( targetInput ) dialog.getContentElement( targetInput[ 0 ], targetInput[ 1 ] ).reset(); if ( typeof data == 'function' && data.call( this._.filebrowserSe ) === false ) return; if ( onSelect && onSelect.call( this._.filebrowserSe, fileUrl, data ) === false ) return; // The "data" argument may be used to pass the error message to the editor. if ( typeof data == 'string' && data ) alert( data ); if ( fileUrl ) updateTargetElement( fileUrl, this._.filebrowserSe ); } CKEDITOR.plugins.add( 'filebrowser', { init : function( editor, pluginPath ) { editor._.filebrowserFn = CKEDITOR.tools.addFunction( setUrl, editor ); editor.on( 'destroy', function () { CKEDITOR.tools.removeFunction( this._.filebrowserFn ); } ); } } ); CKEDITOR.on( 'dialogDefinition', function( evt ) { var definition = evt.data.definition, element; // Associate filebrowser to elements with 'filebrowser' attribute. for ( var i in definition.contents ) { if ( ( element = definition.contents[ i ] ) ) { attachFileBrowser( evt.editor, evt.data.name, definition, element.elements ); if ( element.hidden && element.filebrowser ) { element.hidden = !isConfigured( definition, element[ 'id' ], element.filebrowser ); } } } } ); } )(); /** * The location of an external file browser that should be launched when the <strong>Browse Server</strong> * button is pressed. If configured, the <strong>Browse Server</strong> button will appear in the * <strong>Link</strong>, <strong>Image</strong>, and <strong>Flash</strong> dialog windows. * @see The <a href="http://docs.cksource.com/CKEditor_3.x/Developers_Guide/File_Browser_(Uploader)">File Browser/Uploader</a> documentation. * @name CKEDITOR.config.filebrowserBrowseUrl * @since 3.0 * @type String * @default <code>''</code> (empty string = disabled) * @example * config.filebrowserBrowseUrl = '/browser/browse.php'; */ /** * The location of the script that handles file uploads. * If set, the <strong>Upload</strong> tab will appear in the <strong>Link</strong>, <strong>Image</strong>, * and <strong>Flash</strong> dialog windows. * @name CKEDITOR.config.filebrowserUploadUrl * @see The <a href="http://docs.cksource.com/CKEditor_3.x/Developers_Guide/File_Browser_(Uploader)">File Browser/Uploader</a> documentation. * @since 3.0 * @type String * @default <code>''</code> (empty string = disabled) * @example * config.filebrowserUploadUrl = '/uploader/upload.php'; */ /** * The location of an external file browser that should be launched when the <strong>Browse Server</strong> * button is pressed in the <strong>Image</strong> dialog window. * If not set, CKEditor will use <code>{@link CKEDITOR.config.filebrowserBrowseUrl}</code>. * @name CKEDITOR.config.filebrowserImageBrowseUrl * @since 3.0 * @type String * @default <code>''</code> (empty string = disabled) * @example * config.filebrowserImageBrowseUrl = '/browser/browse.php?type=Images'; */ /** * The location of an external file browser that should be launched when the <strong>Browse Server</strong> * button is pressed in the <strong>Flash</strong> dialog window. * If not set, CKEditor will use <code>{@link CKEDITOR.config.filebrowserBrowseUrl}</code>. * @name CKEDITOR.config.filebrowserFlashBrowseUrl * @since 3.0 * @type String * @default <code>''</code> (empty string = disabled) * @example * config.filebrowserFlashBrowseUrl = '/browser/browse.php?type=Flash'; */ /** * The location of the script that handles file uploads in the <strong>Image</strong> dialog window. * If not set, CKEditor will use <code>{@link CKEDITOR.config.filebrowserUploadUrl}</code>. * @name CKEDITOR.config.filebrowserImageUploadUrl * @since 3.0 * @type String * @default <code>''</code> (empty string = disabled) * @example * config.filebrowserImageUploadUrl = '/uploader/upload.php?type=Images'; */ /** * The location of the script that handles file uploads in the <strong>Flash</strong> dialog window. * If not set, CKEditor will use <code>{@link CKEDITOR.config.filebrowserUploadUrl}</code>. * @name CKEDITOR.config.filebrowserFlashUploadUrl * @since 3.0 * @type String * @default <code>''</code> (empty string = disabled) * @example * config.filebrowserFlashUploadUrl = '/uploader/upload.php?type=Flash'; */ /** * The location of an external file browser that should be launched when the <strong>Browse Server</strong> * button is pressed in the <strong>Link</strong> tab of the <strong>Image</strong> dialog window. * If not set, CKEditor will use <code>{@link CKEDITOR.config.filebrowserBrowseUrl}</code>. * @name CKEDITOR.config.filebrowserImageBrowseLinkUrl * @since 3.2 * @type String * @default <code>''</code> (empty string = disabled) * @example * config.filebrowserImageBrowseLinkUrl = '/browser/browse.php'; */ /** * The features to use in the file browser popup window. * @name CKEDITOR.config.filebrowserWindowFeatures * @since 3.4.1 * @type String * @default <code>'location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,resizable=yes,scrollbars=yes'</code> * @example * config.filebrowserWindowFeatures = 'resizable=yes,scrollbars=no'; */ /** * The width of the file browser popup window. It can be a number denoting a value in * pixels or a percent string. * @name CKEDITOR.config.filebrowserWindowWidth * @type Number|String * @default <code>'80%'</code> * @example * config.filebrowserWindowWidth = 750; * @example * config.filebrowserWindowWidth = '50%'; */ /** * The height of the file browser popup window. It can be a number denoting a value in * pixels or a percent string. * @name CKEDITOR.config.filebrowserWindowHeight * @type Number|String * @default <code>'70%'</code> * @example * config.filebrowserWindowHeight = 580; * @example * config.filebrowserWindowHeight = '50%'; */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Spell Check As You Type (SCAYT). * Button name : Scayt. */ (function() { var commandName = 'scaytcheck', openPage = ''; // Checks if a value exists in an array function in_array( needle, haystack ) { var found = 0, key; for ( key in haystack ) { if ( haystack[ key ] == needle ) { found = 1; break; } } return found; } var onEngineLoad = function() { var editor = this; var createInstance = function() // Create new instance every time Document is created. { var config = editor.config; // Initialise Scayt instance. var oParams = {}; // Get the iframe. oParams.srcNodeRef = editor.document.getWindow().$.frameElement; // syntax : AppName.AppVersion@AppRevision oParams.assocApp = 'CKEDITOR.' + CKEDITOR.version + '@' + CKEDITOR.revision; oParams.customerid = config.scayt_customerid || '1:WvF0D4-UtPqN1-43nkD4-NKvUm2-daQqk3-LmNiI-z7Ysb4-mwry24-T8YrS3-Q2tpq2'; oParams.customDictionaryIds = config.scayt_customDictionaryIds || ''; oParams.userDictionaryName = config.scayt_userDictionaryName || ''; oParams.sLang = config.scayt_sLang || 'en_US'; // Introduce SCAYT onLoad callback. (#5632) oParams.onLoad = function() { // Draw down word marker to avoid being covered by background-color style.(#5466) if ( !( CKEDITOR.env.ie && CKEDITOR.env.version < 8 ) ) this.addStyle( this.selectorCss(), 'padding-bottom: 2px !important;' ); // Call scayt_control.focus when SCAYT loaded // and only if editor has focus and scayt control creates at first time (#5720) if ( editor.focusManager.hasFocus && !plugin.isControlRestored( editor ) ) this.focus(); }; oParams.onBeforeChange = function() { if ( plugin.getScayt( editor ) && !editor.checkDirty() ) setTimeout( function(){ editor.resetDirty(); }, 0 ); }; var scayt_custom_params = window.scayt_custom_params; if ( typeof scayt_custom_params == 'object' ) { for ( var k in scayt_custom_params ) oParams[ k ] = scayt_custom_params[ k ]; } // needs for restoring a specific scayt control settings if ( plugin.getControlId( editor ) ) oParams.id = plugin.getControlId( editor ); var scayt_control = new window.scayt( oParams ); scayt_control.afterMarkupRemove.push( function( node ) { ( new CKEDITOR.dom.element( node, scayt_control.document ) ).mergeSiblings(); } ); // Copy config. var lastInstance = plugin.instances[ editor.name ]; if ( lastInstance ) { scayt_control.sLang = lastInstance.sLang; scayt_control.option( lastInstance.option() ); scayt_control.paused = lastInstance.paused; } plugin.instances[ editor.name ] = scayt_control; try { scayt_control.setDisabled( plugin.isPaused( editor ) === false ); } catch (e) {} editor.fire( 'showScaytState' ); }; editor.on( 'contentDom', createInstance ); editor.on( 'contentDomUnload', function() { // Remove scripts. var scripts = CKEDITOR.document.getElementsByTag( 'script' ), scaytIdRegex = /^dojoIoScript(\d+)$/i, scaytSrcRegex = /^https?:\/\/svc\.webspellchecker\.net\/spellcheck\/script\/ssrv\.cgi/i; for ( var i=0; i < scripts.count(); i++ ) { var script = scripts.getItem( i ), id = script.getId(), src = script.getAttribute( 'src' ); if ( id && src && id.match( scaytIdRegex ) && src.match( scaytSrcRegex )) script.remove(); } }); editor.on( 'beforeCommandExec', function( ev ) // Disable SCAYT before Source command execution. { if ( ( ev.data.name == 'source' || ev.data.name == 'newpage' ) && editor.mode == 'wysiwyg' ) { var scayt_instance = plugin.getScayt( editor ); if ( scayt_instance ) { plugin.setPaused( editor, !scayt_instance.disabled ); // store a control id for restore a specific scayt control settings plugin.setControlId( editor, scayt_instance.id ); scayt_instance.destroy( true ); delete plugin.instances[ editor.name ]; } } // Catch on source mode switch off (#5720) else if ( ev.data.name == 'source' && editor.mode == 'source' ) plugin.markControlRestore( editor ); }); editor.on( 'afterCommandExec', function( ev ) { if ( !plugin.isScaytEnabled( editor ) ) return; if ( editor.mode == 'wysiwyg' && ( ev.data.name == 'undo' || ev.data.name == 'redo' ) ) window.setTimeout( function() { plugin.getScayt( editor ).refresh(); }, 10 ); }); editor.on( 'destroy', function( ev ) { var editor = ev.editor, scayt_instance = plugin.getScayt( editor ); // SCAYT instance might already get destroyed by mode switch (#5744). if ( !scayt_instance ) return; delete plugin.instances[ editor.name ]; // store a control id for restore a specific scayt control settings plugin.setControlId( editor, scayt_instance.id ); scayt_instance.destroy( true ); }); // Listen to data manipulation to reflect scayt markup. editor.on( 'afterSetData', function() { if ( plugin.isScaytEnabled( editor ) ) { window.setTimeout( function() { var instance = plugin.getScayt( editor ); instance && instance.refresh(); }, 10 ); } }); // Reload spell-checking for current word after insertion completed. editor.on( 'insertElement', function() { var scayt_instance = plugin.getScayt( editor ); if ( plugin.isScaytEnabled( editor ) ) { // Unlock the selection before reload, SCAYT will take // care selection update. if ( CKEDITOR.env.ie ) editor.getSelection().unlock( true ); // Return focus to the editor and refresh SCAYT markup (#5573). window.setTimeout( function() { scayt_instance.focus(); scayt_instance.refresh(); }, 10 ); } }, this, null, 50 ); editor.on( 'insertHtml', function() { var scayt_instance = plugin.getScayt( editor ); if ( plugin.isScaytEnabled( editor ) ) { // Unlock the selection before reload, SCAYT will take // care selection update. if ( CKEDITOR.env.ie ) editor.getSelection().unlock( true ); // Return focus to the editor (#5573) // Refresh SCAYT markup window.setTimeout( function() { scayt_instance.focus(); scayt_instance.refresh(); }, 10 ); } }, this, null, 50 ); editor.on( 'scaytDialog', function( ev ) // Communication with dialog. { ev.data.djConfig = window.djConfig; ev.data.scayt_control = plugin.getScayt( editor ); ev.data.tab = openPage; ev.data.scayt = window.scayt; }); var dataProcessor = editor.dataProcessor, htmlFilter = dataProcessor && dataProcessor.htmlFilter; if ( htmlFilter ) { htmlFilter.addRules( { elements : { span : function( element ) { if ( element.attributes[ 'data-scayt_word' ] && element.attributes[ 'data-scaytid' ] ) { delete element.name; // Write children, but don't write this node. return element; } } } } ); } // Override Image.equals method avoid CK snapshot module to add SCAYT markup to snapshots. (#5546) var undoImagePrototype = CKEDITOR.plugins.undo.Image.prototype; undoImagePrototype.equals = CKEDITOR.tools.override( undoImagePrototype.equals, function( org ) { return function( otherImage ) { var thisContents = this.contents, otherContents = otherImage.contents; var scayt_instance = plugin.getScayt( this.editor ); // Making the comparison based on content without SCAYT word markers. if ( scayt_instance && plugin.isScaytReady( this.editor ) ) { // scayt::reset might return value undefined. (#5742) this.contents = scayt_instance.reset( thisContents ) || ''; otherImage.contents = scayt_instance.reset( otherContents ) || ''; } var retval = org.apply( this, arguments ); this.contents = thisContents; otherImage.contents = otherContents; return retval; }; }); if ( editor.document ) createInstance(); }; CKEDITOR.plugins.scayt = { engineLoaded : false, instances : {}, // Data storage for SCAYT control, based on editor instances controlInfo : {}, setControlInfo : function( editor, o ) { if ( editor && editor.name && typeof ( this.controlInfo[ editor.name ] ) != 'object' ) this.controlInfo[ editor.name ] = {}; for ( var infoOpt in o ) this.controlInfo[ editor.name ][ infoOpt ] = o[ infoOpt ]; }, isControlRestored : function( editor ) { if ( editor && editor.name && this.controlInfo[ editor.name ] ) { return this.controlInfo[ editor.name ].restored ; } return false; }, markControlRestore : function( editor ) { this.setControlInfo( editor, { restored:true } ); }, setControlId: function( editor, id ) { this.setControlInfo( editor, { id:id } ); }, getControlId: function( editor ) { if ( editor && editor.name && this.controlInfo[ editor.name ] && this.controlInfo[ editor.name ].id ) { return this.controlInfo[ editor.name ].id; } return null; }, setPaused: function( editor , bool ) { this.setControlInfo( editor, { paused:bool } ); }, isPaused: function( editor ) { if ( editor && editor.name && this.controlInfo[editor.name] ) { return this.controlInfo[editor.name].paused; } return undefined; }, getScayt : function( editor ) { return this.instances[ editor.name ]; }, isScaytReady : function( editor ) { return this.engineLoaded === true && 'undefined' !== typeof window.scayt && this.getScayt( editor ); }, isScaytEnabled : function( editor ) { var scayt_instance = this.getScayt( editor ); return ( scayt_instance ) ? scayt_instance.disabled === false : false; }, getUiTabs : function( editor ) { var uiTabs = []; // read UI tabs value from config var configUiTabs = editor.config.scayt_uiTabs || "1,1,1"; // convert string to array configUiTabs = configUiTabs.split( ',' ); // "About us" should be always shown for standard config configUiTabs[3] = "1"; for ( var i = 0; i < 4; i++ ) { uiTabs[i] = (typeof window.scayt != "undefined" && typeof window.scayt.uiTags != "undefined") ? (parseInt(configUiTabs[i],10) && window.scayt.uiTags[i]) : parseInt(configUiTabs[i],10); } return uiTabs; }, loadEngine : function( editor ) { // SCAYT doesn't work with Firefox2, Opera and AIR. if ( CKEDITOR.env.gecko && CKEDITOR.env.version < 10900 || CKEDITOR.env.opera || CKEDITOR.env.air ) return editor.fire( 'showScaytState' ); if ( this.engineLoaded === true ) return onEngineLoad.apply( editor ); // Add new instance. else if ( this.engineLoaded == -1 ) // We are waiting. return CKEDITOR.on( 'scaytReady', function(){ onEngineLoad.apply( editor ); } ); // Use function(){} to avoid rejection as duplicate. CKEDITOR.on( 'scaytReady', onEngineLoad, editor ); CKEDITOR.on( 'scaytReady', function() { this.engineLoaded = true; }, this, null, 0 ); // First to run. this.engineLoaded = -1; // Loading in progress. // compose scayt url var protocol = document.location.protocol; // Default to 'http' for unknown. protocol = protocol.search( /https?:/) != -1? protocol : 'http:'; var baseUrl = 'svc.webspellchecker.net/scayt26/loader__base.js'; var scaytUrl = editor.config.scayt_srcUrl || ( protocol + '//' + baseUrl ); var scaytConfigBaseUrl = plugin.parseUrl( scaytUrl ).path + '/'; if( window.scayt == undefined ) { CKEDITOR._djScaytConfig = { baseUrl: scaytConfigBaseUrl, addOnLoad: [ function() { CKEDITOR.fireOnce( 'scaytReady' ); } ], isDebug: false }; // Append javascript code. CKEDITOR.document.getHead().append( CKEDITOR.document.createElement( 'script', { attributes : { type : 'text/javascript', async : 'true', src : scaytUrl } }) ); } else CKEDITOR.fireOnce( 'scaytReady' ); return null; }, parseUrl : function ( data ) { var match; if ( data.match && ( match = data.match(/(.*)[\/\\](.*?\.\w+)$/) ) ) return { path: match[1], file: match[2] }; else return data; } }; var plugin = CKEDITOR.plugins.scayt; // Context menu constructing. var addButtonCommand = function( editor, buttonName, buttonLabel, commandName, command, menugroup, menuOrder ) { editor.addCommand( commandName, command ); // If the "menu" plugin is loaded, register the menu item. editor.addMenuItem( commandName, { label : buttonLabel, command : commandName, group : menugroup, order : menuOrder }); }; var commandDefinition = { preserveState : true, editorFocus : false, canUndo : false, exec: function( editor ) { if ( plugin.isScaytReady( editor ) ) { var isEnabled = plugin.isScaytEnabled( editor ); this.setState( isEnabled ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_ON ); var scayt_control = plugin.getScayt( editor ); // the place where the status of editor focus should be restored // after there will be ability to store its state before SCAYT button click // if (storedFocusState is focused ) // scayt_control.focus(); // // now focus is set certainly scayt_control.focus(); scayt_control.setDisabled( isEnabled ); } else if ( !editor.config.scayt_autoStartup && plugin.engineLoaded >= 0 ) // Load first time { this.setState( CKEDITOR.TRISTATE_DISABLED ); plugin.loadEngine( editor ); } } }; // Add scayt plugin. CKEDITOR.plugins.add( 'scayt', { requires : [ 'menubutton' ], beforeInit : function( editor ) { var items_order = editor.config.scayt_contextMenuItemsOrder || 'suggest|moresuggest|control', items_order_str = ""; items_order = items_order.split( '|' ); if ( items_order && items_order.length ) { for ( var pos = 0 ; pos < items_order.length ; pos++ ) items_order_str += 'scayt_' + items_order[ pos ] + ( items_order.length != parseInt( pos, 10 ) + 1 ? ',' : '' ); } // Put it on top of all context menu items (#5717) editor.config.menu_groups = items_order_str + ',' + editor.config.menu_groups; }, init : function( editor ) { // Delete span[data-scaytid] when text pasting in editor (#6921) var dataFilter = editor.dataProcessor && editor.dataProcessor.dataFilter; var dataFilterRules = { elements : { span : function( element ) { var attrs = element.attributes; if ( attrs && attrs[ 'data-scaytid' ] ) delete element.name; } } }; dataFilter && dataFilter.addRules( dataFilterRules ); var moreSuggestions = {}, mainSuggestions = {}; // Scayt command. var command = editor.addCommand( commandName, commandDefinition ); // Add Options dialog. CKEDITOR.dialog.add( commandName, CKEDITOR.getUrl( this.path + 'dialogs/options.js' ) ); var uiTabs = plugin.getUiTabs( editor ); var menuGroup = 'scaytButton'; editor.addMenuGroup( menuGroup ); // combine menu items to render var uiMenuItems = {}; var lang = editor.lang.scayt; // always added uiMenuItems.scaytToggle = { label : lang.enable, command : commandName, group : menuGroup }; if ( uiTabs[0] == 1 ) uiMenuItems.scaytOptions = { label : lang.options, group : menuGroup, onClick : function() { openPage = 'options'; editor.openDialog( commandName ); } }; if ( uiTabs[1] == 1 ) uiMenuItems.scaytLangs = { label : lang.langs, group : menuGroup, onClick : function() { openPage = 'langs'; editor.openDialog( commandName ); } }; if ( uiTabs[2] == 1 ) uiMenuItems.scaytDict = { label : lang.dictionariesTab, group : menuGroup, onClick : function() { openPage = 'dictionaries'; editor.openDialog( commandName ); } }; // always added uiMenuItems.scaytAbout = { label : editor.lang.scayt.about, group : menuGroup, onClick : function() { openPage = 'about'; editor.openDialog( commandName ); } }; editor.addMenuItems( uiMenuItems ); editor.ui.add( 'Scayt', CKEDITOR.UI_MENUBUTTON, { label : lang.title, title : CKEDITOR.env.opera ? lang.opera_title : lang.title, className : 'cke_button_scayt', modes : { wysiwyg : 1 }, onRender: function() { command.on( 'state', function() { this.setState( command.state ); }, this); }, onMenu : function() { var isEnabled = plugin.isScaytEnabled( editor ); editor.getMenuItem( 'scaytToggle' ).label = lang[ isEnabled ? 'disable' : 'enable' ]; var uiTabs = plugin.getUiTabs( editor ); return { scaytToggle : CKEDITOR.TRISTATE_OFF, scaytOptions : isEnabled && uiTabs[0] ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED, scaytLangs : isEnabled && uiTabs[1] ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED, scaytDict : isEnabled && uiTabs[2] ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED, scaytAbout : isEnabled && uiTabs[3] ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED }; } }); // If the "contextmenu" plugin is loaded, register the listeners. if ( editor.contextMenu && editor.addMenuItems ) { editor.contextMenu.addListener( function( element, selection ) { if ( !plugin.isScaytEnabled( editor ) || selection.getRanges()[ 0 ].checkReadOnly() ) return null; var scayt_control = plugin.getScayt( editor ), node = scayt_control.getScaytNode(); if ( !node ) return null; var word = scayt_control.getWord( node ); if ( !word ) return null; var sLang = scayt_control.getLang(), _r = {}, items_suggestion = window.scayt.getSuggestion( word, sLang ); if ( !items_suggestion || !items_suggestion.length ) return null; // Remove unused commands and menuitems for ( var m in moreSuggestions ) { delete editor._.menuItems[ m ]; delete editor._.commands[ m ]; } for ( m in mainSuggestions ) { delete editor._.menuItems[ m ]; delete editor._.commands[ m ]; } moreSuggestions = {}; // Reset items. mainSuggestions = {}; var moreSuggestionsUnable = editor.config.scayt_moreSuggestions || 'on'; var moreSuggestionsUnableAdded = false; var maxSuggestions = editor.config.scayt_maxSuggestions; ( typeof maxSuggestions != 'number' ) && ( maxSuggestions = 5 ); !maxSuggestions && ( maxSuggestions = items_suggestion.length ); var contextCommands = editor.config.scayt_contextCommands || 'all'; contextCommands = contextCommands.split( '|' ); for ( var i = 0, l = items_suggestion.length; i < l; i += 1 ) { var commandName = 'scayt_suggestion_' + items_suggestion[i].replace( ' ', '_' ); var exec = ( function( el, s ) { return { exec: function() { scayt_control.replace( el, s ); } }; })( node, items_suggestion[i] ); if ( i < maxSuggestions ) { addButtonCommand( editor, 'button_' + commandName, items_suggestion[i], commandName, exec, 'scayt_suggest', i + 1 ); _r[ commandName ] = CKEDITOR.TRISTATE_OFF; mainSuggestions[ commandName ] = CKEDITOR.TRISTATE_OFF; } else if ( moreSuggestionsUnable == 'on' ) { addButtonCommand( editor, 'button_' + commandName, items_suggestion[i], commandName, exec, 'scayt_moresuggest', i + 1 ); moreSuggestions[ commandName ] = CKEDITOR.TRISTATE_OFF; moreSuggestionsUnableAdded = true; } } if ( moreSuggestionsUnableAdded ) { // Register the More suggestions group; editor.addMenuItem( 'scayt_moresuggest', { label : lang.moreSuggestions, group : 'scayt_moresuggest', order : 10, getItems : function() { return moreSuggestions; } }); mainSuggestions[ 'scayt_moresuggest' ] = CKEDITOR.TRISTATE_OFF; } if ( in_array( 'all', contextCommands ) || in_array( 'ignore', contextCommands) ) { var ignore_command = { exec: function(){ scayt_control.ignore( node ); } }; addButtonCommand( editor, 'ignore', lang.ignore, 'scayt_ignore', ignore_command, 'scayt_control', 1 ); mainSuggestions[ 'scayt_ignore' ] = CKEDITOR.TRISTATE_OFF; } if ( in_array( 'all', contextCommands ) || in_array( 'ignoreall', contextCommands ) ) { var ignore_all_command = { exec: function(){ scayt_control.ignoreAll( node ); } }; addButtonCommand(editor, 'ignore_all', lang.ignoreAll, 'scayt_ignore_all', ignore_all_command, 'scayt_control', 2); mainSuggestions['scayt_ignore_all'] = CKEDITOR.TRISTATE_OFF; } if ( in_array( 'all', contextCommands ) || in_array( 'add', contextCommands ) ) { var addword_command = { exec: function(){ window.scayt.addWordToUserDictionary( node ); } }; addButtonCommand(editor, 'add_word', lang.addWord, 'scayt_add_word', addword_command, 'scayt_control', 3); mainSuggestions['scayt_add_word'] = CKEDITOR.TRISTATE_OFF; } if ( scayt_control.fireOnContextMenu ) scayt_control.fireOnContextMenu( editor ); return mainSuggestions; }); } var showInitialState = function() { editor.removeListener( 'showScaytState', showInitialState ); if ( !CKEDITOR.env.opera && !CKEDITOR.env.air ) command.setState( plugin.isScaytEnabled( editor ) ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF ); else command.setState( CKEDITOR.TRISTATE_DISABLED ); }; editor.on( 'showScaytState', showInitialState ); if ( CKEDITOR.env.opera || CKEDITOR.env.air ) { editor.on( 'instanceReady', function() { showInitialState(); }); } // Start plugin if ( editor.config.scayt_autoStartup ) { editor.on( 'instanceReady', function() { plugin.loadEngine( editor ); }); } }, afterInit : function( editor ) { // Prevent word marker line from displaying in elements path and been removed when cleaning format. (#3570) (#4125) var elementsPathFilters, scaytFilter = function( element ) { if ( element.hasAttribute( 'data-scaytid' ) ) return false; }; if ( editor._.elementsPath && ( elementsPathFilters = editor._.elementsPath.filters ) ) elementsPathFilters.push( scaytFilter ); editor.addRemoveFormatFilter && editor.addRemoveFormatFilter( scaytFilter ); } }); })(); /** * If enabled (set to <code>true</code>), turns on SCAYT automatically * after loading the editor. * @name CKEDITOR.config.scayt_autoStartup * @type Boolean * @default <code>false</code> * @example * config.scayt_autoStartup = true; */ /** * Defines the number of SCAYT suggestions to show in the main context menu. * Possible values are: * <ul> * <li><code>0</code> (zero) &ndash; All suggestions are displayed in the main context menu.</li> * <li>Positive number &ndash; The maximum number of suggestions to show in the context * menu. Other entries will be shown in the "More Suggestions" sub-menu.</li> * <li>Negative number &ndash; No suggestions are shown in the main context menu. All * entries will be listed in the the "Suggestions" sub-menu.</li> * </ul> * @name CKEDITOR.config.scayt_maxSuggestions * @type Number * @default <code>5</code> * @example * // Display only three suggestions in the main context menu. * config.scayt_maxSuggestions = 3; * @example * // Do not show the suggestions directly. * config.scayt_maxSuggestions = -1; */ /** * Sets the customer ID for SCAYT. Required for migration from free, * ad-supported version to paid, ad-free version. * @name CKEDITOR.config.scayt_customerid * @type String * @default <code>''</code> * @example * // Load SCAYT using my customer ID. * config.scayt_customerid = 'your-encrypted-customer-id'; */ /** * Enables/disables the "More Suggestions" sub-menu in the context menu. * Possible values are <code>on</code> and <code>off</code>. * @name CKEDITOR.config.scayt_moreSuggestions * @type String * @default <code>'on'</code> * @example * // Disables the "More Suggestions" sub-menu. * config.scayt_moreSuggestions = 'off'; */ /** * Customizes the display of SCAYT context menu commands ("Add Word", "Ignore" * and "Ignore All"). This must be a string with one or more of the following * words separated by a pipe character ("|"): * <ul> * <li><code>off</code> &ndash; disables all options.</li> * <li><code>all</code> &ndash; enables all options.</li> * <li><code>ignore</code> &ndash; enables the "Ignore" option.</li> * <li><code>ignoreall</code> &ndash; enables the "Ignore All" option.</li> * <li><code>add</code> &ndash; enables the "Add Word" option.</li> * </ul> * @name CKEDITOR.config.scayt_contextCommands * @type String * @default <code>'all'</code> * @example * // Show only "Add Word" and "Ignore All" in the context menu. * config.scayt_contextCommands = 'add|ignoreall'; */ /** * Sets the default spell checking language for SCAYT. Possible values are: * <code>en_US</code>, <code>en_GB</code>, <code>pt_BR</code>, <code>da_DK</code>, * <code>nl_NL</code>, <code>en_CA</code>, <code>fi_FI</code>, <code>fr_FR</code>, * <code>fr_CA</code>, <code>de_DE</code>, <code>el_GR</code>, <code>it_IT</code>, * <code>nb_NO</code>, <code>pt_PT</code>, <code>es_ES</code>, <code>sv_SE</code>. * @name CKEDITOR.config.scayt_sLang * @type String * @default <code>'en_US'</code> * @example * // Sets SCAYT to German. * config.scayt_sLang = 'de_DE'; */ /** * Sets the visibility of particular tabs in the SCAYT dialog window and toolbar * button. This setting must contain a <code>1</code> (enabled) or <code>0</code> * (disabled) value for each of the following entries, in this precise order, * separated by a comma (","): "Options", "Languages", and "Dictionary". * @name CKEDITOR.config.scayt_uiTabs * @type String * @default <code>'1,1,1'</code> * @example * // Hides the "Languages" tab. * config.scayt_uiTabs = '1,0,1'; */ /** * Sets the URL to SCAYT core. Required to switch to the licensed version of SCAYT application. * Further details available at * <a href="http://wiki.webspellchecker.net/doku.php?id=migration:hosredfreetolicensedck"> * http://wiki.webspellchecker.net/doku.php?id=migration:hosredfreetolicensedck</a>. * @name CKEDITOR.config.scayt_srcUrl * @type String * @default <code>''</code> * @example * config.scayt_srcUrl = "http://my-host/spellcheck/lf/scayt/scayt.js"; */ /** * Links SCAYT to custom dictionaries. This is a string containing dictionary IDs * separared by commas (","). Available only for the licensed version. * Further details at * <a href="http://wiki.webspellchecker.net/doku.php?id=installationandconfiguration:customdictionaries:licensed"> * http://wiki.webspellchecker.net/doku.php?id=installationandconfiguration:customdictionaries:licensed</a>. * @name CKEDITOR.config.scayt_customDictionaryIds * @type String * @default <code>''</code> * @example * config.scayt_customDictionaryIds = '3021,3456,3478"'; */ /** * Makes it possible to activate a custom dictionary in SCAYT. The user * dictionary name must be used. Available only for the licensed version. * @name CKEDITOR.config.scayt_userDictionaryName * @type String * @default <code>''</code> * @example * config.scayt_userDictionaryName = 'MyDictionary'; */ /** * Defines the order SCAYT context menu items by groups. * This must be a string with one or more of the following * words separated by a pipe character ("|"): * <ul> * <li><code>suggest</code> &ndash; main suggestion word list,</li> * <li><code>moresuggest</code> &ndash; more suggestions word list,</li> * <li><code>control</code> &ndash; SCAYT commands, such as "Ignore" and "Add Word".</li> * </ul> * * @name CKEDITOR.config.scayt_contextMenuItemsOrder * @type String * @default <code>'suggest|moresuggest|control'</code> * @example * config.scayt_contextMenuItemsOrder = 'moresuggest|control|suggest'; */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'scaytcheck', function( editor ) { var firstLoad = true, captions, doc = CKEDITOR.document, editorName = editor.name, tags = CKEDITOR.plugins.scayt.getUiTabs( editor ), i, contents = [], userDicActive = 0, dic_buttons = [ // [0] contains buttons for creating "dic_create_" + editorName + ",dic_restore_" + editorName, // [1] contains buton for manipulation "dic_rename_" + editorName + ",dic_delete_" + editorName ], optionsIds = [ 'mixedCase', 'mixedWithDigits', 'allCaps', 'ignoreDomainNames' ]; // common operations function getBOMAllOptions() { if (typeof document.forms["optionsbar_" + editorName] != "undefined") return document.forms["optionsbar_" + editorName]["options"]; return []; } function getBOMAllLangs() { if (typeof document.forms["languagesbar_" + editorName] != "undefined") return document.forms["languagesbar_" + editorName]["scayt_lang"]; return []; } function setCheckedValue( radioObj, newValue ) { if ( !radioObj ) return; var radioLength = radioObj.length; if ( radioLength == undefined ) { radioObj.checked = radioObj.value == newValue.toString(); return; } for ( var i = 0; i < radioLength; i++ ) { radioObj[i].checked = false; if ( radioObj[i].value == newValue.toString() ) radioObj[i].checked = true; } } var lang = editor.lang.scayt; var tags_contents = [ { id : 'options', label : lang.optionsTab, elements : [ { type : 'html', id : 'options', html : '<form name="optionsbar_' + editorName + '"><div class="inner_options">' + ' <div class="messagebox"></div>' + ' <div style="display:none;">' + ' <input type="checkbox" name="options" id="allCaps_' + editorName + '" />' + ' <label for="allCaps" id="label_allCaps_' + editorName + '"></label>' + ' </div>' + ' <div style="display:none;">' + ' <input name="options" type="checkbox" id="ignoreDomainNames_' + editorName + '" />' + ' <label for="ignoreDomainNames" id="label_ignoreDomainNames_' + editorName + '"></label>' + ' </div>' + ' <div style="display:none;">' + ' <input name="options" type="checkbox" id="mixedCase_' + editorName + '" />' + ' <label for="mixedCase" id="label_mixedCase_' + editorName + '"></label>' + ' </div>' + ' <div style="display:none;">' + ' <input name="options" type="checkbox" id="mixedWithDigits_' + editorName + '" />' + ' <label for="mixedWithDigits" id="label_mixedWithDigits_' + editorName + '"></label>' + ' </div>' + '</div></form>' } ] }, { id : 'langs', label : lang.languagesTab, elements : [ { type : 'html', id : 'langs', html : '<form name="languagesbar_' + editorName + '"><div class="inner_langs">' + ' <div class="messagebox"></div> ' + ' <div style="float:left;width:45%;margin-left:5px;" id="scayt_lcol_' + editorName + '" ></div>' + ' <div style="float:left;width:45%;margin-left:15px;" id="scayt_rcol_' + editorName + '"></div>' + '</div></form>' } ] }, { id : 'dictionaries', label : lang.dictionariesTab, elements : [ { type : 'html', style: '', id : 'dictionaries', html : '<form name="dictionarybar_' + editorName + '"><div class="inner_dictionary" style="text-align:left; white-space:normal; width:320px; overflow: hidden;">' + ' <div style="margin:5px auto; width:80%;white-space:normal; overflow:hidden;" id="dic_message_' + editorName + '"> </div>' + ' <div style="margin:5px auto; width:80%;white-space:normal;"> ' + ' <span class="cke_dialog_ui_labeled_label" >Dictionary name</span><br>'+ ' <span class="cke_dialog_ui_labeled_content" >'+ ' <div class="cke_dialog_ui_input_text">'+ ' <input id="dic_name_' + editorName + '" type="text" class="cke_dialog_ui_input_text"/>'+ ' </div></span></div>'+ ' <div style="margin:5px auto; width:80%;white-space:normal;">'+ ' <a style="display:none;" class="cke_dialog_ui_button" href="javascript:void(0)" id="dic_create_' + editorName + '">'+ ' </a>' + ' <a style="display:none;" class="cke_dialog_ui_button" href="javascript:void(0)" id="dic_delete_' + editorName + '">'+ ' </a>' + ' <a style="display:none;" class="cke_dialog_ui_button" href="javascript:void(0)" id="dic_rename_' + editorName + '">'+ ' </a>' + ' <a style="display:none;" class="cke_dialog_ui_button" href="javascript:void(0)" id="dic_restore_' + editorName + '">'+ ' </a>' + ' </div>' + ' <div style="margin:5px auto; width:95%;white-space:normal;" id="dic_info_' + editorName + '"></div>' + '</div></form>' } ] }, { id : 'about', label : lang.aboutTab, elements : [ { type : 'html', id : 'about', style : 'margin: 5px 5px;', html : '<div id="scayt_about_' + editorName + '"></div>' } ] } ]; var dialogDefiniton = { title : lang.title, minWidth : 360, minHeight : 220, onShow : function() { var dialog = this; dialog.data = editor.fire( 'scaytDialog', {} ); dialog.options = dialog.data.scayt_control.option(); dialog.chosed_lang = dialog.sLang = dialog.data.scayt_control.sLang; if ( !dialog.data || !dialog.data.scayt || !dialog.data.scayt_control ) { alert( 'Error loading application service' ); dialog.hide(); return; } var stop = 0; if ( firstLoad ) { dialog.data.scayt.getCaption( editor.langCode || 'en', function( caps ) { if ( stop++ > 0 ) // Once only return; captions = caps; init_with_captions.apply( dialog ); reload.apply( dialog ); firstLoad = false; }); } else reload.apply( dialog ); dialog.selectPage( dialog.data.tab ); }, onOk : function() { var scayt_control = this.data.scayt_control; scayt_control.option( this.options ); // Setup language if it was changed. var csLang = this.chosed_lang; scayt_control.setLang( csLang ); scayt_control.refresh(); }, onCancel: function() { var o = getBOMAllOptions(); for ( var i in o ) o[i].checked = false; setCheckedValue( getBOMAllLangs(), "" ); }, contents : contents }; var scayt_control = CKEDITOR.plugins.scayt.getScayt( editor ); for ( i = 0; i < tags.length; i++ ) { if ( tags[ i ] == 1 ) contents[ contents.length ] = tags_contents[ i ]; } if ( tags[2] == 1 ) userDicActive = 1; var init_with_captions = function() { var dialog = this, lang_list = dialog.data.scayt.getLangList(), buttonCaptions = [ 'dic_create', 'dic_delete', 'dic_rename', 'dic_restore' ], buttonIds = [], langList = [], labels = optionsIds, i; // Add buttons titles if ( userDicActive ) { for ( i = 0; i < buttonCaptions.length; i++ ) { buttonIds[ i ] = buttonCaptions[ i ] + "_" + editorName; doc.getById( buttonIds[ i ] ).setHtml( '<span class="cke_dialog_ui_button">' + captions[ 'button_' + buttonCaptions[ i ]] +'</span>' ); } doc.getById( 'dic_info_' + editorName ).setHtml( captions[ 'dic_info' ] ); } // Fill options and dictionary labels. if ( tags[0] == 1 ) { for ( i in labels ) { var labelCaption = 'label_' + labels[ i ], labelId = labelCaption + '_' + editorName, labelElement = doc.getById( labelId ); if ( 'undefined' != typeof labelElement && 'undefined' != typeof captions[ labelCaption ] && 'undefined' != typeof dialog.options[labels[ i ]] ) { labelElement.setHtml( captions[ labelCaption ] ); var labelParent = labelElement.getParent(); labelParent.$.style.display = "block"; } } } var about = '<p><img src="' + window.scayt.getAboutInfo().logoURL + '" /></p>' + '<p>' + captions[ 'version' ] + window.scayt.getAboutInfo().version.toString() + '</p>' + '<p>' + captions[ 'about_throwt_copy' ] + '</p>'; doc.getById( 'scayt_about_' + editorName ).setHtml( about ); // Create languages tab. var createOption = function( option, list ) { var label = doc.createElement( 'label' ); label.setAttribute( 'for', 'cke_option' + option ); label.setHtml( list[ option ] ); if ( dialog.sLang == option ) // Current. dialog.chosed_lang = option; var div = doc.createElement( 'div' ); var radio = CKEDITOR.dom.element.createFromHtml( '<input id="cke_option' + option + '" type="radio" ' + ( dialog.sLang == option ? 'checked="checked"' : '' ) + ' value="' + option + '" name="scayt_lang" />' ); radio.on( 'click', function() { this.$.checked = true; dialog.chosed_lang = option; }); div.append( radio ); div.append( label ); return { lang : list[ option ], code : option, radio : div }; }; if ( tags[1] ==1 ) { for ( i in lang_list.rtl ) langList[ langList.length ] = createOption( i, lang_list.ltr ); for ( i in lang_list.ltr ) langList[ langList.length ] = createOption( i, lang_list.ltr ); langList.sort( function( lang1, lang2 ) { return ( lang2.lang > lang1.lang ) ? -1 : 1 ; }); var fieldL = doc.getById( 'scayt_lcol_' + editorName ), fieldR = doc.getById( 'scayt_rcol_' + editorName ); for ( i=0; i < langList.length; i++ ) { var field = ( i < langList.length / 2 ) ? fieldL : fieldR; field.append( langList[ i ].radio ); } } // user dictionary handlers var dic = {}; dic.dic_create = function( el, dic_name , dic_buttons ) { // comma separated button's ids include repeats if exists var all_buttons = dic_buttons[0] + ',' + dic_buttons[1]; var err_massage = captions["err_dic_create"]; var suc_massage = captions["succ_dic_create"]; window.scayt.createUserDictionary( dic_name, function( arg ) { hide_dic_buttons ( all_buttons ); display_dic_buttons ( dic_buttons[1] ); suc_massage = suc_massage.replace("%s" , arg.dname ); dic_success_message (suc_massage); }, function( arg ) { err_massage = err_massage.replace("%s" ,arg.dname ); dic_error_message ( err_massage + "( "+ (arg.message || "") +")"); }); }; dic.dic_rename = function( el, dic_name ) { // // try to rename dictionary var err_massage = captions["err_dic_rename"] || ""; var suc_massage = captions["succ_dic_rename"] || ""; window.scayt.renameUserDictionary( dic_name, function( arg ) { suc_massage = suc_massage.replace("%s" , arg.dname ); set_dic_name( dic_name ); dic_success_message ( suc_massage ); }, function( arg ) { err_massage = err_massage.replace("%s" , arg.dname ); set_dic_name( dic_name ); dic_error_message( err_massage + "( " + ( arg.message || "" ) + " )" ); }); }; dic.dic_delete = function( el, dic_name , dic_buttons ) { var all_buttons = dic_buttons[0] + ',' + dic_buttons[1]; var err_massage = captions["err_dic_delete"]; var suc_massage = captions["succ_dic_delete"]; // try to delete dictionary window.scayt.deleteUserDictionary( function( arg ) { suc_massage = suc_massage.replace("%s" , arg.dname ); hide_dic_buttons ( all_buttons ); display_dic_buttons ( dic_buttons[0] ); set_dic_name( "" ); // empty input field dic_success_message( suc_massage ); }, function( arg ) { err_massage = err_massage.replace("%s" , arg.dname ); dic_error_message(err_massage); }); }; dic.dic_restore = dialog.dic_restore || function( el, dic_name , dic_buttons ) { // try to restore existing dictionary var all_buttons = dic_buttons[0] + ',' + dic_buttons[1]; var err_massage = captions["err_dic_restore"]; var suc_massage = captions["succ_dic_restore"]; window.scayt.restoreUserDictionary(dic_name, function( arg ) { suc_massage = suc_massage.replace("%s" , arg.dname ); hide_dic_buttons ( all_buttons ); display_dic_buttons(dic_buttons[1]); dic_success_message( suc_massage ); }, function( arg ) { err_massage = err_massage.replace("%s" , arg.dname ); dic_error_message( err_massage ); }); }; function onDicButtonClick( ev ) { var dic_name = doc.getById('dic_name_' + editorName).getValue(); if ( !dic_name ) { dic_error_message(" Dictionary name should not be empty. "); return false; } try{ var el = ev.data.getTarget().getParent(); var id = /(dic_\w+)_[\w\d]+/.exec(el.getId())[1]; dic[ id ].apply( null, [ el, dic_name, dic_buttons ] ); } catch(err) { dic_error_message(" Dictionary error. "); } return true; } // ** bind event listeners var arr_buttons = ( dic_buttons[0] + ',' + dic_buttons[1] ).split( ',' ), l; for ( i = 0, l = arr_buttons.length ; i < l ; i += 1 ) { var dic_button = doc.getById(arr_buttons[i]); if ( dic_button ) dic_button.on( 'click', onDicButtonClick, this ); } }; var reload = function() { var dialog = this; // for enabled options tab if ( tags[0] == 1 ){ var opto = getBOMAllOptions(); // Animate options. for ( var k=0,l = opto.length; k<l;k++ ) { var i = opto[k].id; var checkbox = doc.getById( i ); if ( checkbox ) { opto[k].checked = false; //alert (opto[k].removeAttribute) if ( dialog.options[ i.split("_")[0] ] == 1 ) { opto[k].checked = true; } // Bind events. Do it only once. if ( firstLoad ) { checkbox.on( 'click', function() { dialog.options[ this.getId().split("_")[0] ] = this.$.checked ? 1 : 0 ; }); } } } } //for enabled languages tab if ( tags[1] == 1 ) { var domLang = doc.getById("cke_option" + dialog.sLang); setCheckedValue( domLang.$,dialog.sLang ); } // * user dictionary if ( userDicActive ) { window.scayt.getNameUserDictionary( function( o ) { var dic_name = o.dname; hide_dic_buttons( dic_buttons[0] + ',' + dic_buttons[1] ); if ( dic_name ) { doc.getById( 'dic_name_' + editorName ).setValue(dic_name); display_dic_buttons( dic_buttons[1] ); } else display_dic_buttons( dic_buttons[0] ); }, function() { doc.getById( 'dic_name_' + editorName ).setValue(""); }); dic_success_message(""); } }; function dic_error_message( m ) { doc.getById('dic_message_' + editorName).setHtml('<span style="color:red;">' + m + '</span>' ); } function dic_success_message( m ) { doc.getById('dic_message_' + editorName).setHtml('<span style="color:blue;">' + m + '</span>') ; } function display_dic_buttons( sIds ) { sIds = String( sIds ); var aIds = sIds.split(','); for ( var i=0, l = aIds.length; i < l ; i+=1) doc.getById( aIds[i] ).$.style.display = "inline"; } function hide_dic_buttons( sIds ) { sIds = String( sIds ); var aIds = sIds.split(','); for ( var i = 0, l = aIds.length; i < l ; i += 1 ) doc.getById( aIds[i] ).$.style.display = "none"; } function set_dic_name( dic_name ) { doc.getById('dic_name_' + editorName).$.value= dic_name; } return dialogDefiniton; });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.add( 'listblock', { requires : [ 'panel' ], onLoad : function() { CKEDITOR.ui.panel.prototype.addListBlock = function( name, definition ) { return this.addBlock( name, new CKEDITOR.ui.listBlock( this.getHolderElement(), definition ) ); }; CKEDITOR.ui.listBlock = CKEDITOR.tools.createClass( { base : CKEDITOR.ui.panel.block, $ : function( blockHolder, blockDefinition ) { blockDefinition = blockDefinition || {}; var attribs = blockDefinition.attributes || ( blockDefinition.attributes = {} ); ( this.multiSelect = !!blockDefinition.multiSelect ) && ( attribs[ 'aria-multiselectable' ] = true ); // Provide default role of 'listbox'. !attribs.role && ( attribs.role = 'listbox' ); // Call the base contructor. this.base.apply( this, arguments ); var keys = this.keys; keys[ 40 ] = 'next'; // ARROW-DOWN keys[ 9 ] = 'next'; // TAB keys[ 38 ] = 'prev'; // ARROW-UP keys[ CKEDITOR.SHIFT + 9 ] = 'prev'; // SHIFT + TAB keys[ 32 ] = CKEDITOR.env.ie ? 'mouseup' : 'click'; // SPACE CKEDITOR.env.ie && ( keys[ 13 ] = 'mouseup' ); // Manage ENTER, since onclick is blocked in IE (#8041). this._.pendingHtml = []; this._.items = {}; this._.groups = {}; }, _ : { close : function() { if ( this._.started ) { this._.pendingHtml.push( '</ul>' ); delete this._.started; } }, getClick : function() { if ( !this._.click ) { this._.click = CKEDITOR.tools.addFunction( function( value ) { var marked = true; if ( this.multiSelect ) marked = this.toggle( value ); else this.mark( value ); if ( this.onClick ) this.onClick( value, marked ); }, this ); } return this._.click; } }, proto : { add : function( value, html, title ) { var pendingHtml = this._.pendingHtml, id = CKEDITOR.tools.getNextId(); if ( !this._.started ) { pendingHtml.push( '<ul role="presentation" class=cke_panel_list>' ); this._.started = 1; this._.size = this._.size || 0; } this._.items[ value ] = id; pendingHtml.push( '<li id=', id, ' class=cke_panel_listItem role=presentation>' + '<a id="', id, '_option" _cke_focus=1 hidefocus=true' + ' title="', title || value, '"' + ' href="javascript:void(\'', value, '\')" ' + ( CKEDITOR.env.ie ? 'onclick="return false;" onmouseup' : 'onclick' ) + // #188 '="CKEDITOR.tools.callFunction(', this._.getClick(), ',\'', value, '\'); return false;"', ' role="option"' + ' aria-posinset="' + ++this._.size + '">', html || value, '</a>' + '</li>' ); }, startGroup : function( title ) { this._.close(); var id = CKEDITOR.tools.getNextId(); this._.groups[ title ] = id; this._.pendingHtml.push( '<h1 role="presentation" id=', id, ' class=cke_panel_grouptitle>', title, '</h1>' ); }, commit : function() { this._.close(); this.element.appendHtml( this._.pendingHtml.join( '' ) ); var items = this._.items, doc = this.element.getDocument(); for ( var value in items ) doc.getById( items[ value ] + '_option' ).setAttribute( 'aria-setsize', this._.size ); delete this._.size; this._.pendingHtml = []; }, toggle : function( value ) { var isMarked = this.isMarked( value ); if ( isMarked ) this.unmark( value ); else this.mark( value ); return !isMarked; }, hideGroup : function( groupTitle ) { var group = this.element.getDocument().getById( this._.groups[ groupTitle ] ), list = group && group.getNext(); if ( group ) { group.setStyle( 'display', 'none' ); if ( list && list.getName() == 'ul' ) list.setStyle( 'display', 'none' ); } }, hideItem : function( value ) { this.element.getDocument().getById( this._.items[ value ] ).setStyle( 'display', 'none' ); }, showAll : function() { var items = this._.items, groups = this._.groups, doc = this.element.getDocument(); for ( var value in items ) { doc.getById( items[ value ] ).setStyle( 'display', '' ); } for ( var title in groups ) { var group = doc.getById( groups[ title ] ), list = group.getNext(); group.setStyle( 'display', '' ); if ( list && list.getName() == 'ul' ) list.setStyle( 'display', '' ); } }, mark : function( value ) { if ( !this.multiSelect ) this.unmarkAll(); var itemId = this._.items[ value ], item = this.element.getDocument().getById( itemId ); item.addClass( 'cke_selected' ); this.element.getDocument().getById( itemId + '_option' ).setAttribute( 'aria-selected', true ); this.onMark && this.onMark( item ); }, unmark : function( value ) { var doc = this.element.getDocument(), itemId = this._.items[ value ], item = doc.getById( itemId ); item.removeClass( 'cke_selected' ); doc.getById( itemId + '_option' ).removeAttribute( 'aria-selected' ); this.onUnmark && this.onUnmark( item ); }, unmarkAll : function() { var items = this._.items, doc = this.element.getDocument(); for ( var value in items ) { var itemId = items[ value ]; doc.getById( itemId ).removeClass( 'cke_selected' ); doc.getById( itemId + '_option' ).removeAttribute( 'aria-selected' ); } this.onUnmark && this.onUnmark(); }, isMarked : function( value ) { return this.element.getDocument().getById( this._.items[ value ] ).hasClass( 'cke_selected' ); }, focus : function( value ) { this._.focusIndex = -1; if ( value ) { var selected = this.element.getDocument().getById( this._.items[ value ] ).getFirst(); var links = this.element.getElementsByTag( 'a' ), link, i = -1; while ( ( link = links.getItem( ++i ) ) ) { if ( link.equals( selected ) ) { this._.focusIndex = i; break; } } setTimeout( function() { selected.focus(); }, 0 ); } } } }); } });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @file Paste as plain text plugin */ (function() { // The pastetext command definition. var pasteTextCmd = { exec : function( editor ) { var clipboardText = CKEDITOR.tools.tryThese( function() { var clipboardText = window.clipboardData.getData( 'Text' ); if ( !clipboardText ) throw 0; return clipboardText; } // Any other approach that's working... ); if ( !clipboardText ) // Clipboard access privilege is not granted. { editor.openDialog( 'pastetext' ); return false; } else editor.fire( 'paste', { 'text' : clipboardText } ); return true; } }; // Register the plugin. CKEDITOR.plugins.add( 'pastetext', { init : function( editor ) { var commandName = 'pastetext', command = editor.addCommand( commandName, pasteTextCmd ); editor.ui.addButton( 'PasteText', { label : editor.lang.pasteText.button, command : commandName }); CKEDITOR.dialog.add( commandName, CKEDITOR.getUrl( this.path + 'dialogs/pastetext.js' ) ); if ( editor.config.forcePasteAsPlainText ) { // Intercept the default pasting process. editor.on( 'beforeCommandExec', function ( evt ) { var mode = evt.data.commandData; // Do NOT overwrite if HTML format is explicitly requested. if ( evt.data.name == 'paste' && mode != 'html' ) { editor.execCommand( 'pastetext' ); evt.cancel(); } }, null, null, 0 ); editor.on( 'beforePaste', function( evt ) { evt.data.mode = 'text'; }); } editor.on( 'pasteState', function( evt ) { editor.getCommand( 'pastetext' ).setState( evt.data ); }); }, requires : [ 'clipboard' ] }); })(); /** * Whether to force all pasting operations to insert on plain text into the * editor, loosing any formatting information possibly available in the source * text. * <strong>Note:</strong> paste from word is not affected by this configuration. * @name CKEDITOR.config.forcePasteAsPlainText * @type Boolean * @default false * @example * config.forcePasteAsPlainText = true; */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { CKEDITOR.dialog.add( 'pastetext', function( editor ) { return { title : editor.lang.pasteText.title, minWidth : CKEDITOR.env.ie && CKEDITOR.env.quirks ? 368 : 350, minHeight : 240, onShow : function(){ this.setupContent(); }, onOk : function(){ this.commitContent(); }, contents : [ { label : editor.lang.common.generalTab, id : 'general', elements : [ { type : 'html', id : 'pasteMsg', html : '<div style="white-space:normal;width:340px;">' + editor.lang.clipboard.pasteMsg + '</div>' }, { type : 'textarea', id : 'content', className : 'cke_pastetext', onLoad : function() { var label = this.getDialog().getContentElement( 'general', 'pasteMsg' ).getElement(), input = this.getElement().getElementsByTag( 'textarea' ).getItem( 0 ); input.setAttribute( 'aria-labelledby', label.$.id ); input.setStyle( 'direction', editor.config.contentsLangDirection ); }, focus : function() { this.getElement().focus(); }, setup : function() { this.setValue( '' ); }, commit : function() { var value = this.getValue(); setTimeout( function() { editor.fire( 'paste', { 'text' : value } ); }, 0 ); } } ] } ] }; }); })();
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { var pxUnit = CKEDITOR.tools.cssLength, needsIEHacks = CKEDITOR.env.ie && ( CKEDITOR.env.ie7Compat || CKEDITOR.env.quirks || CKEDITOR.env.version < 7 ); function getWidth( el ) { return CKEDITOR.env.ie ? el.$.clientWidth : parseInt( el.getComputedStyle( 'width' ), 10 ); } function getBorderWidth( element, side ) { var computed = element.getComputedStyle( 'border-' + side + '-width' ), borderMap = { thin: '0px', medium: '1px', thick: '2px' }; if ( computed.indexOf( 'px' ) < 0 ) { // look up keywords if ( computed in borderMap && element.getComputedStyle( 'border-style' ) != 'none' ) computed = borderMap[ computed ]; else computed = 0; } return parseInt( computed, 10 ); } // Gets the table row that contains the most columns. function getMasterPillarRow( table ) { var $rows = table.$.rows, maxCells = 0, cellsCount, $elected, $tr; for ( var i = 0, len = $rows.length ; i < len; i++ ) { $tr = $rows[ i ]; cellsCount = $tr.cells.length; if ( cellsCount > maxCells ) { maxCells = cellsCount; $elected = $tr; } } return $elected; } function buildTableColumnPillars( table ) { var pillars = [], pillarIndex = -1, rtl = ( table.getComputedStyle( 'direction' ) == 'rtl' ); // Get the raw row element that cointains the most columns. var $tr = getMasterPillarRow( table ); // Get the tbody element and position, which will be used to set the // top and bottom boundaries. var tbody = new CKEDITOR.dom.element( table.$.tBodies[ 0 ] ), tbodyPosition = tbody.getDocumentPosition(); // Loop thorugh all cells, building pillars after each one of them. for ( var i = 0, len = $tr.cells.length ; i < len ; i++ ) { // Both the current cell and the successive one will be used in the // pillar size calculation. var td = new CKEDITOR.dom.element( $tr.cells[ i ] ), nextTd = $tr.cells[ i + 1 ] && new CKEDITOR.dom.element( $tr.cells[ i + 1 ] ); pillarIndex += td.$.colSpan || 1; // Calculate the pillar boundary positions. var pillarLeft, pillarRight, pillarWidth; var x = td.getDocumentPosition().x; // Calculate positions based on the current cell. rtl ? pillarRight = x + getBorderWidth( td, 'left' ) : pillarLeft = x + td.$.offsetWidth - getBorderWidth( td, 'right' ); // Calculate positions based on the next cell, if available. if ( nextTd ) { x = nextTd.getDocumentPosition().x; rtl ? pillarLeft = x + nextTd.$.offsetWidth - getBorderWidth( nextTd, 'right' ) : pillarRight = x + getBorderWidth( nextTd, 'left' ); } // Otherwise calculate positions based on the table (for last cell). else { x = table.getDocumentPosition().x; rtl ? pillarLeft = x : pillarRight = x + table.$.offsetWidth; } pillarWidth = Math.max( pillarRight - pillarLeft, 3 ); // The pillar should reflects exactly the shape of the hovered // column border line. pillars.push( { table : table, index : pillarIndex, x : pillarLeft, y : tbodyPosition.y, width : pillarWidth, height : tbody.$.offsetHeight, rtl : rtl } ); } return pillars; } function getPillarAtPosition( pillars, positionX ) { for ( var i = 0, len = pillars.length ; i < len ; i++ ) { var pillar = pillars[ i ]; if ( positionX >= pillar.x && positionX <= ( pillar.x + pillar.width ) ) return pillar; } return null; } function cancel( evt ) { ( evt.data || evt ).preventDefault(); } function columnResizer( editor ) { var pillar, document, resizer, isResizing, startOffset, currentShift; var leftSideCells, rightSideCells, leftShiftBoundary, rightShiftBoundary; function detach() { pillar = null; currentShift = 0; isResizing = 0; document.removeListener( 'mouseup', onMouseUp ); resizer.removeListener( 'mousedown', onMouseDown ); resizer.removeListener( 'mousemove', onMouseMove ); document.getBody().setStyle( 'cursor', 'auto' ); // Hide the resizer (remove it on IE7 - #5890). needsIEHacks ? resizer.remove() : resizer.hide(); } function resizeStart() { // Before starting to resize, figure out which cells to change // and the boundaries of this resizing shift. var columnIndex = pillar.index, map = CKEDITOR.tools.buildTableMap( pillar.table ), leftColumnCells = [], rightColumnCells = [], leftMinSize = Number.MAX_VALUE, rightMinSize = leftMinSize, rtl = pillar.rtl; for ( var i = 0, len = map.length ; i < len ; i++ ) { var row = map[ i ], leftCell = row[ columnIndex + ( rtl ? 1 : 0 ) ], rightCell = row[ columnIndex + ( rtl ? 0 : 1 ) ]; leftCell = leftCell && new CKEDITOR.dom.element( leftCell ); rightCell = rightCell && new CKEDITOR.dom.element( rightCell ); if ( !leftCell || !rightCell || !leftCell.equals( rightCell ) ) { leftCell && ( leftMinSize = Math.min( leftMinSize, getWidth( leftCell ) ) ); rightCell && ( rightMinSize = Math.min( rightMinSize, getWidth( rightCell ) ) ); leftColumnCells.push( leftCell ); rightColumnCells.push( rightCell ); } } // Cache the list of cells to be resized. leftSideCells = leftColumnCells; rightSideCells = rightColumnCells; // Cache the resize limit boundaries. leftShiftBoundary = pillar.x - leftMinSize; rightShiftBoundary = pillar.x + rightMinSize; resizer.setOpacity( 0.5 ); startOffset = parseInt( resizer.getStyle( 'left' ), 10 ); currentShift = 0; isResizing = 1; resizer.on( 'mousemove', onMouseMove ); // Prevent the native drag behavior otherwise 'mousemove' won't fire. document.on( 'dragstart', cancel ); } function resizeEnd() { isResizing = 0; resizer.setOpacity( 0 ); currentShift && resizeColumn(); var table = pillar.table; setTimeout( function () { table.removeCustomData( '_cke_table_pillars' ); }, 0 ); document.removeListener( 'dragstart', cancel ); } function resizeColumn() { var rtl = pillar.rtl, cellsCount = rtl ? rightSideCells.length : leftSideCells.length; // Perform the actual resize to table cells, only for those by side of the pillar. for ( var i = 0 ; i < cellsCount ; i++ ) { var leftCell = leftSideCells[ i ], rightCell = rightSideCells[ i ], table = pillar.table; // Defer the resizing to avoid any interference among cells. CKEDITOR.tools.setTimeout( function( leftCell, leftOldWidth, rightCell, rightOldWidth, tableWidth, sizeShift ) { leftCell && leftCell.setStyle( 'width', pxUnit( Math.max( leftOldWidth + sizeShift, 0 ) ) ); rightCell && rightCell.setStyle( 'width', pxUnit( Math.max( rightOldWidth - sizeShift, 0 ) ) ); // If we're in the last cell, we need to resize the table as well if ( tableWidth ) table.setStyle( 'width', pxUnit( tableWidth + sizeShift * ( rtl ? -1 : 1 ) ) ); } , 0, this, [ leftCell, leftCell && getWidth( leftCell ), rightCell, rightCell && getWidth( rightCell ), ( !leftCell || !rightCell ) && ( getWidth( table ) + getBorderWidth( table, 'left' ) + getBorderWidth( table, 'right' ) ), currentShift ] ); } } function onMouseDown( evt ) { cancel( evt ); resizeStart(); document.on( 'mouseup', onMouseUp, this ); } function onMouseUp( evt ) { evt.removeListener(); resizeEnd(); } function onMouseMove( evt ) { move( evt.data.$.clientX ); } document = editor.document; resizer = CKEDITOR.dom.element.createFromHtml( '<div data-cke-temp=1 contenteditable=false unselectable=on '+ 'style="position:absolute;cursor:col-resize;filter:alpha(opacity=0);opacity:0;' + 'padding:0;background-color:#004;background-image:none;border:0px none;z-index:10"></div>', document ); // Except on IE6/7 (#5890), place the resizer after body to prevent it // from being editable. if ( !needsIEHacks ) document.getDocumentElement().append( resizer ); this.attachTo = function( targetPillar ) { // Accept only one pillar at a time. if ( isResizing ) return; // On IE6/7, we append the resizer everytime we need it. (#5890) if ( needsIEHacks ) { document.getBody().append( resizer ); currentShift = 0; } pillar = targetPillar; resizer.setStyles( { width: pxUnit( targetPillar.width ), height : pxUnit( targetPillar.height ), left : pxUnit( targetPillar.x ), top : pxUnit( targetPillar.y ) }); // In IE6/7, it's not possible to have custom cursors for floating // elements in an editable document. Show the resizer in that case, // to give the user a visual clue. needsIEHacks && resizer.setOpacity( 0.25 ); resizer.on( 'mousedown', onMouseDown, this ); document.getBody().setStyle( 'cursor', 'col-resize' ); // Display the resizer to receive events but don't show it, // only change the cursor to resizable shape. resizer.show(); }; var move = this.move = function( posX ) { if ( !pillar ) return 0; if ( !isResizing && ( posX < pillar.x || posX > ( pillar.x + pillar.width ) ) ) { detach(); return 0; } var resizerNewPosition = posX - Math.round( resizer.$.offsetWidth / 2 ); if ( isResizing ) { if ( resizerNewPosition == leftShiftBoundary || resizerNewPosition == rightShiftBoundary ) return 1; resizerNewPosition = Math.max( resizerNewPosition, leftShiftBoundary ); resizerNewPosition = Math.min( resizerNewPosition, rightShiftBoundary ); currentShift = resizerNewPosition - startOffset; } resizer.setStyle( 'left', pxUnit( resizerNewPosition ) ); return 1; }; } function clearPillarsCache( evt ) { var target = evt.data.getTarget(); if ( evt.name == 'mouseout' ) { // Bypass interal mouse move. if ( !target.is ( 'table' ) ) return; var dest = new CKEDITOR.dom.element( evt.data.$.relatedTarget || evt.data.$.toElement ); while( dest && dest.$ && !dest.equals( target ) && !dest.is( 'body' ) ) dest = dest.getParent(); if ( !dest || dest.equals( target ) ) return; } target.getAscendant( 'table', 1 ).removeCustomData( '_cke_table_pillars' ); evt.removeListener(); } CKEDITOR.plugins.add( 'tableresize', { requires : [ 'tabletools' ], init : function( editor ) { editor.on( 'contentDom', function() { var resizer; editor.document.getBody().on( 'mousemove', function( evt ) { evt = evt.data; // If we're already attached to a pillar, simply move the // resizer. if ( resizer && resizer.move( evt.$.clientX ) ) { cancel( evt ); return; } // Considering table, tr, td, tbody but nothing else. var target = evt.getTarget(), table, pillars; if ( !target.is( 'table' ) && !target.getAscendant( 'tbody', 1 ) ) return; table = target.getAscendant( 'table', 1 ); if ( !( pillars = table.getCustomData( '_cke_table_pillars' ) ) ) { // Cache table pillars calculation result. table.setCustomData( '_cke_table_pillars', ( pillars = buildTableColumnPillars( table ) ) ); table.on( 'mouseout', clearPillarsCache ); table.on( 'mousedown', clearPillarsCache ); } var pillar = getPillarAtPosition( pillars, evt.$.clientX ); if ( pillar ) { !resizer && ( resizer = new columnResizer( editor ) ); resizer.attachTo( pillar ); } }); }); } }); })();
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.add( 'resize', { init : function( editor ) { var config = editor.config; // Resize in the same direction of chrome, // which is identical to dir of editor element. (#6614) var resizeDir = editor.element.getDirection( 1 ); !config.resize_dir && ( config.resize_dir = 'both' ); ( config.resize_maxWidth == undefined ) && ( config.resize_maxWidth = 3000 ); ( config.resize_maxHeight == undefined ) && ( config.resize_maxHeight = 3000 ); ( config.resize_minWidth == undefined ) && ( config.resize_minWidth = 750 ); ( config.resize_minHeight == undefined ) && ( config.resize_minHeight = 250 ); if ( config.resize_enabled !== false ) { var container = null, origin, startSize, resizeHorizontal = ( config.resize_dir == 'both' || config.resize_dir == 'horizontal' ) && ( config.resize_minWidth != config.resize_maxWidth ), resizeVertical = ( config.resize_dir == 'both' || config.resize_dir == 'vertical' ) && ( config.resize_minHeight != config.resize_maxHeight ); function dragHandler( evt ) { var dx = evt.data.$.screenX - origin.x, dy = evt.data.$.screenY - origin.y, width = startSize.width, height = startSize.height, internalWidth = width + dx * ( resizeDir == 'rtl' ? -1 : 1 ), internalHeight = height + dy; if ( resizeHorizontal ) width = Math.max( config.resize_minWidth, Math.min( internalWidth, config.resize_maxWidth ) ); if ( resizeVertical ) height = Math.max( config.resize_minHeight, Math.min( internalHeight, config.resize_maxHeight ) ); editor.resize( width, height ); } function dragEndHandler ( evt ) { CKEDITOR.document.removeListener( 'mousemove', dragHandler ); CKEDITOR.document.removeListener( 'mouseup', dragEndHandler ); if ( editor.document ) { editor.document.removeListener( 'mousemove', dragHandler ); editor.document.removeListener( 'mouseup', dragEndHandler ); } } var mouseDownFn = CKEDITOR.tools.addFunction( function( $event ) { if ( !container ) container = editor.getResizable(); startSize = { width : container.$.offsetWidth || 0, height : container.$.offsetHeight || 0 }; origin = { x : $event.screenX, y : $event.screenY }; config.resize_minWidth > startSize.width && ( config.resize_minWidth = startSize.width ); config.resize_minHeight > startSize.height && ( config.resize_minHeight = startSize.height ); CKEDITOR.document.on( 'mousemove', dragHandler ); CKEDITOR.document.on( 'mouseup', dragEndHandler ); if ( editor.document ) { editor.document.on( 'mousemove', dragHandler ); editor.document.on( 'mouseup', dragEndHandler ); } }); editor.on( 'destroy', function() { CKEDITOR.tools.removeFunction( mouseDownFn ); } ); editor.on( 'themeSpace', function( event ) { if ( event.data.space == 'bottom' ) { var direction = ''; if ( resizeHorizontal && !resizeVertical ) direction = ' cke_resizer_horizontal'; if ( !resizeHorizontal && resizeVertical ) direction = ' cke_resizer_vertical'; var resizerHtml = '<div' + ' class="cke_resizer' + direction + ' cke_resizer_' + resizeDir + '"' + ' title="' + CKEDITOR.tools.htmlEncode( editor.lang.resize ) + '"' + ' onmousedown="CKEDITOR.tools.callFunction(' + mouseDownFn + ', event)"' + '></div>'; // Always sticks the corner of botttom space. resizeDir == 'ltr' && direction == 'ltr' ? event.data.html += resizerHtml : event.data.html = resizerHtml + event.data.html; } }, editor, null, 100 ); } } } ); /** * The minimum editor width, in pixels, when resizing the editor interface by using the resize handle. * Note: It falls back to editor's actual width if it is smaller than the default value. * @name CKEDITOR.config.resize_minWidth * @type Number * @default 750 * @example * config.resize_minWidth = 500; */ /** * The minimum editor height, in pixels, when resizing the editor interface by using the resize handle. * Note: It falls back to editor's actual height if it is smaller than the default value. * @name CKEDITOR.config.resize_minHeight * @type Number * @default 250 * @example * config.resize_minHeight = 600; */ /** * The maximum editor width, in pixels, when resizing the editor interface by using the resize handle. * @name CKEDITOR.config.resize_maxWidth * @type Number * @default 3000 * @example * config.resize_maxWidth = 750; */ /** * The maximum editor height, in pixels, when resizing the editor interface by using the resize handle. * @name CKEDITOR.config.resize_maxHeight * @type Number * @default 3000 * @example * config.resize_maxHeight = 600; */ /** * Whether to enable the resizing feature. If this feature is disabled, the resize handle will not be visible. * @name CKEDITOR.config.resize_enabled * @type Boolean * @default true * @example * config.resize_enabled = false; */ /** * The dimensions for which the editor resizing is enabled. Possible values * are <code>both</code>, <code>vertical</code>, and <code>horizontal</code>. * @name CKEDITOR.config.resize_dir * @type String * @default 'both' * @since 3.3 * @example * config.resize_dir = 'vertical'; */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview The "show border" plugin. The command display visible outline * border line around all table elements if table doesn't have a none-zero 'border' attribute specified. */ (function() { var showBorderClassName = 'cke_show_border', cssStyleText, cssTemplate = // TODO: For IE6, we don't have child selector support, // where nested table cells could be incorrect. ( CKEDITOR.env.ie6Compat ? [ '.%1 table.%2,', '.%1 table.%2 td, .%1 table.%2 th', '{', 'border : #d3d3d3 1px dotted', '}' ] : [ '.%1 table.%2,', '.%1 table.%2 > tr > td, .%1 table.%2 > tr > th,', '.%1 table.%2 > tbody > tr > td, .%1 table.%2 > tbody > tr > th,', '.%1 table.%2 > thead > tr > td, .%1 table.%2 > thead > tr > th,', '.%1 table.%2 > tfoot > tr > td, .%1 table.%2 > tfoot > tr > th', '{', 'border : #d3d3d3 1px dotted', '}' ] ).join( '' ); cssStyleText = cssTemplate.replace( /%2/g, showBorderClassName ).replace( /%1/g, 'cke_show_borders ' ); var commandDefinition = { preserveState : true, editorFocus : false, readOnly: 1, exec : function ( editor ) { this.toggleState(); this.refresh( editor ); }, refresh : function( editor ) { if ( editor.document ) { var funcName = ( this.state == CKEDITOR.TRISTATE_ON ) ? 'addClass' : 'removeClass'; editor.document.getBody()[ funcName ]( 'cke_show_borders' ); } } }; CKEDITOR.plugins.add( 'showborders', { requires : [ 'wysiwygarea' ], modes : { 'wysiwyg' : 1 }, init : function( editor ) { var command = editor.addCommand( 'showborders', commandDefinition ); command.canUndo = false; if ( editor.config.startupShowBorders !== false ) command.setState( CKEDITOR.TRISTATE_ON ); editor.addCss( cssStyleText ); // Refresh the command on setData. editor.on( 'mode', function() { if ( command.state != CKEDITOR.TRISTATE_DISABLED ) command.refresh( editor ); }, null, null, 100 ); // Refresh the command on wysiwyg frame reloads. editor.on( 'contentDom', function() { if ( command.state != CKEDITOR.TRISTATE_DISABLED ) command.refresh( editor ); }); editor.on( 'removeFormatCleanup', function( evt ) { var element = evt.data; if ( editor.getCommand( 'showborders' ).state == CKEDITOR.TRISTATE_ON && element.is( 'table' ) && ( !element.hasAttribute( 'border' ) || parseInt( element.getAttribute( 'border' ), 10 ) <= 0 ) ) element.addClass( showBorderClassName ); }); }, afterInit : function( editor ) { var dataProcessor = editor.dataProcessor, dataFilter = dataProcessor && dataProcessor.dataFilter, htmlFilter = dataProcessor && dataProcessor.htmlFilter; if ( dataFilter ) { dataFilter.addRules( { elements : { 'table' : function( element ) { var attributes = element.attributes, cssClass = attributes[ 'class' ], border = parseInt( attributes.border, 10 ); if ( ( !border || border <= 0 ) && ( !cssClass || cssClass.indexOf( showBorderClassName ) == -1 ) ) attributes[ 'class' ] = ( cssClass || '' ) + ' ' + showBorderClassName; } } } ); } if ( htmlFilter ) { htmlFilter.addRules( { elements : { 'table' : function( table ) { var attributes = table.attributes, cssClass = attributes[ 'class' ]; cssClass && ( attributes[ 'class' ] = cssClass.replace( showBorderClassName, '' ) .replace( /\s{2}/, ' ' ) .replace( /^\s+|\s+$/, '' ) ); } } } ); } } }); // Table dialog must be aware of it. CKEDITOR.on( 'dialogDefinition', function( ev ) { var dialogName = ev.data.name; if ( dialogName == 'table' || dialogName == 'tableProperties' ) { var dialogDefinition = ev.data.definition, infoTab = dialogDefinition.getContents( 'info' ), borderField = infoTab.get( 'txtBorder' ), originalCommit = borderField.commit; borderField.commit = CKEDITOR.tools.override( originalCommit, function( org ) { return function( data, selectedTable ) { org.apply( this, arguments ); var value = parseInt( this.getValue(), 10 ); selectedTable[ ( !value || value <= 0 ) ? 'addClass' : 'removeClass' ]( showBorderClassName ); }; } ); var advTab = dialogDefinition.getContents( 'advanced' ), classField = advTab && advTab.get( 'advCSSClasses' ); if ( classField ) { classField.setup = CKEDITOR.tools.override( classField.setup, function( originalSetup ) { return function() { originalSetup.apply( this, arguments ); this.setValue( this.getValue().replace( /cke_show_border/, '' ) ); }; }); classField.commit = CKEDITOR.tools.override( classField.commit, function( originalCommit ) { return function( data, element ) { originalCommit.apply( this, arguments ); if ( !parseInt( element.getAttribute( 'border' ), 10 ) ) element.addClass( 'cke_show_border' ); }; }); } } }); } )(); /** * Whether to automatically enable the "show borders" command when the editor loads. * (ShowBorders in FCKeditor) * @name CKEDITOR.config.startupShowBorders * @type Boolean * @default true * @example * config.startupShowBorders = false; */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { // Base HTML entities. var htmlbase = 'nbsp,gt,lt,amp'; var entities = // Latin-1 Entities 'quot,iexcl,cent,pound,curren,yen,brvbar,sect,uml,copy,ordf,laquo,' + 'not,shy,reg,macr,deg,plusmn,sup2,sup3,acute,micro,para,middot,' + 'cedil,sup1,ordm,raquo,frac14,frac12,frac34,iquest,times,divide,' + // Symbols 'fnof,bull,hellip,prime,Prime,oline,frasl,weierp,image,real,trade,' + 'alefsym,larr,uarr,rarr,darr,harr,crarr,lArr,uArr,rArr,dArr,hArr,' + 'forall,part,exist,empty,nabla,isin,notin,ni,prod,sum,minus,lowast,' + 'radic,prop,infin,ang,and,or,cap,cup,int,there4,sim,cong,asymp,ne,' + 'equiv,le,ge,sub,sup,nsub,sube,supe,oplus,otimes,perp,sdot,lceil,' + 'rceil,lfloor,rfloor,lang,rang,loz,spades,clubs,hearts,diams,' + // Other Special Characters 'circ,tilde,ensp,emsp,thinsp,zwnj,zwj,lrm,rlm,ndash,mdash,lsquo,' + 'rsquo,sbquo,ldquo,rdquo,bdquo,dagger,Dagger,permil,lsaquo,rsaquo,' + 'euro'; // Latin Letters Entities var latin = 'Agrave,Aacute,Acirc,Atilde,Auml,Aring,AElig,Ccedil,Egrave,Eacute,' + 'Ecirc,Euml,Igrave,Iacute,Icirc,Iuml,ETH,Ntilde,Ograve,Oacute,Ocirc,' + 'Otilde,Ouml,Oslash,Ugrave,Uacute,Ucirc,Uuml,Yacute,THORN,szlig,' + 'agrave,aacute,acirc,atilde,auml,aring,aelig,ccedil,egrave,eacute,' + 'ecirc,euml,igrave,iacute,icirc,iuml,eth,ntilde,ograve,oacute,ocirc,' + 'otilde,ouml,oslash,ugrave,uacute,ucirc,uuml,yacute,thorn,yuml,' + 'OElig,oelig,Scaron,scaron,Yuml'; // Greek Letters Entities. var greek = 'Alpha,Beta,Gamma,Delta,Epsilon,Zeta,Eta,Theta,Iota,Kappa,Lambda,Mu,' + 'Nu,Xi,Omicron,Pi,Rho,Sigma,Tau,Upsilon,Phi,Chi,Psi,Omega,alpha,' + 'beta,gamma,delta,epsilon,zeta,eta,theta,iota,kappa,lambda,mu,nu,xi,' + 'omicron,pi,rho,sigmaf,sigma,tau,upsilon,phi,chi,psi,omega,thetasym,' + 'upsih,piv'; /** * Create a mapping table between one character and its entity form from a list of entity names. * @param reverse {Boolean} Whether to create a reverse map from the entity string form to an actual character. */ function buildTable( entities, reverse ) { var table = {}, regex = []; // Entities that the browsers DOM don't transform to the final char // automatically. var specialTable = { nbsp : '\u00A0', // IE | FF shy : '\u00AD', // IE gt : '\u003E', // IE | FF | -- | Opera lt : '\u003C', // IE | FF | Safari | Opera amp : '\u0026' // ALL }; entities = entities.replace( /\b(nbsp|shy|gt|lt|amp)(?:,|$)/g, function( match, entity ) { var org = reverse ? '&' + entity + ';' : specialTable[ entity ], result = reverse ? specialTable[ entity ] : '&' + entity + ';'; table[ org ] = result; regex.push( org ); return ''; }); if ( !reverse && entities ) { // Transforms the entities string into an array. entities = entities.split( ',' ); // Put all entities inside a DOM element, transforming them to their // final chars. var div = document.createElement( 'div' ), chars; div.innerHTML = '&' + entities.join( ';&' ) + ';'; chars = div.innerHTML; div = null; // Add all chars to the table. for ( var i = 0 ; i < chars.length ; i++ ) { var charAt = chars.charAt( i ); table[ charAt ] = '&' + entities[ i ] + ';'; regex.push( charAt ); } } table.regex = regex.join( reverse ? '|' : '' ); return table; } CKEDITOR.plugins.add( 'entities', { afterInit : function( editor ) { var config = editor.config; var dataProcessor = editor.dataProcessor, htmlFilter = dataProcessor && dataProcessor.htmlFilter; if ( htmlFilter ) { // Mandatory HTML base entities. var selectedEntities = ''; if ( config.basicEntities !== false ) selectedEntities += htmlbase; if ( config.entities ) { selectedEntities += ',' + entities; if ( config.entities_latin ) selectedEntities += ',' + latin; if ( config.entities_greek ) selectedEntities += ',' + greek; if ( config.entities_additional ) selectedEntities += ',' + config.entities_additional; } var entitiesTable = buildTable( selectedEntities ); // Create the Regex used to find entities in the text, leave it matches nothing if entities are empty. var entitiesRegex = entitiesTable.regex ? '[' + entitiesTable.regex + ']' : 'a^'; delete entitiesTable.regex; if ( config.entities && config.entities_processNumerical ) entitiesRegex = '[^ -~]|' + entitiesRegex ; entitiesRegex = new RegExp( entitiesRegex, 'g' ); function getEntity( character ) { return config.entities_processNumerical == 'force' || !entitiesTable[ character ] ? '&#' + character.charCodeAt(0) + ';' : entitiesTable[ character ]; } // Decode entities that the browsers has transformed // at first place. var baseEntitiesTable = buildTable( [ htmlbase, 'shy' ].join( ',' ) , true ), baseEntitiesRegex = new RegExp( baseEntitiesTable.regex, 'g' ); function getChar( character ) { return baseEntitiesTable[ character ]; } htmlFilter.addRules( { text : function( text ) { return text.replace( baseEntitiesRegex, getChar ) .replace( entitiesRegex, getEntity ); } }); } } }); })(); /** * Whether to escape basic HTML entities in the document, including: * <ul> * <li><code>nbsp</code></li> * <li><code>gt</code></li> * <li><code>lt</code></li> * <li><code>amp</code></li> * </ul> * <strong>Note:</strong> It should not be subject to change unless when outputting a non-HTML data format like BBCode. * @type Boolean * @default <code>true</code> * @example * config.basicEntities = false; */ CKEDITOR.config.basicEntities = true; /** * Whether to use HTML entities in the output. * @name CKEDITOR.config.entities * @type Boolean * @default <code>true</code> * @example * config.entities = false; */ CKEDITOR.config.entities = true; /** * Whether to convert some Latin characters (Latin alphabet No&#46; 1, ISO 8859-1) * to HTML entities. The list of entities can be found in the * <a href="http://www.w3.org/TR/html4/sgml/entities.html#h-24.2.1">W3C HTML 4.01 Specification, section 24.2.1</a>. * @name CKEDITOR.config.entities_latin * @type Boolean * @default <code>true</code> * @example * config.entities_latin = false; */ CKEDITOR.config.entities_latin = true; /** * Whether to convert some symbols, mathematical symbols, and Greek letters to * HTML entities. This may be more relevant for users typing text written in Greek. * The list of entities can be found in the * <a href="http://www.w3.org/TR/html4/sgml/entities.html#h-24.3.1">W3C HTML 4.01 Specification, section 24.3.1</a>. * @name CKEDITOR.config.entities_greek * @type Boolean * @default <code>true</code> * @example * config.entities_greek = false; */ CKEDITOR.config.entities_greek = true; /** * Whether to convert all remaining characters not included in the ASCII * character table to their relative decimal numeric representation of HTML entity. * When set to <code>force</code>, it will convert all entities into this format. * For example the phrase "This is Chinese: &#27721;&#35821;." is output * as "This is Chinese: &amp;#27721;&amp;#35821;." * @name CKEDITOR.config.entities_processNumerical * @type Boolean|String * @default <code>false</code> * @example * config.entities_processNumerical = true; * config.entities_processNumerical = 'force'; //Converts from "&nbsp;" into "&#160;"; */ /** * A comma separated list of additional entities to be used. Entity names * or numbers must be used in a form that excludes the "&amp;" prefix and the ";" ending. * @name CKEDITOR.config.entities_additional * @default <code>'#39'</code> (The single quote (') character.) * @type String * @example * config.entities_additional = '#1049'; // Adds Cyrillic capital letter Short I (&#1049;). */ CKEDITOR.config.entities_additional = '#39';
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.add( 'docprops', { init : function( editor ) { var cmd = new CKEDITOR.dialogCommand( 'docProps' ); // Only applicable on full page mode. cmd.modes = { wysiwyg : editor.config.fullPage }; editor.addCommand( 'docProps', cmd ); CKEDITOR.dialog.add( 'docProps', this.path + 'dialogs/docprops.js' ); editor.ui.addButton( 'DocProps', { label : editor.lang.docprops.label, command : 'docProps' }); } });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'docProps', function( editor ) { var lang = editor.lang.docprops, langCommon = editor.lang.common, metaHash = {}; function getDialogValue( dialogName, callback ) { var onOk = function() { releaseHandlers( this ); callback( this, this._.parentDialog ); }; var releaseHandlers = function( dialog ) { dialog.removeListener( 'ok', onOk ); dialog.removeListener( 'cancel', releaseHandlers ); }; var bindToDialog = function( dialog ) { dialog.on( 'ok', onOk ); dialog.on( 'cancel', releaseHandlers ); }; editor.execCommand( dialogName ); if ( editor._.storedDialogs.colordialog ) bindToDialog( editor._.storedDialogs.colordialog ); else { CKEDITOR.on( 'dialogDefinition', function( e ) { if ( e.data.name != dialogName ) return; var definition = e.data.definition; e.removeListener(); definition.onLoad = CKEDITOR.tools.override( definition.onLoad, function( orginal ) { return function() { bindToDialog( this ); definition.onLoad = orginal; if ( typeof orginal == 'function' ) orginal.call( this ); }; }); }); } } function handleOther() { var dialog = this.getDialog(), other = dialog.getContentElement( 'general', this.id + 'Other' ); if ( !other ) return; if ( this.getValue() == 'other' ) { other.getInputElement().removeAttribute( 'readOnly' ); other.focus(); other.getElement().removeClass( 'cke_disabled' ); } else { other.getInputElement().setAttribute( 'readOnly', true ); other.getElement().addClass( 'cke_disabled' ); } } function commitMeta( name, isHttp, value ) { return function( doc, html, head ) { var hash = metaHash, val = typeof value != 'undefined' ? value : this.getValue(); if ( !val && ( name in hash ) ) hash[ name ].remove(); else if ( val && ( name in hash ) ) hash[ name ].setAttribute( 'content', val ); else if ( val ) { var meta = new CKEDITOR.dom.element( 'meta', editor.document ); meta.setAttribute( isHttp ? 'http-equiv' : 'name', name ); meta.setAttribute( 'content', val ); head.append( meta ); } }; } function setupMeta( name, ret ) { return function() { var hash = metaHash, result = ( name in hash ) ? hash[ name ].getAttribute( 'content' ) || '' : ''; if ( ret ) return result; this.setValue( result ); return null; }; } function commitMargin( name ) { return function( doc, html, head, body ) { body.removeAttribute( 'margin' + name ); var val = this.getValue(); if ( val !== '' ) body.setStyle( 'margin-' + name, CKEDITOR.tools.cssLength( val ) ); else body.removeStyle( 'margin-' + name ); }; } function createMetaHash( doc ) { var hash = {}, metas = doc.getElementsByTag( 'meta' ), count = metas.count(); for ( var i = 0; i < count; i++ ) { var meta = metas.getItem( i ); hash[ meta.getAttribute( meta.hasAttribute( 'http-equiv' ) ? 'http-equiv' : 'name' ).toLowerCase() ] = meta; } return hash; } // We cannot just remove the style from the element, as it might be affected from non-inline stylesheets. // To get the proper result, we should manually set the inline style to its default value. function resetStyle( element, prop, resetVal ) { element.removeStyle( prop ); if ( element.getComputedStyle( prop ) != resetVal ) element.setStyle( prop, resetVal ); } // Utilty to shorten the creation of color fields in the dialog. var colorField = function( id, label, fieldProps ) { return { type : 'hbox', padding : 0, widths : [ '60%', '40%' ], children : [ CKEDITOR.tools.extend( { type : 'text', id : id, label : lang[ label ] }, fieldProps || {}, 1 ), { type : 'button', id : id + 'Choose', label : lang.chooseColor, className : 'colorChooser', onClick : function() { var self = this; getDialogValue( 'colordialog', function( colorDialog ) { var dialog = self.getDialog(); dialog.getContentElement( dialog._.currentTabId, id ).setValue( colorDialog.getContentElement( 'picker', 'selectedColor' ).getValue() ); }); } } ] }; }; var previewSrc = 'javascript:' + 'void((function(){' + encodeURIComponent( 'document.open();' + ( CKEDITOR.env.isCustomDomain() ? 'document.domain=\'' + document.domain + '\';' : '' ) + 'document.write( \'<html style="background-color: #ffffff; height: 100%"><head></head><body style="width: 100%; height: 100%; margin: 0px">' + lang.previewHtml + '</body></html>\' );' + 'document.close();' ) + '})())'; return { title : lang.title, minHeight: 330, minWidth: 500, onShow : function() { var doc = editor.document, html = doc.getElementsByTag( 'html' ).getItem( 0 ), head = doc.getHead(), body = doc.getBody(); metaHash = createMetaHash( doc ); this.setupContent( doc, html, head, body ); }, onHide : function() { metaHash = {}; }, onOk : function() { var doc = editor.document, html = doc.getElementsByTag( 'html' ).getItem( 0 ), head = doc.getHead(), body = doc.getBody(); this.commitContent( doc, html, head, body ); }, contents : [ { id : 'general', label : langCommon.generalTab, elements : [ { type : 'text', id : 'title', label : lang.docTitle, setup : function( doc ) { this.setValue( doc.getElementsByTag( 'title' ).getItem( 0 ).data( 'cke-title' ) ); }, commit : function( doc, html, head, body, isPreview ) { if ( isPreview ) return; doc.getElementsByTag( 'title' ).getItem( 0 ).data( 'cke-title', this.getValue() ); } }, { type : 'hbox', children : [ { type : 'select', id : 'dir', label : langCommon.langDir, style : 'width: 100%', items : [ [ langCommon.notSet , '' ], [ langCommon.langDirLtr, 'ltr' ], [ langCommon.langDirRtl, 'rtl' ] ], setup : function( doc, html, head, body ) { this.setValue( body.getDirection() || '' ); }, commit : function( doc, html, head, body ) { var val = this.getValue(); if ( val ) body.setAttribute( 'dir', val ); else body.removeAttribute( 'dir' ); body.removeStyle( 'direction' ); } }, { type : 'text', id : 'langCode', label : langCommon.langCode, setup : function( doc, html ) { this.setValue( html.getAttribute( 'xml:lang' ) || html.getAttribute( 'lang' ) || '' ); }, commit : function( doc, html, head, body, isPreview ) { if ( isPreview ) return; var val = this.getValue(); if ( val ) html.setAttributes( { 'xml:lang' : val, lang : val } ); else html.removeAttributes( { 'xml:lang' : 1, lang : 1 } ); } } ] }, { type : 'hbox', children : [ { type : 'select', id : 'charset', label : lang.charset, style : 'width: 100%', items : [ [ langCommon.notSet, '' ], [ lang.charsetASCII, 'us-ascii' ], [ lang.charsetCE, 'iso-8859-2' ], [ lang.charsetCT, 'big5' ], [ lang.charsetCR, 'iso-8859-5' ], [ lang.charsetGR, 'iso-8859-7' ], [ lang.charsetJP, 'iso-2022-jp' ], [ lang.charsetKR, 'iso-2022-kr' ], [ lang.charsetTR, 'iso-8859-9' ], [ lang.charsetUN, 'utf-8' ], [ lang.charsetWE, 'iso-8859-1' ], [ lang.other, 'other' ] ], 'default' : '', onChange : function() { this.getDialog().selectedCharset = this.getValue() != 'other' ? this.getValue() : ''; handleOther.call( this ); }, setup : function() { this.metaCharset = ( 'charset' in metaHash ); var func = setupMeta( this.metaCharset ? 'charset' : 'content-type', 1, 1 ), val = func.call( this ); !this.metaCharset && val.match( /charset=[^=]+$/ ) && ( val = val.substring( val.indexOf( '=' ) + 1 ) ); if ( val ) { this.setValue( val.toLowerCase() ); if ( !this.getValue() ) { this.setValue( 'other' ); var other = this.getDialog().getContentElement( 'general', 'charsetOther' ); other && other.setValue( val ); } this.getDialog().selectedCharset = val; } handleOther.call( this ); }, commit : function( doc, html, head, body, isPreview ) { if ( isPreview ) return; var value = this.getValue(), other = this.getDialog().getContentElement( 'general', 'charsetOther' ); value == 'other' && ( value = other ? other.getValue() : '' ); value && !this.metaCharset && ( value = ( metaHash[ 'content-type' ] ? metaHash[ 'content-type' ].getAttribute( 'content' ).split( ';' )[0] : 'text/html' ) + '; charset=' + value ); var func = commitMeta( this.metaCharset ? 'charset' : 'content-type', 1, value ); func.call( this, doc, html, head ); } }, { type : 'text', id : 'charsetOther', label : lang.charsetOther, onChange : function(){ this.getDialog().selectedCharset = this.getValue(); } } ] }, { type : 'hbox', children : [ { type : 'select', id : 'docType', label : lang.docType, style : 'width: 100%', items : [ [ langCommon.notSet , '' ], [ 'XHTML 1.1', '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">' ], [ 'XHTML 1.0 Transitional', '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' ], [ 'XHTML 1.0 Strict', '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' ], [ 'XHTML 1.0 Frameset', '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">' ], [ 'HTML 5', '<!DOCTYPE html>' ], [ 'HTML 4.01 Transitional', '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">' ], [ 'HTML 4.01 Strict', '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' ], [ 'HTML 4.01 Frameset', '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">' ], [ 'HTML 3.2', '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">' ], [ 'HTML 2.0', '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">' ], [ lang.other, 'other' ] ], onChange : handleOther, setup : function() { if ( editor.docType ) { this.setValue( editor.docType ); if ( !this.getValue() ) { this.setValue( 'other' ); var other = this.getDialog().getContentElement( 'general', 'docTypeOther' ); other && other.setValue( editor.docType ); } } handleOther.call( this ); }, commit : function( doc, html, head, body, isPreview ) { if ( isPreview ) return; var value = this.getValue(), other = this.getDialog().getContentElement( 'general', 'docTypeOther' ); editor.docType = value == 'other' ? ( other ? other.getValue() : '' ) : value; } }, { type : 'text', id : 'docTypeOther', label : lang.docTypeOther } ] }, { type : 'checkbox', id : 'xhtmlDec', label : lang.xhtmlDec, setup : function() { this.setValue( !!editor.xmlDeclaration ); }, commit : function( doc, html, head, body, isPreview ) { if ( isPreview ) return; if ( this.getValue() ) { editor.xmlDeclaration = '<?xml version="1.0" encoding="' + ( this.getDialog().selectedCharset || 'utf-8' )+ '"?>' ; html.setAttribute( 'xmlns', 'http://www.w3.org/1999/xhtml' ); } else { editor.xmlDeclaration = ''; html.removeAttribute( 'xmlns' ); } } } ] }, { id : 'design', label : lang.design, elements : [ { type : 'hbox', widths : [ '60%', '40%' ], children : [ { type : 'vbox', children : [ colorField( 'txtColor', 'txtColor', { setup : function( doc, html, head, body ) { this.setValue( body.getComputedStyle( 'color' ) ); }, commit : function( doc, html, head, body, isPreview ) { if ( this.isChanged() || isPreview ) { body.removeAttribute( 'text' ); var val = this.getValue(); if ( val ) body.setStyle( 'color', val ); else body.removeStyle( 'color' ); } } }), colorField( 'bgColor', 'bgColor', { setup : function( doc, html, head, body ) { var val = body.getComputedStyle( 'background-color' ) || ''; this.setValue( val == 'transparent' ? '' : val ); }, commit : function( doc, html, head, body, isPreview ) { if ( this.isChanged() || isPreview ) { body.removeAttribute( 'bgcolor' ); var val = this.getValue(); if ( val ) body.setStyle( 'background-color', val ); else resetStyle( body, 'background-color', 'transparent' ); } } }), { type : 'hbox', widths : [ '60%', '40%' ], padding : 1, children : [ { type : 'text', id : 'bgImage', label : lang.bgImage, setup : function( doc, html, head, body ) { var val = body.getComputedStyle( 'background-image' ) || ''; if ( val == 'none' ) val = ''; else { val = val.replace( /url\(\s*(["']?)\s*([^\)]*)\s*\1\s*\)/i, function( match, quote, url ) { return url; }); } this.setValue( val ); }, commit : function( doc, html, head, body ) { body.removeAttribute( 'background' ); var val = this.getValue(); if ( val ) body.setStyle( 'background-image', 'url(' + val + ')' ); else resetStyle( body, 'background-image', 'none' ); } }, { type : 'button', id : 'bgImageChoose', label : langCommon.browseServer, style : 'display:inline-block;margin-top:10px;', hidden : true, filebrowser : 'design:bgImage' } ] }, { type : 'checkbox', id : 'bgFixed', label : lang.bgFixed, setup : function( doc, html, head, body ) { this.setValue( body.getComputedStyle( 'background-attachment' ) == 'fixed' ); }, commit : function( doc, html, head, body ) { if ( this.getValue() ) body.setStyle( 'background-attachment', 'fixed' ); else resetStyle( body, 'background-attachment', 'scroll' ); } } ] }, { type : 'vbox', children : [ { type : 'html', id : 'marginTitle', html : '<div style="text-align: center; margin: 0px auto; font-weight: bold">' + lang.margin + '</div>' }, { type : 'text', id : 'marginTop', label : lang.marginTop, style : 'width: 80px; text-align: center', align : 'center', inputStyle : 'text-align: center', setup : function( doc, html, head, body ) { this.setValue( body.getStyle( 'margin-top' ) || body.getAttribute( 'margintop' ) || '' ); }, commit : commitMargin( 'top' ) }, { type : 'hbox', children : [ { type : 'text', id : 'marginLeft', label : lang.marginLeft, style : 'width: 80px; text-align: center', align : 'center', inputStyle : 'text-align: center', setup : function( doc, html, head, body ) { this.setValue( body.getStyle( 'margin-left' ) || body.getAttribute( 'marginleft' ) || '' ); }, commit : commitMargin( 'left' ) }, { type : 'text', id : 'marginRight', label : lang.marginRight, style : 'width: 80px; text-align: center', align : 'center', inputStyle : 'text-align: center', setup : function( doc, html, head, body ) { this.setValue( body.getStyle( 'margin-right' ) || body.getAttribute( 'marginright' ) || '' ); }, commit : commitMargin( 'right' ) } ] }, { type : 'text', id : 'marginBottom', label : lang.marginBottom, style : 'width: 80px; text-align: center', align : 'center', inputStyle : 'text-align: center', setup : function( doc, html, head, body ) { this.setValue( body.getStyle( 'margin-bottom' ) || body.getAttribute( 'marginbottom' ) || '' ); }, commit : commitMargin( 'bottom' ) } ] } ] } ] }, { id : 'meta', label : lang.meta, elements : [ { type : 'textarea', id : 'metaKeywords', label : lang.metaKeywords, setup : setupMeta( 'keywords' ), commit : commitMeta( 'keywords' ) }, { type : 'textarea', id : 'metaDescription', label : lang.metaDescription, setup : setupMeta( 'description' ), commit : commitMeta( 'description' ) }, { type : 'text', id : 'metaAuthor', label : lang.metaAuthor, setup : setupMeta( 'author' ), commit : commitMeta( 'author' ) }, { type : 'text', id : 'metaCopyright', label : lang.metaCopyright, setup : setupMeta( 'copyright' ), commit : commitMeta( 'copyright' ) } ] }, { id : 'preview', label : langCommon.preview, elements : [ { type : 'html', id : 'previewHtml', html : '<iframe src="' + previewSrc + '" style="width: 100%; height: 310px" hidefocus="true" frameborder="0" ' + 'id="cke_docProps_preview_iframe"></iframe>', onLoad : function() { this.getDialog().on( 'selectPage', function( ev ) { if ( ev.data.page == 'preview' ) { var self = this; setTimeout( function() { var doc = CKEDITOR.document.getById( 'cke_docProps_preview_iframe' ).getFrameDocument(), html = doc.getElementsByTag( 'html' ).getItem( 0 ), head = doc.getHead(), body = doc.getBody(); self.commitContent( doc, html, head, body, 1 ); }, 50 ); } }); CKEDITOR.document.getById( 'cke_docProps_preview_iframe' ).getAscendant( 'table' ).setStyle( 'height', '100%' ); } } ] } ] }; });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Plugin definition for the a11yhelp, which provides a dialog * with accessibility related help. */ (function() { var pluginName = 'a11yhelp', commandName = 'a11yHelp'; CKEDITOR.plugins.add( pluginName, { // List of available localizations. availableLangs : { en:1, he:1 }, init : function( editor ) { var plugin = this; editor.addCommand( commandName, { exec : function() { var langCode = editor.langCode; langCode = plugin.availableLangs[ langCode ] ? langCode : 'en'; CKEDITOR.scriptLoader.load( CKEDITOR.getUrl( plugin.path + 'lang/' + langCode + '.js' ), function() { CKEDITOR.tools.extend( editor.lang, plugin.langEntries[ langCode ] ); editor.openDialog( commandName ); }); }, modes : { wysiwyg:1, source:1 }, readOnly : 1, canUndo : false }); CKEDITOR.dialog.add( commandName, this.path + 'dialogs/a11yhelp.js' ); } }); })();
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'a11yhelp', 'en', { accessibilityHelp : { title : 'Accessibility Instructions', contents : 'Help Contents. To close this dialog press ESC.', legend : [ { name : 'General', items : [ { name : 'Editor Toolbar', legend: 'Press ${toolbarFocus} to navigate to the toolbar. ' + 'Move to the next and previous toolbar group with TAB and SHIFT-TAB. ' + 'Move to the next and previous toolbar button with RIGHT ARROW or LEFT ARROW. ' + 'Press SPACE or ENTER to activate the toolbar button.' }, { name : 'Editor Dialog', legend : 'Inside a dialog, press TAB to navigate to next dialog field, press SHIFT + TAB to move to previous field, press ENTER to submit dialog, press ESC to cancel dialog. ' + 'For dialogs that have multiple tab pages, press ALT + F10 to navigate to tab-list. ' + 'Then move to next tab with TAB OR RIGTH ARROW. ' + 'Move to previous tab with SHIFT + TAB or LEFT ARROW. ' + 'Press SPACE or ENTER to select the tab page.' }, { name : 'Editor Context Menu', legend : 'Press ${contextMenu} or APPLICATION KEY to open context-menu. ' + 'Then move to next menu option with TAB or DOWN ARROW. ' + 'Move to previous option with SHIFT+TAB or UP ARROW. ' + 'Press SPACE or ENTER to select the menu option. ' + 'Open sub-menu of current option wtih SPACE or ENTER or RIGHT ARROW. ' + 'Go back to parent menu item with ESC or LEFT ARROW. ' + 'Close context menu with ESC.' }, { name : 'Editor List Box', legend : 'Inside a list-box, move to next list item with TAB OR DOWN ARROW. ' + 'Move to previous list item with SHIFT + TAB or UP ARROW. ' + 'Press SPACE or ENTER to select the list option. ' + 'Press ESC to close the list-box.' }, { name : 'Editor Element Path Bar', legend : 'Press ${elementsPathFocus} to navigate to the elements path bar. ' + 'Move to next element button with TAB or RIGHT ARROW. ' + 'Move to previous button with SHIFT+TAB or LEFT ARROW. ' + 'Press SPACE or ENTER to select the element in editor.' } ] }, { name : 'Commands', items : [ { name : ' Undo command', legend : 'Press ${undo}' }, { name : ' Redo command', legend : 'Press ${redo}' }, { name : ' Bold command', legend : 'Press ${bold}' }, { name : ' Italic command', legend : 'Press ${italic}' }, { name : ' Underline command', legend : 'Press ${underline}' }, { name : ' Link command', legend : 'Press ${link}' }, { name : ' Toolbar Collapse command', legend : 'Press ${toolbarCollapse}' }, { name : ' Accessibility Help', legend : 'Press ${a11yHelp}' } ] } ] } });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'a11yhelp', 'he', { accessibilityHelp : { title : 'הוראות נגישות', contents : 'הוראות נגישות. לסגירה לחץ אסקייפ (ESC).', legend : [ { name : 'כללי', items : [ { name : 'סרגל הכלים', legend: 'לחץ על ${toolbarFocus} כדי לנווט לסרגל הכלים. ' + 'עבור לכפתור הבא עם מקש הטאב (TAB) או חץ שמאלי. ' + 'עבור לכפתור הקודם עם מקש השיפט (SHIFT) + טאב (TAB) או חץ ימני. ' + 'לחץ רווח או אנטר (ENTER) כדי להפעיל את הכפתור הנבחר.' }, { name : 'דיאלוגים (חלונות תשאול)', legend : 'בתוך דיאלוג, לחץ טאב (TAB) כדי לנווט לשדה הבא, לחץ שיפט (SHIFT) + טאב (TAB) כדי לנווט לשדה הקודם, לחץ אנטר (ENTER) כדי לשלוח את הדיאלוג, לחץ אסקייפ (ESC) כדי לבטל. ' + 'בתוך דיאלוגים בעלי מספר טאבים (לשוניות), לחץ אלט (ALT) + F10 כדי לנווט לשורת הטאבים. ' + 'נווט לטאב הבא עם טאב (TAB) או חץ שמאלי. ' + 'עבור לטאב הקודם עם שיפט (SHIFT) + טאב (TAB) או חץ שמאלי. ' + 'לחץ רווח או אנטר (ENTER) כדי להיכנס לטאב.' }, { name : 'תפריט ההקשר (Context Menu)', legend : 'לחץ ${contextMenu} או APPLICATION KEYכדי לפתוח את תפריט ההקשר. ' + 'עבור לאפשרות הבאה עם טאב (TAB) או חץ למטה. ' + 'עבור לאפשרות הקודמת עם שיפט (SHIFT) + טאב (TAB) או חץ למעלה. ' + 'לחץ רווח או אנטר (ENTER) כדי לבחור את האפשרות. ' + 'פתח את תת התפריט (Sub-menu) של האפשרות הנוכחית עם רווח או אנטר (ENTER) או חץ שמאלי. ' + 'חזור לתפריט האב עם אסקייפ (ESC) או חץ שמאלי. ' + 'סגור את תפריט ההקשר עם אסקייפ (ESC).' }, { name : 'תפריטים צפים (List boxes)', legend : 'בתוך תפריט צף, עבור לפריט הבא עם טאב (TAB) או חץ למטה. ' + 'עבור לתפריט הקודם עם שיפט (SHIFT) + טאב (TAB) or חץ עליון. ' + 'Press SPACE or ENTER to select the list option. ' + 'Press ESC to close the list-box.' }, { name : 'עץ אלמנטים (Elements Path)', legend : 'לחץ ${elementsPathFocus} כדי לנווט לעץ האלמנטים. ' + 'עבור לפריט הבא עם טאב (TAB) או חץ ימני. ' + 'עבור לפריט הקודם עם שיפט (SHIFT) + טאב (TAB) או חץ שמאלי. ' + 'לחץ רווח או אנטר (ENTER) כדי לבחור את האלמנט בעורך.' } ] }, { name : 'פקודות', items : [ { name : ' ביטול צעד אחרון', legend : 'לחץ ${undo}' }, { name : ' חזרה על צעד אחרון', legend : 'לחץ ${redo}' }, { name : ' הדגשה', legend : 'לחץ ${bold}' }, { name : ' הטייה', legend : 'לחץ ${italic}' }, { name : ' הוספת קו תחתון', legend : 'לחץ ${underline}' }, { name : ' הוספת לינק', legend : 'לחץ ${link}' }, { name : ' כיווץ סרגל הכלים', legend : 'לחץ ${toolbarCollapse}' }, { name : ' הוראות נגישות', legend : 'לחץ ${a11yHelp}' } ] } ] } }); /* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'a11yhelp', 'he', { accessibilityHelp : { title : 'הוראות נגישות', contents : 'הוראות נגישות. לסגירה לחץ אסקייפ (ESC).', legend : [ { name : 'כללי', items : [ { name : 'סרגל הכלים', legend: 'לחץ על ${toolbarFocus} כדי לנווט לסרגל הכלים. ' + 'עבור לכפתור הבא עם מקש הטאב (TAB) או חץ שמאלי. ' + 'עבור לכפתור הקודם עם מקש השיפט (SHIFT) + טאב (TAB) או חץ ימני. ' + 'לחץ רווח או אנטר (ENTER) כדי להפעיל את הכפתור הנבחר.' }, { name : 'דיאלוגים (חלונות תשאול)', legend : 'בתוך דיאלוג, לחץ טאב (TAB) כדי לנווט לשדה הבא, לחץ שיפט (SHIFT) + טאב (TAB) כדי לנווט לשדה הקודם, לחץ אנטר (ENTER) כדי לשלוח את הדיאלוג, לחץ אסקייפ (ESC) כדי לבטל. ' + 'בתוך דיאלוגים בעלי מספר טאבים (לשוניות), לחץ אלט (ALT) + F10 כדי לנווט לשורת הטאבים. ' + 'נווט לטאב הבא עם טאב (TAB) או חץ שמאלי. ' + 'עבור לטאב הקודם עם שיפט (SHIFT) + טאב (TAB) או חץ שמאלי. ' + 'לחץ רווח או אנטר (ENTER) כדי להיכנס לטאב.' }, { name : 'תפריט ההקשר (Context Menu)', legend : 'לחץ ${contextMenu} או APPLICATION KEYכדי לפתוח את תפריט ההקשר. ' + 'עבור לאפשרות הבאה עם טאב (TAB) או חץ למטה. ' + 'עבור לאפשרות הקודמת עם שיפט (SHIFT) + טאב (TAB) או חץ למעלה. ' + 'לחץ רווח או אנטר (ENTER) כדי לבחור את האפשרות. ' + 'פתח את תת התפריט (Sub-menu) של האפשרות הנוכחית עם רווח או אנטר (ENTER) או חץ שמאלי. ' + 'חזור לתפריט האב עם אסקייפ (ESC) או חץ שמאלי. ' + 'סגור את תפריט ההקשר עם אסקייפ (ESC).' }, { name : 'תפריטים צפים (List boxes)', legend : 'בתוך תפריט צף, עבור לפריט הבא עם טאב (TAB) או חץ למטה. ' + 'עבור לתפריט הקודם עם שיפט (SHIFT) + טאב (TAB) or חץ עליון. ' + 'Press SPACE or ENTER to select the list option. ' + 'Press ESC to close the list-box.' }, { name : 'עץ אלמנטים (Elements Path)', legend : 'לחץ ${elementsPathFocus} כדי לנווט לעץ האלמנטים. ' + 'עבור לפריט הבא עם טאב (TAB) או חץ ימני. ' + 'עבור לפריט הקודם עם שיפט (SHIFT) + טאב (TAB) או חץ שמאלי. ' + 'לחץ רווח או אנטר (ENTER) כדי לבחור את האלמנט בעורך.' } ] }, { name : 'פקודות', items : [ { name : ' ביטול צעד אחרון', legend : 'לחץ ${undo}' }, { name : ' חזרה על צעד אחרון', legend : 'לחץ ${redo}' }, { name : ' הדגשה', legend : 'לחץ ${bold}' }, { name : ' הטייה', legend : 'לחץ ${italic}' }, { name : ' הוספת קו תחתון', legend : 'לחץ ${underline}' }, { name : ' הוספת לינק', legend : 'לחץ ${link}' }, { name : ' כיווץ סרגל הכלים', legend : 'לחץ ${toolbarCollapse}' }, { name : ' הוראות נגישות', legend : 'לחץ ${a11yHelp}' } ] } ] } });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'a11yHelp', function( editor ) { var lang = editor.lang.accessibilityHelp, id = CKEDITOR.tools.getNextId(); // CharCode <-> KeyChar. var keyMap = { 8 : "BACKSPACE", 9 : "TAB" , 13 : "ENTER" , 16 : "SHIFT" , 17 : "CTRL" , 18 : "ALT" , 19 : "PAUSE" , 20 : "CAPSLOCK" , 27 : "ESCAPE" , 33 : "PAGE UP" , 34 : "PAGE DOWN" , 35 : "END" , 36 : "HOME" , 37 : "LEFT ARROW" , 38 : "UP ARROW" , 39 : "RIGHT ARROW" , 40 : "DOWN ARROW" , 45 : "INSERT" , 46 : "DELETE" , 91 : "LEFT WINDOW KEY" , 92 : "RIGHT WINDOW KEY" , 93 : "SELECT KEY" , 96 : "NUMPAD 0" , 97 : "NUMPAD 1" , 98 : "NUMPAD 2" , 99 : "NUMPAD 3" , 100 : "NUMPAD 4" , 101 : "NUMPAD 5" , 102 : "NUMPAD 6" , 103 : "NUMPAD 7" , 104 : "NUMPAD 8" , 105 : "NUMPAD 9" , 106 : "MULTIPLY" , 107 : "ADD" , 109 : "SUBTRACT" , 110 : "DECIMAL POINT" , 111 : "DIVIDE" , 112 : "F1" , 113 : "F2" , 114 : "F3" , 115 : "F4" , 116 : "F5" , 117 : "F6" , 118 : "F7" , 119 : "F8" , 120 : "F9" , 121 : "F10" , 122 : "F11" , 123 : "F12" , 144 : "NUM LOCK" , 145 : "SCROLL LOCK" , 186 : "SEMI-COLON" , 187 : "EQUAL SIGN" , 188 : "COMMA" , 189 : "DASH" , 190 : "PERIOD" , 191 : "FORWARD SLASH" , 192 : "GRAVE ACCENT" , 219 : "OPEN BRACKET" , 220 : "BACK SLASH" , 221 : "CLOSE BRAKET" , 222 : "SINGLE QUOTE" }; // Modifier keys override. keyMap[ CKEDITOR.ALT ] = 'ALT'; keyMap[ CKEDITOR.SHIFT ] = 'SHIFT'; keyMap[ CKEDITOR.CTRL ] = 'CTRL'; // Sort in desc. var modifiers = [ CKEDITOR.ALT, CKEDITOR.SHIFT, CKEDITOR.CTRL ]; function representKeyStroke( keystroke ) { var quotient, modifier, presentation = []; for ( var i = 0; i < modifiers.length; i++ ) { modifier = modifiers[ i ]; quotient = keystroke / modifiers[ i ]; if ( quotient > 1 && quotient <= 2 ) { keystroke -= modifier; presentation.push( keyMap[ modifier ] ); } } presentation.push( keyMap[ keystroke ] || String.fromCharCode( keystroke ) ); return presentation.join( '+' ); } var variablesPattern = /\$\{(.*?)\}/g; function replaceVariables( match, name ) { var keystrokes = editor.config.keystrokes, definition, length = keystrokes.length; for ( var i = 0; i < length; i++ ) { definition = keystrokes[ i ]; if ( definition[ 1 ] == name ) break; } return representKeyStroke( definition[ 0 ] ); } // Create the help list directly from lang file entries. function buildHelpContents() { var pageTpl = '<div class="cke_accessibility_legend" role="document" aria-labelledby="' + id + '_arialbl" tabIndex="-1">%1</div>' + '<span id="' + id + '_arialbl" class="cke_voice_label">' + lang.contents + ' </span>', sectionTpl = '<h1>%1</h1><dl>%2</dl>', itemTpl = '<dt>%1</dt><dd>%2</dd>'; var pageHtml = [], sections = lang.legend, sectionLength = sections.length; for ( var i = 0; i < sectionLength; i++ ) { var section = sections[ i ], sectionHtml = [], items = section.items, itemsLength = items.length; for ( var j = 0; j < itemsLength; j++ ) { var item = items[ j ], itemHtml; itemHtml = itemTpl.replace( '%1', item.name ). replace( '%2', item.legend.replace( variablesPattern, replaceVariables ) ); sectionHtml.push( itemHtml ); } pageHtml.push( sectionTpl.replace( '%1', section.name ).replace( '%2', sectionHtml.join( '' ) ) ); } return pageTpl.replace( '%1', pageHtml.join( '' ) ); } return { title : lang.title, minWidth : 600, minHeight : 400, contents : [ { id : 'info', label : editor.lang.common.generalTab, expand : true, elements : [ { type : 'html', id : 'legends', style : 'white-space:normal;', focus : function() {}, html : buildHelpContents() + '<style type="text/css">' + '.cke_accessibility_legend' + '{' + 'width:600px;' + 'height:400px;' + 'padding-right:5px;' + 'overflow-y:auto;' + 'overflow-x:hidden;' + '}' + // Some adjustments are to be done for IE6 and Quirks to work "properly" (#5757) '.cke_browser_quirks .cke_accessibility_legend,' + '.cke_browser_ie6 .cke_accessibility_legend' + '{' + 'height:390px' + '}' + // Override non-wrapping white-space rule in reset css. '.cke_accessibility_legend *' + '{' + 'white-space:normal;' + '}' + '.cke_accessibility_legend h1' + '{' + 'font-size: 20px;' + 'border-bottom: 1px solid #AAA;' + 'margin: 5px 0px 15px;' + '}' + '.cke_accessibility_legend dl' + '{' + 'margin-left: 5px;' + '}' + '.cke_accessibility_legend dt' + '{' + 'font-size: 13px;' + 'font-weight: bold;' + '}' + '.cke_accessibility_legend dd' + '{' + 'margin:10px' + '}' + '</style>' } ] } ], buttons : [ CKEDITOR.dialog.cancelButton ] }; });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.add( 'richcombo', { requires : [ 'floatpanel', 'listblock', 'button' ], beforeInit : function( editor ) { editor.ui.addHandler( CKEDITOR.UI_RICHCOMBO, CKEDITOR.ui.richCombo.handler ); } }); /** * Button UI element. * @constant * @example */ CKEDITOR.UI_RICHCOMBO = 'richcombo'; CKEDITOR.ui.richCombo = CKEDITOR.tools.createClass( { $ : function( definition ) { // Copy all definition properties to this object. CKEDITOR.tools.extend( this, definition, // Set defaults. { title : definition.label, modes : { wysiwyg : 1 } }); // We don't want the panel definition in this object. var panelDefinition = this.panel || {}; delete this.panel; this.id = CKEDITOR.tools.getNextNumber(); this.document = ( panelDefinition && panelDefinition.parent && panelDefinition.parent.getDocument() ) || CKEDITOR.document; panelDefinition.className = ( panelDefinition.className || '' ) + ' cke_rcombopanel'; panelDefinition.block = { multiSelect : panelDefinition.multiSelect, attributes : panelDefinition.attributes }; this._ = { panelDefinition : panelDefinition, items : {}, state : CKEDITOR.TRISTATE_OFF }; }, statics : { handler : { create : function( definition ) { return new CKEDITOR.ui.richCombo( definition ); } } }, proto : { renderHtml : function( editor ) { var output = []; this.render( editor, output ); return output.join( '' ); }, /** * Renders the combo. * @param {CKEDITOR.editor} editor The editor instance which this button is * to be used by. * @param {Array} output The output array to which append the HTML relative * to this button. * @example */ render : function( editor, output ) { var env = CKEDITOR.env; var id = 'cke_' + this.id; var clickFn = CKEDITOR.tools.addFunction( function( $element ) { var _ = this._; if ( _.state == CKEDITOR.TRISTATE_DISABLED ) return; this.createPanel( editor ); if ( _.on ) { _.panel.hide(); return; } this.commit(); var value = this.getValue(); if ( value ) _.list.mark( value ); else _.list.unmarkAll(); _.panel.showBlock( this.id, new CKEDITOR.dom.element( $element ), 4 ); }, this ); var instance = { id : id, combo : this, focus : function() { var element = CKEDITOR.document.getById( id ).getChild( 1 ); element.focus(); }, clickFn : clickFn }; function updateState() { var state = this.modes[ editor.mode ] ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED; this.setState( editor.readOnly && !this.readOnly ? CKEDITOR.TRISTATE_DISABLED : state ); this.setValue( '' ); } editor.on( 'mode', updateState, this ); // If this combo is sensitive to readOnly state, update it accordingly. !this.readOnly && editor.on( 'readOnly', updateState, this); var keyDownFn = CKEDITOR.tools.addFunction( function( ev, element ) { ev = new CKEDITOR.dom.event( ev ); var keystroke = ev.getKeystroke(); switch ( keystroke ) { case 13 : // ENTER case 32 : // SPACE case 40 : // ARROW-DOWN // Show panel CKEDITOR.tools.callFunction( clickFn, element ); break; default : // Delegate the default behavior to toolbar button key handling. instance.onkey( instance, keystroke ); } // Avoid subsequent focus grab on editor document. ev.preventDefault(); }); var focusFn = CKEDITOR.tools.addFunction( function() { instance.onfocus && instance.onfocus(); } ); // For clean up instance.keyDownFn = keyDownFn; output.push( '<span class="cke_rcombo" role="presentation">', '<span id=', id ); if ( this.className ) output.push( ' class="', this.className, ' cke_off"'); output.push( ' role="presentation">', '<span id="' + id+ '_label" class=cke_label>', this.label, '</span>', '<a hidefocus=true title="', this.title, '" tabindex="-1"', env.gecko && env.version >= 10900 && !env.hc ? '' : ' href="javascript:void(\'' + this.label + '\')"', ' role="button" aria-labelledby="', id , '_label" aria-describedby="', id, '_text" aria-haspopup="true"' ); // Some browsers don't cancel key events in the keydown but in the // keypress. // TODO: Check if really needed for Gecko+Mac. if ( CKEDITOR.env.opera || ( CKEDITOR.env.gecko && CKEDITOR.env.mac ) ) { output.push( ' onkeypress="return false;"' ); } // With Firefox, we need to force it to redraw, otherwise it // will remain in the focus state. if ( CKEDITOR.env.gecko ) { output.push( ' onblur="this.style.cssText = this.style.cssText;"' ); } output.push( ' onkeydown="CKEDITOR.tools.callFunction( ', keyDownFn, ', event, this );"' + ' onfocus="return CKEDITOR.tools.callFunction(', focusFn, ', event);" ' + ( CKEDITOR.env.ie ? 'onclick="return false;" onmouseup' : 'onclick' ) + // #188 '="CKEDITOR.tools.callFunction(', clickFn, ', this); return false;">' + '<span>' + '<span id="' + id + '_text" class="cke_text cke_inline_label">' + this.label + '</span>' + '</span>' + '<span class=cke_openbutton><span class=cke_icon>' + ( CKEDITOR.env.hc ? '&#9660;' : CKEDITOR.env.air ? '&nbsp;' : '' ) + '</span></span>' + // BLACK DOWN-POINTING TRIANGLE '</a>' + '</span>' + '</span>' ); if ( this.onRender ) this.onRender(); return instance; }, createPanel : function( editor ) { if ( this._.panel ) return; var panelDefinition = this._.panelDefinition, panelBlockDefinition = this._.panelDefinition.block, panelParentElement = panelDefinition.parent || CKEDITOR.document.getBody(), panel = new CKEDITOR.ui.floatPanel( editor, panelParentElement, panelDefinition ), list = panel.addListBlock( this.id, panelBlockDefinition ), me = this; panel.onShow = function() { if ( me.className ) this.element.getFirst().addClass( me.className + '_panel' ); me.setState( CKEDITOR.TRISTATE_ON ); list.focus( !me.multiSelect && me.getValue() ); me._.on = 1; if ( me.onOpen ) me.onOpen(); }; panel.onHide = function( preventOnClose ) { if ( me.className ) this.element.getFirst().removeClass( me.className + '_panel' ); me.setState( me.modes && me.modes[ editor.mode ] ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED ); me._.on = 0; if ( !preventOnClose && me.onClose ) me.onClose(); }; panel.onEscape = function() { panel.hide(); }; list.onClick = function( value, marked ) { // Move the focus to the main windows, otherwise it will stay // into the floating panel, even if invisible, and Safari and // Opera will go a bit crazy. me.document.getWindow().focus(); if ( me.onClick ) me.onClick.call( me, value, marked ); if ( marked ) me.setValue( value, me._.items[ value ] ); else me.setValue( '' ); panel.hide( false ); }; this._.panel = panel; this._.list = list; panel.getBlock( this.id ).onHide = function() { me._.on = 0; me.setState( CKEDITOR.TRISTATE_OFF ); }; if ( this.init ) this.init(); }, setValue : function( value, text ) { this._.value = value; var textElement = this.document.getById( 'cke_' + this.id + '_text' ); if ( textElement ) { if ( !( value || text ) ) { text = this.label; textElement.addClass( 'cke_inline_label' ); } else textElement.removeClass( 'cke_inline_label' ); textElement.setHtml( typeof text != 'undefined' ? text : value ); } }, getValue : function() { return this._.value || ''; }, unmarkAll : function() { this._.list.unmarkAll(); }, mark : function( value ) { this._.list.mark( value ); }, hideItem : function( value ) { this._.list.hideItem( value ); }, hideGroup : function( groupTitle ) { this._.list.hideGroup( groupTitle ); }, showAll : function() { this._.list.showAll(); }, add : function( value, html, text ) { this._.items[ value ] = text || value; this._.list.add( value, html, text ); }, startGroup : function( title ) { this._.list.startGroup( title ); }, commit : function() { if ( !this._.committed ) { this._.list.commit(); this._.committed = 1; CKEDITOR.ui.fire( 'ready', this ); } this._.committed = 1; }, setState : function( state ) { if ( this._.state == state ) return; this.document.getById( 'cke_' + this.id ).setState( state ); this._.state = state; } } }); CKEDITOR.ui.prototype.addRichCombo = function( name, definition ) { this.add( name, CKEDITOR.UI_RICHCOMBO, definition ); };
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @file Print Plugin */ CKEDITOR.plugins.add( 'print', { init : function( editor ) { var pluginName = 'print'; // Register the command. var command = editor.addCommand( pluginName, CKEDITOR.plugins.print ); // Register the toolbar button. editor.ui.addButton( 'Print', { label : editor.lang.print, command : pluginName }); } } ); CKEDITOR.plugins.print = { exec : function( editor ) { if ( CKEDITOR.env.opera ) return; else if ( CKEDITOR.env.gecko ) editor.window.$.print(); else editor.document.$.execCommand( "Print" ); }, canUndo : false, readOnly : 1, modes : { wysiwyg : !( CKEDITOR.env.opera ) } // It is imposible to print the inner document in Opera. };
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.colordialog = { init : function( editor ) { editor.addCommand( 'colordialog', new CKEDITOR.dialogCommand( 'colordialog' ) ); CKEDITOR.dialog.add( 'colordialog', this.path + 'dialogs/colordialog.js' ); } }; CKEDITOR.plugins.add( 'colordialog', CKEDITOR.plugins.colordialog );
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'colordialog', function( editor ) { // Define some shorthands. var $el = CKEDITOR.dom.element, $doc = CKEDITOR.document, $tools = CKEDITOR.tools, lang = editor.lang.colordialog; // Reference the dialog. var dialog; var spacer = { type : 'html', html : '&nbsp;' }; function clearSelected() { $doc.getById( selHiColorId ).removeStyle( 'background-color' ); dialog.getContentElement( 'picker', 'selectedColor' ).setValue( '' ); } function updateSelected( evt ) { if ( ! ( evt instanceof CKEDITOR.dom.event ) ) evt = new CKEDITOR.dom.event( evt ); var target = evt.getTarget(), color; if ( target.getName() == 'a' && ( color = target.getChild( 0 ).getHtml() ) ) dialog.getContentElement( 'picker', 'selectedColor' ).setValue( color ); } function updateHighlight( event ) { if ( ! ( event instanceof CKEDITOR.dom.event ) ) event = event.data; var target = event.getTarget(), color; if ( target.getName() == 'a' && ( color = target.getChild( 0 ).getHtml() ) ) { $doc.getById( hicolorId ).setStyle( 'background-color', color ); $doc.getById( hicolorTextId ).setHtml( color ); } } function clearHighlight() { $doc.getById( hicolorId ).removeStyle( 'background-color' ); $doc.getById( hicolorTextId ).setHtml( '&nbsp;' ); } var onMouseout = $tools.addFunction( clearHighlight ), onClick = updateSelected, onClickHandler = CKEDITOR.tools.addFunction( onClick ), onFocus = updateHighlight, onBlur = clearHighlight; var onKeydownHandler = CKEDITOR.tools.addFunction( function( ev ) { ev = new CKEDITOR.dom.event( ev ); var element = ev.getTarget(); var relative, nodeToMove; var keystroke = ev.getKeystroke(), rtl = editor.lang.dir == 'rtl'; switch ( keystroke ) { // UP-ARROW case 38 : // relative is TR if ( ( relative = element.getParent().getParent().getPrevious() ) ) { nodeToMove = relative.getChild( [element.getParent().getIndex(), 0] ); nodeToMove.focus(); onBlur( ev, element ); onFocus( ev, nodeToMove ); } ev.preventDefault(); break; // DOWN-ARROW case 40 : // relative is TR if ( ( relative = element.getParent().getParent().getNext() ) ) { nodeToMove = relative.getChild( [ element.getParent().getIndex(), 0 ] ); if ( nodeToMove && nodeToMove.type == 1 ) { nodeToMove.focus(); onBlur( ev, element ); onFocus( ev, nodeToMove ); } } ev.preventDefault(); break; // SPACE // ENTER is already handled as onClick case 32 : onClick( ev ); ev.preventDefault(); break; // RIGHT-ARROW case rtl ? 37 : 39 : // relative is TD if ( ( relative = element.getParent().getNext() ) ) { nodeToMove = relative.getChild( 0 ); if ( nodeToMove.type == 1 ) { nodeToMove.focus(); onBlur( ev, element ); onFocus( ev, nodeToMove ); ev.preventDefault( true ); } else onBlur( null, element ); } // relative is TR else if ( ( relative = element.getParent().getParent().getNext() ) ) { nodeToMove = relative.getChild( [ 0, 0 ] ); if ( nodeToMove && nodeToMove.type == 1 ) { nodeToMove.focus(); onBlur( ev, element ); onFocus( ev, nodeToMove ); ev.preventDefault( true ); } else onBlur( null, element ); } break; // LEFT-ARROW case rtl ? 39 : 37 : // relative is TD if ( ( relative = element.getParent().getPrevious() ) ) { nodeToMove = relative.getChild( 0 ); nodeToMove.focus(); onBlur( ev, element ); onFocus( ev, nodeToMove ); ev.preventDefault( true ); } // relative is TR else if ( ( relative = element.getParent().getParent().getPrevious() ) ) { nodeToMove = relative.getLast().getChild( 0 ); nodeToMove.focus(); onBlur( ev, element ); onFocus( ev, nodeToMove ); ev.preventDefault( true ); } else onBlur( null, element ); break; default : // Do not stop not handled events. return; } }); function createColorTable() { // Create the base colors array. var aColors = [ '00', '33', '66', '99', 'cc', 'ff' ]; // This function combines two ranges of three values from the color array into a row. function appendColorRow( rangeA, rangeB ) { for ( var i = rangeA ; i < rangeA + 3 ; i++ ) { var row = table.$.insertRow( -1 ); for ( var j = rangeB ; j < rangeB + 3 ; j++ ) { for ( var n = 0 ; n < 6 ; n++ ) { appendColorCell( row, '#' + aColors[j] + aColors[n] + aColors[i] ); } } } } // This function create a single color cell in the color table. function appendColorCell( targetRow, color ) { var cell = new $el( targetRow.insertCell( -1 ) ); cell.setAttribute( 'class', 'ColorCell' ); cell.setStyle( 'background-color', color ); cell.setStyle( 'width', '15px' ); cell.setStyle( 'height', '15px' ); var index = cell.$.cellIndex + 1 + 18 * targetRow.rowIndex; cell.append( CKEDITOR.dom.element.createFromHtml( '<a href="javascript: void(0);" role="option"' + ' aria-posinset="' + index + '"' + ' aria-setsize="' + 13 * 18 + '"' + ' style="cursor: pointer;display:block;width:100%;height:100% " title="'+ CKEDITOR.tools.htmlEncode( color )+ '"' + ' onkeydown="CKEDITOR.tools.callFunction( ' + onKeydownHandler + ', event, this )"' + ' onclick="CKEDITOR.tools.callFunction(' + onClickHandler + ', event, this ); return false;"' + ' tabindex="-1"><span class="cke_voice_label">' + color + '</span>&nbsp;</a>', CKEDITOR.document ) ); } appendColorRow( 0, 0 ); appendColorRow( 3, 0 ); appendColorRow( 0, 3 ); appendColorRow( 3, 3 ); // Create the last row. var oRow = table.$.insertRow(-1) ; // Create the gray scale colors cells. for ( var n = 0 ; n < 6 ; n++ ) { appendColorCell( oRow, '#' + aColors[n] + aColors[n] + aColors[n] ) ; } // Fill the row with black cells. for ( var i = 0 ; i < 12 ; i++ ) { appendColorCell( oRow, '#000000' ) ; } } var table = new $el( 'table' ); createColorTable(); var html = table.getHtml(); var numbering = function( id ) { return CKEDITOR.tools.getNextId() + '_' + id; }, hicolorId = numbering( 'hicolor' ), hicolorTextId = numbering( 'hicolortext' ), selHiColorId = numbering( 'selhicolor' ), tableLabelId = numbering( 'color_table_label' ); return { title : lang.title, minWidth : 360, minHeight : 220, onLoad : function() { // Update reference. dialog = this; }, contents : [ { id : 'picker', label : lang.title, accessKey : 'I', elements : [ { type : 'hbox', padding : 0, widths : [ '70%', '10%', '30%' ], children : [ { type : 'html', html : '<table role="listbox" aria-labelledby="' + tableLabelId + '" onmouseout="CKEDITOR.tools.callFunction( ' + onMouseout + ' );">' + ( !CKEDITOR.env.webkit ? html : '' ) + '</table><span id="' + tableLabelId + '" class="cke_voice_label">' + lang.options +'</span>', onLoad : function() { var table = CKEDITOR.document.getById( this.domId ); table.on( 'mouseover', updateHighlight ); // In WebKit, the table content must be inserted after this event call (#6150) CKEDITOR.env.webkit && table.setHtml( html ); }, focus: function() { var firstColor = this.getElement().getElementsByTag( 'a' ).getItem( 0 ); firstColor.focus(); } }, spacer, { type : 'vbox', padding : 0, widths : [ '70%', '5%', '25%' ], children : [ { type : 'html', html : '<span>' + lang.highlight +'</span>\ <div id="' + hicolorId + '" style="border: 1px solid; height: 74px; width: 74px;"></div>\ <div id="' + hicolorTextId + '">&nbsp;</div><span>' + lang.selected + '</span>\ <div id="' + selHiColorId + '" style="border: 1px solid; height: 20px; width: 74px;"></div>' }, { type : 'text', label : lang.selected, labelStyle: 'display:none', id : 'selectedColor', style : 'width: 74px', onChange : function() { // Try to update color preview with new value. If fails, then set it no none. try { $doc.getById( selHiColorId ).setStyle( 'background-color', this.getValue() ); } catch ( e ) { clearSelected(); } } }, spacer, { type : 'button', id : 'clear', style : 'margin-top: 5px', label : lang.clear, onClick : clearSelected } ] } ] } ] } ] }; } );
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @file Justify commands. */ (function() { function getState( editor, path ) { var firstBlock = path.block || path.blockLimit; if ( !firstBlock || firstBlock.getName() == 'body' ) return CKEDITOR.TRISTATE_OFF; return ( getAlignment( firstBlock, editor.config.useComputedState ) == this.value ) ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF; } function getAlignment( element, useComputedState ) { useComputedState = useComputedState === undefined || useComputedState; var align; if ( useComputedState ) align = element.getComputedStyle( 'text-align' ); else { while ( !element.hasAttribute || !( element.hasAttribute( 'align' ) || element.getStyle( 'text-align' ) ) ) { var parent = element.getParent(); if ( !parent ) break; element = parent; } align = element.getStyle( 'text-align' ) || element.getAttribute( 'align' ) || ''; } align && ( align = align.replace( /-moz-|-webkit-|start|auto/i, '' ) ); !align && useComputedState && ( align = element.getComputedStyle( 'direction' ) == 'rtl' ? 'right' : 'left' ); return align; } function onSelectionChange( evt ) { if ( evt.editor.readOnly ) return; var command = evt.editor.getCommand( this.name ); command.state = getState.call( this, evt.editor, evt.data.path ); command.fire( 'state' ); } function justifyCommand( editor, name, value ) { this.name = name; this.value = value; var classes = editor.config.justifyClasses; if ( classes ) { switch ( value ) { case 'left' : this.cssClassName = classes[0]; break; case 'center' : this.cssClassName = classes[1]; break; case 'right' : this.cssClassName = classes[2]; break; case 'justify' : this.cssClassName = classes[3]; break; } this.cssClassRegex = new RegExp( '(?:^|\\s+)(?:' + classes.join( '|' ) + ')(?=$|\\s)' ); } } function onDirChanged( e ) { var editor = e.editor; var range = new CKEDITOR.dom.range( editor.document ); range.setStartBefore( e.data.node ); range.setEndAfter( e.data.node ); var walker = new CKEDITOR.dom.walker( range ), node; while ( ( node = walker.next() ) ) { if ( node.type == CKEDITOR.NODE_ELEMENT ) { // A child with the defined dir is to be ignored. if ( !node.equals( e.data.node ) && node.getDirection() ) { range.setStartAfter( node ); walker = new CKEDITOR.dom.walker( range ); continue; } // Switch the alignment. var classes = editor.config.justifyClasses; if ( classes ) { // The left align class. if ( node.hasClass( classes[ 0 ] ) ) { node.removeClass( classes[ 0 ] ); node.addClass( classes[ 2 ] ); } // The right align class. else if ( node.hasClass( classes[ 2 ] ) ) { node.removeClass( classes[ 2 ] ); node.addClass( classes[ 0 ] ); } } // Always switch CSS margins. var style = 'text-align'; var align = node.getStyle( style ); if ( align == 'left' ) node.setStyle( style, 'right' ); else if ( align == 'right' ) node.setStyle( style, 'left' ); } } } justifyCommand.prototype = { exec : function( editor ) { var selection = editor.getSelection(), enterMode = editor.config.enterMode; if ( !selection ) return; var bookmarks = selection.createBookmarks(), ranges = selection.getRanges( true ); var cssClassName = this.cssClassName, iterator, block; var useComputedState = editor.config.useComputedState; useComputedState = useComputedState === undefined || useComputedState; for ( var i = ranges.length - 1 ; i >= 0 ; i-- ) { iterator = ranges[ i ].createIterator(); iterator.enlargeBr = enterMode != CKEDITOR.ENTER_BR; while ( ( block = iterator.getNextParagraph( enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' ) ) ) { block.removeAttribute( 'align' ); block.removeStyle( 'text-align' ); // Remove any of the alignment classes from the className. var className = cssClassName && ( block.$.className = CKEDITOR.tools.ltrim( block.$.className.replace( this.cssClassRegex, '' ) ) ); var apply = ( this.state == CKEDITOR.TRISTATE_OFF ) && ( !useComputedState || ( getAlignment( block, true ) != this.value ) ); if ( cssClassName ) { // Append the desired class name. if ( apply ) block.addClass( cssClassName ); else if ( !className ) block.removeAttribute( 'class' ); } else if ( apply ) block.setStyle( 'text-align', this.value ); } } editor.focus(); editor.forceNextSelectionCheck(); selection.selectBookmarks( bookmarks ); } }; CKEDITOR.plugins.add( 'justify', { init : function( editor ) { var left = new justifyCommand( editor, 'justifyleft', 'left' ), center = new justifyCommand( editor, 'justifycenter', 'center' ), right = new justifyCommand( editor, 'justifyright', 'right' ), justify = new justifyCommand( editor, 'justifyblock', 'justify' ); editor.addCommand( 'justifyleft', left ); editor.addCommand( 'justifycenter', center ); editor.addCommand( 'justifyright', right ); editor.addCommand( 'justifyblock', justify ); editor.ui.addButton( 'JustifyLeft', { label : editor.lang.justify.left, command : 'justifyleft' } ); editor.ui.addButton( 'JustifyCenter', { label : editor.lang.justify.center, command : 'justifycenter' } ); editor.ui.addButton( 'JustifyRight', { label : editor.lang.justify.right, command : 'justifyright' } ); editor.ui.addButton( 'JustifyBlock', { label : editor.lang.justify.block, command : 'justifyblock' } ); editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, left ) ); editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, right ) ); editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, center ) ); editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, justify ) ); editor.on( 'dirChanged', onDirChanged ); }, requires : [ 'domiterator' ] }); })(); /** * List of classes to use for aligning the contents. If it's null, no classes will be used * and instead the corresponding CSS values will be used. The array should contain 4 members, in the following order: left, center, right, justify. * @name CKEDITOR.config.justifyClasses * @type Array * @default null * @example * // Use the classes 'AlignLeft', 'AlignCenter', 'AlignRight', 'AlignJustify' * config.justifyClasses = [ 'AlignLeft', 'AlignCenter', 'AlignRight', 'AlignJustify' ]; */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @name CKEDITOR.theme * @class */ CKEDITOR.themes.add( 'default', (function() { var hiddenSkins = {}; function checkSharedSpace( editor, spaceName ) { var container, element; // Try to retrieve the target element from the sharedSpaces settings. element = editor.config.sharedSpaces; element = element && element[ spaceName ]; element = element && CKEDITOR.document.getById( element ); // If the element is available, we'll then create the container for // the space. if ( element ) { // Creates an HTML structure that reproduces the editor class hierarchy. var html = '<span class="cke_shared "' + ' dir="'+ editor.lang.dir + '"' + '>' + '<span class="' + editor.skinClass + ' ' + editor.id + ' cke_editor_' + editor.name + '">' + '<span class="' + CKEDITOR.env.cssClass + '">' + '<span class="cke_wrapper cke_' + editor.lang.dir + '">' + '<span class="cke_editor">' + '<div class="cke_' + spaceName + '">' + '</div></span></span></span></span></span>'; var mainContainer = element.append( CKEDITOR.dom.element.createFromHtml( html, element.getDocument() ) ); // Only the first container starts visible. Others get hidden. if ( element.getCustomData( 'cke_hasshared' ) ) mainContainer.hide(); else element.setCustomData( 'cke_hasshared', 1 ); // Get the deeper inner <div>. container = mainContainer.getChild( [0,0,0,0] ); // Save a reference to the shared space container. !editor.sharedSpaces && ( editor.sharedSpaces = {} ); editor.sharedSpaces[ spaceName ] = container; // When the editor gets focus, we show the space container, hiding others. editor.on( 'focus', function() { for ( var i = 0, sibling, children = element.getChildren() ; ( sibling = children.getItem( i ) ) ; i++ ) { if ( sibling.type == CKEDITOR.NODE_ELEMENT && !sibling.equals( mainContainer ) && sibling.hasClass( 'cke_shared' ) ) { sibling.hide(); } } mainContainer.show(); }); editor.on( 'destroy', function() { mainContainer.remove(); }); } return container; } return /** @lends CKEDITOR.theme */ { build : function( editor, themePath ) { var name = editor.name, element = editor.element, elementMode = editor.elementMode; if ( !element || elementMode == CKEDITOR.ELEMENT_MODE_NONE ) return; if ( elementMode == CKEDITOR.ELEMENT_MODE_REPLACE ) element.hide(); // Get the HTML for the predefined spaces. var topHtml = editor.fire( 'themeSpace', { space : 'top', html : '' } ).html; var contentsHtml = editor.fire( 'themeSpace', { space : 'contents', html : '' } ).html; var bottomHtml = editor.fireOnce( 'themeSpace', { space : 'bottom', html : '' } ).html; var height = contentsHtml && editor.config.height; var tabIndex = editor.config.tabIndex || editor.element.getAttribute( 'tabindex' ) || 0; // The editor height is considered only if the contents space got filled. if ( !contentsHtml ) height = 'auto'; else if ( !isNaN( height ) ) height += 'px'; var style = ''; var width = editor.config.width; if ( width ) { if ( !isNaN( width ) ) width += 'px'; style += "width: " + width + ";"; } var sharedTop = topHtml && checkSharedSpace( editor, 'top' ), sharedBottoms = checkSharedSpace( editor, 'bottom' ); sharedTop && ( sharedTop.setHtml( topHtml ) , topHtml = '' ); sharedBottoms && ( sharedBottoms.setHtml( bottomHtml ), bottomHtml = '' ); var hideSkin = '<style>.' + editor.skinClass + '{visibility:hidden;}</style>'; if ( hiddenSkins[ editor.skinClass ] ) hideSkin = ''; else hiddenSkins[ editor.skinClass ] = 1; var container = CKEDITOR.dom.element.createFromHtml( [ '<span' + ' id="cke_', name, '"' + ' class="', editor.skinClass, ' ', editor.id, ' cke_editor_', name, '"' + ' dir="', editor.lang.dir, '"' + ' title="', ( CKEDITOR.env.gecko ? ' ' : '' ), '"' + ' lang="', editor.langCode, '"' + ( CKEDITOR.env.webkit? ' tabindex="' + tabIndex + '"' : '' ) + ' role="application"' + ' aria-labelledby="cke_', name, '_arialbl"' + ( style ? ' style="' + style + '"' : '' ) + '>' + '<span id="cke_', name, '_arialbl" class="cke_voice_label">' + editor.lang.editor + '</span>' + '<span class="' , CKEDITOR.env.cssClass, '" role="presentation">' + '<span class="cke_wrapper cke_', editor.lang.dir, '" role="presentation">' + '<table class="cke_editor" border="0" cellspacing="0" cellpadding="0" role="presentation"><tbody>' + '<tr', topHtml ? '' : ' style="display:none"', ' role="presentation"><td id="cke_top_' , name, '" class="cke_top" role="presentation">' , topHtml , '</td></tr>' + '<tr', contentsHtml ? '' : ' style="display:none"', ' role="presentation"><td id="cke_contents_', name, '" class="cke_contents" style="height:', height, '" role="presentation">', contentsHtml, '</td></tr>' + '<tr', bottomHtml ? '' : ' style="display:none"', ' role="presentation"><td id="cke_bottom_' , name, '" class="cke_bottom" role="presentation">' , bottomHtml , '</td></tr>' + '</tbody></table>' + //Hide the container when loading skins, later restored by skin css. hideSkin + '</span>' + '</span>' + '</span>' ].join( '' ) ); container.getChild( [1, 0, 0, 0, 0] ).unselectable(); container.getChild( [1, 0, 0, 0, 2] ).unselectable(); if ( elementMode == CKEDITOR.ELEMENT_MODE_REPLACE ) container.insertAfter( element ); else element.append( container ); /** * The DOM element that holds the main editor interface. * @name CKEDITOR.editor.prototype.container * @type CKEDITOR.dom.element * @example * var editor = CKEDITOR.instances.editor1; * alert( <b>editor.container</b>.getName() ); "span" */ editor.container = container; // Disable browser context menu for editor's chrome. container.disableContextMenu(); // Use a class to indicate that the current selection is in different direction than the UI. editor.on( 'contentDirChanged', function( evt ) { var func = ( editor.lang.dir != evt.data ? 'add' : 'remove' ) + 'Class'; container.getChild( 1 )[ func ]( 'cke_mixed_dir_content' ); // Put the mixed direction class on the respective element also for shared spaces. var toolbarSpace = this.sharedSpaces && this.sharedSpaces[ this.config.toolbarLocation ]; toolbarSpace && toolbarSpace.getParent().getParent()[ func ]( 'cke_mixed_dir_content' ); }); editor.fireOnce( 'themeLoaded' ); editor.fireOnce( 'uiReady' ); }, buildDialog : function( editor ) { var baseIdNumber = CKEDITOR.tools.getNextNumber(); var element = CKEDITOR.dom.element.createFromHtml( [ '<div class="', editor.id, '_dialog cke_editor_', editor.name.replace('.', '\\.'), '_dialog cke_skin_', editor.skinName, '" dir="', editor.lang.dir, '"' + ' lang="', editor.langCode, '"' + ' role="dialog"' + ' aria-labelledby="%title#"' + '>' + '<table class="cke_dialog', ' ' + CKEDITOR.env.cssClass, ' cke_', editor.lang.dir, '" style="position:absolute" role="presentation">' + '<tr><td role="presentation">' + '<div class="%body" role="presentation">' + '<div id="%title#" class="%title" role="presentation"></div>' + '<a id="%close_button#" class="%close_button" href="javascript:void(0)" title="' + editor.lang.common.close+'" role="button"><span class="cke_label">X</span></a>' + '<div id="%tabs#" class="%tabs" role="tablist"></div>' + '<table class="%contents" role="presentation">' + '<tr>' + '<td id="%contents#" class="%contents" role="presentation"></td>' + '</tr>' + '<tr>' + '<td id="%footer#" class="%footer" role="presentation"></td>' + '</tr>' + '</table>' + '</div>' + '<div id="%tl#" class="%tl"></div>' + '<div id="%tc#" class="%tc"></div>' + '<div id="%tr#" class="%tr"></div>' + '<div id="%ml#" class="%ml"></div>' + '<div id="%mr#" class="%mr"></div>' + '<div id="%bl#" class="%bl"></div>' + '<div id="%bc#" class="%bc"></div>' + '<div id="%br#" class="%br"></div>' + '</td></tr>' + '</table>', //Hide the container when loading skins, later restored by skin css. ( CKEDITOR.env.ie ? '' : '<style>.cke_dialog{visibility:hidden;}</style>' ), '</div>' ].join( '' ) .replace( /#/g, '_' + baseIdNumber ) .replace( /%/g, 'cke_dialog_' ) ); var body = element.getChild( [ 0, 0, 0, 0, 0 ] ), title = body.getChild( 0 ), close = body.getChild( 1 ); // IFrame shim for dialog that masks activeX in IE. (#7619) if ( CKEDITOR.env.ie && !CKEDITOR.env.ie6Compat ) { var isCustomDomain = CKEDITOR.env.isCustomDomain(), src = 'javascript:void(function(){' + encodeURIComponent( 'document.open();' + ( isCustomDomain ? ( 'document.domain="' + document.domain + '";' ) : '' ) + 'document.close();' ) + '}())', iframe = CKEDITOR.dom.element.createFromHtml( '<iframe' + ' frameBorder="0"' + ' class="cke_iframe_shim"' + ' src="' + src + '"' + ' tabIndex="-1"' + '></iframe>' ); iframe.appendTo( body.getParent() ); } // Make the Title and Close Button unselectable. title.unselectable(); close.unselectable(); return { element : element, parts : { dialog : element.getChild( 0 ), title : title, close : close, tabs : body.getChild( 2 ), contents : body.getChild( [ 3, 0, 0, 0 ] ), footer : body.getChild( [ 3, 0, 1, 0 ] ) } }; }, destroy : function( editor ) { var container = editor.container, element = editor.element; if ( container ) { container.clearCustomData(); container.remove(); } if ( element ) { element.clearCustomData(); editor.elementMode == CKEDITOR.ELEMENT_MODE_REPLACE && element.show(); delete editor.element; } } }; })() ); /** * Returns the DOM element that represents a theme space. The default theme defines * three spaces, namely "top", "contents" and "bottom", representing the main * blocks that compose the editor interface. * @param {String} spaceName The space name. * @returns {CKEDITOR.dom.element} The element that represents the space. * @example * // Hide the bottom space in the UI. * var bottom = editor.getThemeSpace( 'bottom' ); * bottom.setStyle( 'display', 'none' ); */ CKEDITOR.editor.prototype.getThemeSpace = function( spaceName ) { var spacePrefix = 'cke_' + spaceName; var space = this._[ spacePrefix ] || ( this._[ spacePrefix ] = CKEDITOR.document.getById( spacePrefix + '_' + this.name ) ); return space; }; /** * Resizes the editor interface. * @param {Number|String} width The new width. It can be an pixels integer or a * CSS size value. * @param {Number|String} height The new height. It can be an pixels integer or * a CSS size value. * @param {Boolean} [isContentHeight] Indicates that the provided height is to * be applied to the editor contents space, not to the entire editor * interface. Defaults to false. * @param {Boolean} [resizeInner] Indicates that the first inner interface * element must receive the size, not the outer element. The default theme * defines the interface inside a pair of span elements * (&lt;span&gt;&lt;span&gt;...&lt;/span&gt;&lt;/span&gt;). By default the * first span element receives the sizes. If this parameter is set to * true, the second span is sized instead. * @example * editor.resize( 900, 300 ); * @example * editor.resize( '100%', 450, true ); */ CKEDITOR.editor.prototype.resize = function( width, height, isContentHeight, resizeInner ) { var container = this.container, contents = CKEDITOR.document.getById( 'cke_contents_' + this.name ), contentsFrame = CKEDITOR.env.webkit && this.document && this.document.getWindow().$.frameElement, outer = resizeInner ? container.getChild( 1 ) : container; // Set as border box width. (#5353) outer.setSize( 'width', width, true ); // WebKit needs to refresh the iframe size to avoid rendering issues. (1/2) (#8348) contentsFrame && ( contentsFrame.style.width = '1%' ); // Get the height delta between the outer table and the content area. // If we're setting the content area's height, then we don't need the delta. var delta = isContentHeight ? 0 : ( outer.$.offsetHeight || 0 ) - ( contents.$.clientHeight || 0 ); contents.setStyle( 'height', Math.max( height - delta, 0 ) + 'px' ); // WebKit needs to refresh the iframe size to avoid rendering issues. (2/2) (#8348) contentsFrame && ( contentsFrame.style.width = '100%' ); // Emit a resize event. this.fire( 'resize' ); }; /** * Gets the element that can be freely used to check the editor size. This method * is mainly used by the resize plugin, which adds a UI handle that can be used * to resize the editor. * @param {Boolean} forContents Whether to return the "contents" part of the theme instead of the container. * @returns {CKEDITOR.dom.element} The resizable element. * @example */ CKEDITOR.editor.prototype.getResizable = function( forContents ) { return forContents ? CKEDITOR.document.getById( 'cke_contents_' + this.name ) : this.container; }; /** * Makes it possible to place some of the editor UI blocks, like the toolbar * and the elements path, into any element in the page. * The elements used to hold the UI blocks can be shared among several editor * instances. In that case, only the blocks of the active editor instance will * display. * @name CKEDITOR.config.sharedSpaces * @type Object * @default undefined * @example * // Place the toolbar inside the element with ID "someElementId" and the * // elements path into the element with ID "anotherId". * config.sharedSpaces = * { * top : 'someElementId', * bottom : 'anotherId' * }; * @example * // Place the toolbar inside the element with ID "someElementId". The * // elements path will remain attached to the editor UI. * config.sharedSpaces = * { * top : 'someElementId' * }; */ /** * Fired after the editor instance is resized through * the {@link CKEDITOR.editor.prototype.resize} method. * @name CKEDITOR.editor#resize * @event */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ // Compressed version of core/ckeditor_base.js. See original for instructions. /*jsl:ignore*/ if(!window.CKEDITOR)window.CKEDITOR=(function(){var a={timestamp:'',version:'3.6.2',revision:'7275',_:{},status:'unloaded',basePath:(function(){var d=window.CKEDITOR_BASEPATH||'';if(!d){var e=document.getElementsByTagName('script');for(var f=0;f<e.length;f++){var g=e[f].src.match(/(^|.*[\\\/])ckeditor(?:_basic)?(?:_source)?.js(?:\?.*)?$/i);if(g){d=g[1];break;}}}if(d.indexOf(':/')==-1)if(d.indexOf('/')===0)d=location.href.match(/^.*?:\/\/[^\/]*/)[0]+d;else d=location.href.match(/^[^\?]*\/(?:)/)[0]+d;return d;})(),getUrl:function(d){if(d.indexOf(':/')==-1&&d.indexOf('/')!==0)d=this.basePath+d;if(this.timestamp&&d.charAt(d.length-1)!='/')d+=(d.indexOf('?')>=0?'&':'?')+('t=')+this.timestamp;return d;}},b=window.CKEDITOR_GETURL;if(b){var c=a.getUrl;a.getUrl=function(d){return b.call(a,d)||c.call(a,d);};}return a;})(); /*jsl:end*/ // Uncomment the following line to have a new timestamp generated for each // request, having clear cache load of the editor code. // CKEDITOR.timestamp = ( new Date() ).valueOf(); if ( CKEDITOR.loader ) CKEDITOR.loader.load( 'core/ckeditor' ); else { // Set the script name to be loaded by the loader. CKEDITOR._autoLoad = 'core/ckeditor'; // Include the loader script. if ( document.body && (!document.readyState || document.readyState == 'complete') ) { var script = document.createElement( 'script' ); script.type = 'text/javascript'; script.src = CKEDITOR.getUrl( '_source/core/loader.js' ); document.body.appendChild( script ); } else { document.write( '<script type="text/javascript" src="' + CKEDITOR.getUrl( '_source/core/loader.js' ) + '"></script>' ); } }
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; };
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('placeholder','en',{placeholder:{title:'Placeholder Properties',toolbar:'Create Placeholder',text:'Placeholder Text',edit:'Edit Placeholder',textMissing:'The placeholder must contain text.'}});
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('placeholder','he',{placeholder:{title:'מאפייני שומר מקום',toolbar:'צור שומר מקום',text:'תוכן שומר המקום',edit:'ערוך שומר מקום',textMissing:'שומר המקום חייב להכיל טקסט.'}});
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('uicolor','he',{uicolor:{title:'בחירת צבע ממשק משתמש',preview:'תצוגה מקדימה',config:'הדבק את הטקסט הבא לתוך הקובץ config.js',predefined:'קבוצות צבעים מוגדרות מראש'}});
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('devtools','en',{devTools:{title:'Element Information',dialogName:'Dialog window name',tabName:'Tab name',elementId:'Element ID',elementType:'Element type'}});
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.add('docprops',{init:function(a){var b=new CKEDITOR.dialogCommand('docProps');b.modes={wysiwyg:a.config.fullPage};a.addCommand('docProps',b);CKEDITOR.dialog.add('docProps',this.path+'dialogs/docprops.js');a.ui.addButton('DocProps',{label:a.lang.docprops.label,command:'docProps'});}});
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ // Compressed version of core/ckeditor_base.js. See original for instructions. /*jsl:ignore*/ if(!window.CKEDITOR)window.CKEDITOR=(function(){var a={timestamp:'',version:'3.6.2',revision:'7275',_:{},status:'unloaded',basePath:(function(){var d=window.CKEDITOR_BASEPATH||'';if(!d){var e=document.getElementsByTagName('script');for(var f=0;f<e.length;f++){var g=e[f].src.match(/(^|.*[\\\/])ckeditor(?:_basic)?(?:_source)?.js(?:\?.*)?$/i);if(g){d=g[1];break;}}}if(d.indexOf(':/')==-1)if(d.indexOf('/')===0)d=location.href.match(/^.*?:\/\/[^\/]*/)[0]+d;else d=location.href.match(/^[^\?]*\/(?:)/)[0]+d;return d;})(),getUrl:function(d){if(d.indexOf(':/')==-1&&d.indexOf('/')!==0)d=this.basePath+d;if(this.timestamp&&d.charAt(d.length-1)!='/')d+=(d.indexOf('?')>=0?'&':'?')+('t=')+this.timestamp;return d;}},b=window.CKEDITOR_GETURL;if(b){var c=a.getUrl;a.getUrl=function(d){return b.call(a,d)||c.call(a,d);};}return a;})(); /*jsl:end*/ // Uncomment the following line to have a new timestamp generated for each // request, having clear cache load of the editor code. // CKEDITOR.timestamp = ( new Date() ).valueOf(); // Set the script name to be loaded by the loader. CKEDITOR._autoLoad = 'core/ckeditor_basic'; // Include the loader script. document.write( '<script type="text/javascript" src="' + CKEDITOR.getUrl( '_source/core/loader.js' ) + '"></script>' );
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'myDialog', function( editor ) { return { title : 'My Dialog', minWidth : 400, minHeight : 200, contents : [ { id : 'tab1', label : 'First Tab', title : 'First Tab', elements : [ { id : 'input1', type : 'text', label : 'Input 1' } ] } ] }; } );
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ // This file is not required by CKEditor and may be safely ignored. // It is just a helper file that displays a red message about browser compatibility // at the top of the samples (if incompatible browser is detected). if ( window.CKEDITOR ) { (function() { var showCompatibilityMsg = function() { var env = CKEDITOR.env; var html = '<p><strong>Your browser is not compatible with CKEditor.</strong>'; var browsers = { gecko : 'Firefox 2.0', ie : 'Internet Explorer 6.0', opera : 'Opera 9.5', webkit : 'Safari 3.0' }; var alsoBrowsers = ''; for ( var key in env ) { if ( browsers[ key ] ) { if ( env[key] ) html += ' CKEditor is compatible with ' + browsers[ key ] + ' or higher.'; else alsoBrowsers += browsers[ key ] + '+, '; } } alsoBrowsers = alsoBrowsers.replace( /\+,([^,]+), $/, '+ and $1' ); html += ' It is also compatible with ' + alsoBrowsers + '.'; html += '</p><p>With non compatible browsers, you should still be able to see and edit the contents (HTML) in a plain text field.</p>'; var alertsEl = document.getElementById( 'alerts' ); alertsEl && ( alertsEl.innerHTML = html ); }; var onload = function() { // Show a friendly compatibility message as soon as the page is loaded, // for those browsers that are not compatible with CKEditor. if ( !CKEDITOR.env.isCompatible ) showCompatibilityMsg(); }; // Register the onload listener. if ( window.addEventListener ) window.addEventListener( 'load', onload, false ); else if ( window.attachEvent ) window.attachEvent( 'onload', onload ); })(); }
JavaScript
var inlineedit_included = true; /* +-------------------------------------------------------------------------------+ | Copyright (c) 2006-2007 Andrew G. Samoilov, Alexey Kornilov | | Universal Data Solutions inc. | | All rights reserved. | | | | Redistribution and use in source and binary forms, with or without | | modification, are permitted provided that the following conditions | | are met: | | | | Redistributions of source code must retain the above copyright | | notice, this list of conditions and the following disclaimer. | | Redistributions in binary form must reproduce the above copyright | | notice, this list of conditions and the following disclaimer in the | | documentation and/or other materials provided with the distribution. | | | | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | +-------------------------------------------------------------------------------+ */ //var pics = new Array(); var timeoutID = 0; var gTop; var gLeft; var arrStates = new Array('AL', 'AK', 'AS', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FM', 'FL', 'GA', 'GU', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MH', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'MP', 'OH', 'OK', 'OR', 'PW', 'PA', 'PR', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VI', 'VA', 'WA', 'WV', 'WI', 'WY'); function updatesaveall() { if ($("a[@id^=save_]").length) { if ($("[@name=saveall_edited]").css("display") == "none") { $("[@name=saveall_edited]").css("display", "inline"); $("[@name=revertall_edited]").css("display", "inline"); if ($("[@name=edit_selected]").length) $("[@name=edit_selected]").css("display", "none"); } } else { if ($("[@name=saveall_edited]").css("display") != "none") { $("[@name=saveall_edited]").css("display", "none"); $("[@name=revertall_edited]").css("display", "none"); if ($("[@name=edit_selected]").length) $("[@name=edit_selected]").css("display", "inline"); } } $("#addmessage").hide(); } function inlineAdd(tempid) { if (!$(".addarea").length) return; $("[@name=maintable]").show(); $("[@name=notfound_message]").hide(); $("#record_controls").show(); var htext = ""; var hclass = ""; var hstyle = ""; var firstelement = $(".addarea")[0]; $(".addarea").each(function(i) { var row = $(this).clone(); $(row)[0].className = "addarea" + tempid; $("*", row).each(function(j) { if (this.id == "editlink_add") { this.id = "editlink" + tempid; $(this).hide(); } else if (this.id == "ieditlink_add") { this.id = "ieditlink" + tempid; hclass = $(this).attr("class"); hstyle = $(this).attr("style"); $(this).hide(); } else if (this.id == "copylink_add") { this.id = "copylink" + tempid; $(this).hide(); } else if (this.id == "check_add") { this.id = "check" + tempid; $(this).hide(); } else if (this.id == "viewlink_add") { this.id = "viewlink" + tempid; $(this).hide(); } else if (this.id.substr(0, 7) == "master_" && this.id.substr(this.id.length - 4) == "_add") { this.id = this.id.substr(0, this.id.length - 4) + tempid; $(this).hide(); } else if (this.id.substr(0, 4) == "add_") { this.id = "edit" + tempid + '_' + this.id.substr(4); } }); $(row).insertBefore(firstelement); // $(row).insertAfter(this); $(row).show(); }); var self = $("#ieditlink" + tempid); /* change the word Edit for images "Save" and "Revert" */ if ($(self).length) { htext = $("#ieditlink" + tempid).html(); mySetOuterHTML(self, '<span id="ieditlink' + tempid + '"><a class="saveEditing" href="#" title="' + TEXT_SAVE + '" id="save_' + tempid + '"><img src="images/ok.gif" border="0" /></a>&nbsp;&nbsp;<a class="revertEditing" href="#" title="' + TEXT_CANCEL + '" id="revert_' + tempid + '"><img src="images/cancel.gif" border="0" /></a></span>'); $("#ieditlink" + tempid)[0].revertText = htext; $("#ieditlink" + tempid)[0].revertClass = hclass; $("#ieditlink" + tempid)[0].revertStyle = hstyle; } $("span[@id^=edit" + tempid + "_]").each(function(i) { var j; this.validatetype = ""; for (j = 0; j < addValidateFields.length; j++) { if (addValidateFields[j] == this.id.substr(this.id.indexOf("_") + 1)) { this.validatetype = addValidateTypes[j]; break; } } }); makeControlsEditable(tempid, "", "add"); updatesaveall(); return false; } function inlineEdit(record_id, record_key) { var self = $("#ieditlink" + record_id); /* highlighting edited record */ $(self).parents("tr").addClass("highlight_row"); /* change the word Edit for images "Save" and "Revert" */ if ($(self).length) { var htext = $("#ieditlink" + record_id).html(); var hclass = $("#ieditlink" + record_id).attr("class"); var hstyle = $("#ieditlink" + record_id).attr("style"); mySetOuterHTML(self, '<span id="ieditlink' + record_id + '"><a class="saveEditing" href="#" title="' + TEXT_SAVE + '" id="save_' + record_id + '"><img src="images/ok.gif" border="0" /></a>&nbsp;&nbsp;<a class="revertEditing" href="#" title="' + TEXT_CANCEL + '" id="revert_' + record_id + '"><img src="images/cancel.gif" border="0" /></a></span>'); $("#ieditlink" + record_id)[0].revertText = htext; $("#ieditlink" + record_id)[0].revertClass = hclass; $("#ieditlink" + record_id)[0].revertStyle = hstyle; } /* create backup values */ $("span[@id^=edit" + record_id + "_]").each(function(i) { this.revert = this.innerHTML; var j; for (j = 0; j < editValidateFields.length; j++) { if (editValidateFields[j] == this.id.substr(this.id.indexOf("_") + 1)) { this.validatetype = editValidateTypes[j]; break; } } }); updatesaveall(); /* load HTML controls */ makeControlsEditable(record_id, record_key, "edit"); return false; } //function makeControlsEditable(line, id, key, type) function makeControlsEditable(id, key, type) { var controls = new Array(); var fields = new Array(); var types = new Array(); var jscode = ""; var server_url = (type == "edit") ? INLINE_EDIT_TABLE + '?' + key : INLINE_ADD_TABLE; $.get(server_url, { rndval: Math.random(), recordID: id, editType: "inline", browser: $.browser.msie ? "ie" : "" }, function(xml) { var pos = xml.indexOf("<edit_controls>"); if (pos > 0) xml = xml.substr(pos); var pos1, pos2; var oldpos = 0; while ((pos = xml.indexOf("<control", oldpos)) >= 0) { pos1 = xml.indexOf(">", pos); if (pos1 < 0) break; pos2 = xml.indexOf("</control>", pos1); if (pos2 < 0) break; var tag = xml.substr(pos, pos1 - pos + 1); var attrpos = tag.indexOf("field=\""); if (attrpos < 0) break; attrpos += 7; var quotpos = tag.indexOf("\"", attrpos); if (quotpos < 0) break; controls[controls.length] = xml.substr(pos1 + 1, pos2 - pos1 - 1); fields[fields.length] = tag.substr(attrpos, quotpos - attrpos); attrpos = tag.indexOf("type=\""); if (attrpos > 0) { attrpos += 6; quotpos = tag.indexOf("\"", attrpos); } if (attrpos > 0 && quotpos > 0) types[types.length] = tag.substr(attrpos, quotpos - attrpos); else types[types.length] = ""; oldpos = pos2 + 10; } pos = xml.indexOf("<jscode>"); pos1 = xml.indexOf("</jscode>"); if (pos >= 0 && pos1 >= 0) jscode = xml.substr(pos + 8, pos1 - pos - 8); $.each(controls, function(i, n) { var span = $("#edit" + id + "_" + fields[i]); if ($(span)[0] != undefined) { $(span).html(n); if (types[i] == "FCK" || types[i] == "Innova" || types[i] == "RTE") { $(span).attr("type", types[i]); if (types[i] == "FCK") { var fckurl = $("iframe", span)[0].src; var fckurl = (type == "edit") ? fckurl + '?' + key : fckurl; $.get(fckurl, { id: id, mode: type, field: fields[i] }, function(xml) { $(span).html(xml); var fckdiv = $("#fckedit", span); $(span).html(fckdiv.html()); $(span).attr("type", types[i]); }); } } else { $("input[@type=text],input[@type=password],input[@type=hidden],input[@type=file],select", span).each(function(i) { if (this.type == "select-multiple") { this.id = this.name.replace(/\[\]$/, "") + "_" + id; } else { this.id = this.name + "_" + id; } }); $("img", span).each(function(i) { this.id = "img_" + this.name.substr(6) + "_" + id; if ($(this)[0].tagName == 'IMG' && $(this)[0].src.indexOf("?") >= 0) $(this)[0].src = $(this)[0].src + "&rndVal=" + Math.random(); }); } } }); jscode = jscode.replace(/&gt;/ig, "\>"); jscode = jscode.replace(/&lt;/ig, "\<"); jscode = jscode.replace(/&amp;/ig, "&"); eval(jscode); if (type == "add") { /* save icon click handler */ $('a[@id=save_' + id + ']').click(function() { if (validate(id, "add")) { submitInputContent(id, "", "add"); } }); /* revert icon click handler */ $('a[@id=revert_' + id + ']').click(function() { $(".addarea" + id).each(function(i) { $(this).remove(); updatesaveall(); if ($("[@name=saveall_edited]").css("display") == "none") if ($("#usermessage")[0] != undefined) $("#usermessage").html(""); }); }); } else { /* save icon click handler */ $('a[@id=save_' + id + ']').click(function() { if (validate(id, "edit")) { submitInputContent(id, key, "edit"); } }); /* revert icon click handler */ $('a[@id=revert_' + id + ']').click(function() { $("span[@id^=edit" + id + "_]").each(function(i) { this.innerHTML = this.revert; }); var htext = this.parentNode.revertText; var hclass = this.parentNode.revertClass; var hstyle = this.parentNode.revertStyle; mySetOuterHTML(this.parentNode, '<a href="' + INLINE_EDIT_TABLE + '?' + key + '" id="ieditlink' + id + '" onclick="return inlineEdit(' + id + ',\'' + key + '\');"></a>'); $("#ieditlink" + id).html(htext); $("#ieditlink" + id).attr("class", hclass); $("#ieditlink" + id).attr("style", hstyle); updatesaveall(); if ($("[@name=saveall_edited]").css("display") == "none") if ($("#usermessage")[0] != undefined) $("#usermessage").html(""); $(this).parents("tr").removeClass("highlight_row"); for (i = 0; i < document.forms.frmAdmin.elements['selection[]'].length; i++) { if (document.forms.frmAdmin.elements['selection[]'][i].id == "check" + id) { document.forms.frmAdmin.elements['selection[]'][i].checked = false; break; } } }); } }); } function picRefresh(id) { $("span[@id^=edit" + id + "]").each(function(i) { var rndVal = new Date().getTime(); $('img', this).each(function() { if (this.src.indexOf("?") >= 0) this.src += "&rndVal=" + rndVal; }); }); // pics.splice(0,pics.length); } function validate(id, type) { var isValid = true; $("span[@id^=edit" + id + "_]").each(function(i) { $("div", this).remove(".error"); if (this.validatetype == undefined) { return; } if (this.validatetype.indexOf("IsRequired") >= 0 && $("input[@type=text],input[@type=password],input[@type=file],select", this).length) { var sVal = $("input[@type=text],input[@type=password],input[@type=file],select", this).val(); var regexp = /.+/; if (!sVal.match(regexp)) { isValid = false; $(this).append('<div class="error"><p>' + TEXT_INLINE_FIELD_REQUIRED + '</p></div>'); } } if ($("input[@type=text]", this).length) { if (this.validatetype.indexOf("IsNumeric") >= 0) { var sVal = $("input[@type=text]", this).val().replace(/,/g, ""); /* var regexp = /^\d{1,}(\.\d+)?$/; if ( sVal.match(/.+/) && !sVal.match(regexp) ) { */ if (isNaN(sVal)) { isValid = false; $(this).append('<div class="error"><p>' + TEXT_INLINE_FIELD_NUMBER + '</p></div>'); } } else if (this.validatetype.indexOf("IsPassword") >= 0) { var sVal = $("input[@type=text],input[@type=password]", this).val(); var regexp1 = /^password$/; var regexp2 = /.{4,}/; if (sVal.match(/.+/)) { if (sVal.match(regexp1)) { isValid = false; $(this).append('<div class="error"><p>' + TEXT_INLINE_FIELD_PASSWORD1 + '</p></div>'); } else if (!sVal.match(regexp2)) { isValid = false; $(this).append('<div class="error"><p>' + TEXT_INLINE_FIELD_PASSWORD2 + '</p></div>'); } } } else if (this.validatetype.indexOf("IsEmail") >= 0) { var sVal = $("input[@type=text]", this).val(); var regexp = /^[A-z0-9_-]+([.][A-z0-9_-]+)*[@][A-z0-9_-]+([.][A-z0-9_-]+)*[.][A-z]{2,4}$/; if (sVal.match(/.+/) && !sVal.match(regexp)) { isValid = false; $(this).append('<div class="error"><p>' + TEXT_INLINE_FIELD_EMAIL + '</p></div>'); } } else if (this.validatetype.indexOf("IsMoney") >= 0) { var sVal = $("input[@type=text]", this).val(); var regexp = /^(\d*)\.?(\d*)$/; if (sVal.match(/.+/) && !sVal.match(regexp)) { isValid = false; $(this).append('<div class="error"><p>' + TEXT_INLINE_FIELD_CURRENCY + '</p></div>'); } } else if (this.validatetype.indexOf("IsZipCode") >= 0) { var sVal = $("input[@type=text]", this).val(); var regexp = /^\d{5}([\-]\d{4})?$/; if (sVal.match(/.+/) && !sVal.match(regexp)) { isValid = false; $(this).append('<div class="error"><p>' + TEXT_INLINE_FIELD_ZIPCODE + '</p></div>'); } } else if (this.validatetype.indexOf("IsPhoneNumber") >= 0) { var sVal = $("input[@type=text]", this).val(); var regexp = /^\(\d{3}\)\s?\d{3}\-\d{4}$/; var stripped = sVal.replace(/[\(\)\.\-\ ]/g, ''); if (sVal.match(/.+/) && (isNaN(parseInt(stripped)) || stripped.length != 10)) { isValid = false; $(this).append('<div class="error"><p>' + TEXT_INLINE_FIELD_PHONE + '</p></div>'); } } else if (this.validatetype.indexOf("IsState") >= 0) { var sVal = $("input[@type=text]", this).val(); if (sVal.match(/.+/) && !arrStates.inArray(sVal, false)) { isValid = false; $(this).append('<div class="error"><p>' + TEXT_INLINE_FIELD_STATE + '</p></div>'); } } else if (this.validatetype.indexOf("IsSSN") >= 0) { // 123-45-6789 or 123 45 6789 var sVal = $("input[@type=text]", this).val(); var regexp = /^\d{3}(-|\s)\d{2}(-|\s)\d{4}$/; if (sVal.match(/.+/) && !sVal.match(regexp)) { isValid = false; $(this).append('<div class="error"><p>' + TEXT_INLINE_FIELD_SSN + '</p></div>'); } } else if (this.validatetype.indexOf("IsCC") >= 0) { var sVal = $("input[@type=text]", this).val(); //Visa, Master Card, American Express var regexp = /^((4\d{3})|(5[1-5]\d{2}))(-?|\040?)(\d{4}(-?|\040?)){3}|^(3[4,7]\d{2})(-?|\040?)\d{6}(-?|\040?)\d{5}/; if (sVal.match(/.+/) && !sVal.match(regexp)) { isValid = false; $(this).append('<div class="error"><p>' + TEXT_INLINE_FIELD_CC + '</p></div>'); } } else if (this.validatetype.indexOf("IsTime") >= 0) { var sVal = $("input[@type=text]", this).val(); if (sVal.match(/.+/)) { var regexp = /\d+/g; var arr = sVal.match(regexp); var bFlag = true; if (arr == null || arr.length > 3) { bFlag = false; } while (bFlag && arr.length < 3) { arr[arr.length] = 0; } if (bFlag && (arr[0] < 0 || arr[0] > 23 || arr[1] < 0 || arr[1] > 59 || arr[2] < 0 || arr[2] > 59)) { bFlag = false; } if (!bFlag) { isValid = false; $(this).append('<div class="error"><p>' + TEXT_INLINE_FIELD_TIME + '</p></div>'); } } } else if (this.validatetype.indexOf("IsDate") >= 0) { var sVal = $("input[@type=text]", this).val(); var fmt = ""; switch (locale_dateformat) { case 0: fmt = "MDY"; break; case 1: fmt = "DMY"; break; default: fmt = "YMD"; break; }; if (sVal.match(/.+/) && !isValidDate(sVal, fmt)) { isValid = false; $(this).append('<div class="error"><p>' + TEXT_INLINE_FIELD_DATE + '</p></div>'); } } } }); return isValid; } function submitInputContent(id, key, type) { gTop = document.body.scrollTop; gLeft = document.body.scrollLeft; if ($("#usermessage")[0] != undefined) $("#usermessage").html(""); var value_key = key.split(/&|=/g); var io = createUploadIframe(id, type); var form = createUploadForm(id, type); if (type == "edit") { for (i = 0; i < value_key.length; i = i + 2) { $('<input type="hidden" name="' + value_key[i] + '" />').appendTo(form); $(form)[0].elements[value_key[i]].value = unescape(value_key[i + 1]); } } $("span[@id^=edit" + id + "_]").each(function(i) { var span = this; if (($(span).attr("type") == "Innova" || $(span).attr("type") == "RTE") && $("iframe", span).length) { var doc; if ($.browser.msie) { doc = window.frames[$("iframe", span)[0].name].document; if (doc.forms[0].onsubmit != null) doc.forms[0].onsubmit(); var txtarea; var name; if ($(span).attr("type") == "RTE") txtarea = $("input[@type=hidden]", doc)[0]; else txtarea = $("textarea", doc)[0]; name = txtarea.name.substr(0, txtarea.name.length - 1 - (new String(id)).length); $('<input type="text" name="' + name + '">').appendTo(form); if ($(span).attr("type") == "RTE") $("[@name=" + name + "]", form).val($(txtarea).val()); else $("[@name=" + name + "]", form).val($(txtarea).text()); } else { doc = $("iframe", span)[0].contentDocument; var txt = doc.forms[0].onsubmit(); name = "value_" + span.id.substr(5 + (new String(id)).length); $('<input type="text" name="' + name + '">').appendTo(form); $("[@name=" + name + "]", form).val(txt); } return; } if ($(span).attr("type") == "FCK") { var txt = $("input[@type=hidden][@name^=value_]", span); if (!txt.length) return; var name = $(txt)[0].name; try { if (typeof (FCKeditorAPI) == "object") FCKeditorAPI.GetInstance($(txt)[0].name).UpdateLinkedField(); } catch (err) { } } if ($.browser.msie) { $("[@type=file]", this).each(function() { $(this).appendTo(form); $(this).clone().appendTo(span); }); $("[@type=hidden],[@type=text],[@type=password],[@type=radio][@checked]", this).each(function() { var name = this.name; if (this.type == 'radio' || $(span).attr("type") == "FCK") name = this.name.substr(0, this.name.length - 1 - (new String(id)).length); $('<input type="text" name="' + name + '">').appendTo(form); $("[@name=" + name + "]", form).val(this.value); }); $("textarea", this).each(function() { $('<textarea name="' + this.name + '"></textarea>').appendTo(form); $("[@name=" + this.name + "]", form)[0].innerText = this.value; }); } else { $("[@type=hidden],[@type=text],[@type=password],[@type=file],[@type=radio][@checked]", this).each(function() { $(this).clone().appendTo(form); if (this.name != undefined && (this.type == 'radio' || $(span).attr("type") == "FCK")) $(form)[0].elements[$(form)[0].elements.length - 1].name = this.name.substr(0, this.name.length - 1 - (new String(id)).length); }); /* $("select",this).each(function() { $('<input type="text" name="'+this.name+'">').appendTo(form); $(form)[0].elements[this.name].value=this.value; }); */ $("textarea", this).each(function() { $('<textarea name="' + this.name + '"></textarea>').appendTo(form); $("[@name=" + this.name + "]", form).text(this.value); }); } $("select", this).each(function() { var name = this.name; if (!this.multiple) { $('<input type="text" name="' + name + '">').appendTo(form); $("[@name=" + name + "]", form).val(this.value); } else { // multiple select for (i = 0; i < this.options.length; i++) { if (!this.options[i].selected) continue; var input = $('<input type="text" name="' + name + '">'); $(input).val(this.options[i].value); $(input).appendTo(form); } } }); $("[@type=checkbox]", this).each(function(i) { if (this.checked == true) { $('<input type="hidden" value="1" name="' + this.name + '">').appendTo(form); } else { $('<input type="hidden" value="" name="' + this.name + '">').appendTo(form); } }); }); /* if ( !$.browser.msie ) { $("input[@type=radio]",form).each(function(){ this.name=this.name.substr(0,this.name.length-1-(new String(id)).length); }); } */ $(form)[0].submit(); setTimeout('$("#uploadForm' + id + '").remove()', 500); } function setInputContent(txt, id, type) { window.scrollTo(gLeft, gTop); var new_edit_id = ""; var new_copy_id = ""; if (txt.substr(0, 5) == "error") { $("span[@id^=edit" + id + "_]:eq(0)").children("div.error").remove(); $("span[@id^=edit" + id + "_]:eq(0)").append("<div class=error><br/><a href=# id=\"error_" + id + "\" style=\"white-space:nowrap;\">" + TEXT_INLINE_ERROR + " >></a></div>"); $("#error_" + id)[0].onmouseover = function() { $("#inline_error").html(slashdecode(txt.substr(5))); var coors = findPos(this); coors[0] += coors[2]; $("#inline_error").css("top", coors[1] + "px"); $("#inline_error").css("left", coors[0] + "px"); $("#inline_error").show(); }; $("#error_" + id)[0].onmouseout = function() { $("#inline_error").hide(); } if ($.browser.msie) { //set all file radion buttons to '0' - keep $("span[@id^=edit" + id + "_]") { $("input[@type=radio][@name^=type_]", this).each(function(i) { if ($(this)[0].value == 'file0' || $(this)[0].value == 'upload0') $(this)[0].checked = true; }); } } return; } else if (txt.substr(0, 5) == "decli") { $("span[@id^=edit" + id + "_]:eq(0)").children("div.error").remove(); if ($.browser.msie) { //set all file radion buttons to '0' - keep $("span[@id^=edit" + id + "_]") { $("input[@type=radio][@name^=type_]", this).each(function(i) { if ($(this)[0].value == 'file0' || $(this)[0].value == 'upload0') $(this)[0].checked = true; }); } } if ($("#usermessage")[0] != undefined && txt.substr(5).length) $("#usermessage").append("<br>" + slashdecode(txt.substr(5))); return; } else if (txt.substr(0, 5) != "saved" && txt.substr(0, 5) != "savnd") return; var havedata = true; if (txt.substr(0, 5) == "savnd") havedata = false; txt = txt.substr(5); var blocks = txt.split("\n"); $.each(blocks, function(i, n) { blocks[i] = slashdecode(n); }); while (blocks.length < 7) blocks[blocks.length] = ""; var keys = blocks[0].split("\n"); keys.splice(keys.length - 1, 1); $.each(keys, function(i, n) { keys[i] = slashdecode(n); }); var values = blocks[1].split("\n"); values.splice(values.length - 1, 1); $.each(values, function(i, n) { values[i] = slashdecode(n); }); var fields = blocks[2].split("\n"); fields.splice(fields.length - 1, 1); $.each(fields, function(i, n) { fields[i] = slashdecode(n); }); var rawvalues = blocks[3].split("\n"); rawvalues.splice(rawvalues.length - 1, 1); $.each(rawvalues, function(i, n) { rawvalues[i] = slashdecode(n); }); while (rawvalues.length < values.length) rawvalues[rawvalues.length] = ""; var detailtables = blocks[4].split("\n"); detailtables.splice(detailtables.length - 1, 1); $.each(detailtables, function(i, n) { detailtables[i] = slashdecode(n); }); var detailkeys = blocks[5].split("\n"); detailkeys.splice(detailkeys.length - 1, 1); $.each(detailkeys, function(i, n) { detailkeys[i] = slashdecode(n); }); var usermessage = slashdecode(blocks[6]); if ($("#usermessage")[0] != undefined && usermessage.length) $("#usermessage").append("<br>" + slashdecode(usermessage)); $.each(values, function(i, n) { var span = $("#edit" + id + "_" + fields[i]); if ($(span)[0] != undefined) { $(span).html(n); $(span)[0].value = rawvalues[i]; } }); $.each(detailtables, function(i, n) { var ahref = $("#master" + "_" + n + id); if ($(ahref)[0] != undefined) { var pos = $(ahref)[0].href.indexOf("?"); $(ahref)[0].href = $(ahref)[0].href.substr(0, pos + 1) + detailkeys[i]; if (havedata) $(ahref).show(); else $(ahref).hide(); } }); $.each(keys, function(i, n) { new_edit_id += "editid" + (i + 1) + "=" + n + "&"; new_copy_id += "copyid" + (i + 1) + "=" + n + "&"; }); new_edit_id = new_edit_id.substr(0, new_edit_id.length - 1); new_copy_id = new_copy_id.substr(0, new_copy_id.length - 1); if ($("#ieditlink" + id).length) { var htext = $("#ieditlink" + id)[0].revertText; var hclass = $("#ieditlink" + id)[0].revertClass; var hstyle = $("#ieditlink" + id)[0].revertStyle; mySetOuterHTML($("#ieditlink" + id)[0], '<a href="' + INLINE_EDIT_TABLE + '?' + new_edit_id + '" id="ieditlink' + id + '" onclick="return inlineEdit(' + id + ',\'' + new_edit_id + '\');"></a>'); if (!havedata) { htext = ""; } $("#ieditlink" + id).html(htext); $("#ieditlink" + id).attr("class", hclass); $("#ieditlink" + id).attr("style", hstyle); } updatesaveall(); $("a[@id=editlink" + id + "]").attr('href', INLINE_EDIT_TABLE + '?' + new_edit_id); $("a[@id=viewlink" + id + "]").attr('href', INLINE_VIEW_TABLE + '?' + new_edit_id); $("a[@id=copylink" + id + "]").attr('href', INLINE_ADD_TABLE + '?' + new_edit_id); if (havedata) { $("a[@id=editlink" + id + "]").show(); $("a[@id=viewlink" + id + "]").show(); $("a[@id=copylink" + id + "]").show(); $("input[@id=check" + id + "]").show(); } else { $("a[@id=editlink" + id + "]").hide(); $("a[@id=viewlink" + id + "]").hide(); $("a[@id=copylink" + id + "]").hide(); $("input[@id=check" + id + "]").hide(); } // $(line).removeClass("highlight_row"); var keyblock = ""; for (i = 0; i < keys.length; i++) { if (keyblock.length) keyblock += "&"; keyblock += keys[i]; } if ($("#check" + id).length) { $("#check" + id).val(keyblock); $("#check" + id)[0].checked = false; } // add a key to a newly added select checkbox if ($("#checklink_add").length) { $("#checklink_add").val(keyblock); $("#checklink_add")[0].name = "selection[]"; } setTimeout('picRefresh(' + id + ')', 500); calcTotals(); } function createUploadIframe(id, type) { //create frame var frameId = 'uploadFrame' + id; if (window.ActiveXObject) { var io = document.createElement('<iframe onload="if (typeof this.loadCount == \'undefined\') { this.loadCount = 0; } this.loadCount++; if (this.loadCount > 0) { var ioDocument = window.frames[\'' + frameId + '\'].document; if(!$(\'#data\',ioDocument).length) { setInputContent(\'error\'+ioDocument.body.innerHTML, \'' + id + '\', \'' + type + '\'); }else {setInputContent($(\'#data\',ioDocument)[0].innerText, \'' + id + '\', \'' + type + '\'); } document.body.removeChild(this); }" id="' + frameId + '" name="' + frameId + '" />'); } else { var io = document.createElement('iframe'); io.id = frameId; io.name = frameId; $(io).load(function() { if (typeof this.loadCount == 'undefined') { this.loadCount = 0; } this.loadCount++; if (this.loadCount > 0 && this.contentDocument.body.innerHTML != '') { var ioDocument = $("#" + frameId).get(0).contentDocument; if (!$('#data', ioDocument).length) setInputContent("error" + ioDocument.body.innerHTML, id, type); else setInputContent($("#data", ioDocument).text(), id, type); setTimeout('$("#' + frameId + '").remove()', 500); } }); } io.style.position = 'absolute'; io.style.top = '-1000px'; io.style.left = '-1000px'; document.body.appendChild(io); return io; } function createUploadForm(id, type) { var frameId = 'uploadFrame' + id; var formId = 'uploadForm' + id; var server_url = (type == "edit") ? INLINE_EDIT_TABLE : INLINE_ADD_TABLE; var form = $('<form action="' + server_url + '" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); if (type == "edit") { $('<input type="hidden" name="a" value="edited">').appendTo(form); } else { $('<input type="hidden" name="a" value="added">').appendTo(form); } $('<input type="hidden" name="editType" value="inline">').appendTo(form); $('<input type="hidden" name="recordID" value="' + id + '">').appendTo(form); //set attributes $(form).css('position', 'absolute'); $(form).css('top', '-1200px'); $(form).css('left', '-1200px'); $(form).attr('target', frameId); $(form).appendTo('body'); return form; } function isValidDate(dateStr, format) { if (format == null) { format = "MDY"; } format = format.toUpperCase(); if (format.length != 3) { format = "MDY"; } if ((format.indexOf("M") == -1) || (format.indexOf("D") == -1) || (format.indexOf("Y") == -1)) { format = "MDY"; } if (format.substring(0, 1) == "Y") { // If the year is first var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/ var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/ } else if (format.substring(1, 2) == "Y") { // If the year is second var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/ var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/ } else { // The year must be third var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/ var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/ } // If it doesn't conform to the right format (with either a 2 digit year or 4 digit year), fail if ((reg1.test(dateStr) == false) && (reg2.test(dateStr) == false)) { return false; } var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was // Check to see if the 3 parts end up making a valid date if (format.substring(0, 1) == "M") { var mm = parts[0]; } else if (format.substring(1, 2) == "M") { var mm = parts[1]; } else { var mm = parts[2]; } if (format.substring(0, 1) == "D") { var dd = parts[0]; } else if (format.substring(1, 2) == "D") { var dd = parts[1]; } else { var dd = parts[2]; } if (format.substring(0, 1) == "Y") { var yy = parts[0]; } else if (format.substring(1, 2) == "Y") { var yy = parts[1]; } else { var yy = parts[2]; } if (parseFloat(yy) <= 50) { yy = (parseFloat(yy) + 2000).toString(); } if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); } var dt = new Date(parseFloat(yy), parseFloat(mm) - 1, parseFloat(dd), 0, 0, 0, 0); if (parseFloat(dd) != dt.getDate()) { return false; } if (parseFloat(mm) - 1 != dt.getMonth()) { return false; } return true; } function mySetOuterHTML(self, str) { if ($.browser.msie) $(self)[0].outerHTML = str; else { var r = $(self)[0].ownerDocument.createRange(); r.setStartBefore($(self)[0]); var df = r.createContextualFragment(str); $(self)[0].parentNode.replaceChild(df, $(self)[0]); } } function calcTotals() { $("span[@id^=total_]").each(function(i) { var type = $(this)[0].type; var field = $(this)[0].id.substr(6); var total = 0; var count = 0; $("span[@id^=edit][@id$=_" + field + "]").each(function(j) { var val = $(this)[0].value; if (!isNaN(val)) { total += new Number(val); count++; } else if (val != "") count++; }); if (type == "TOTAL") $(this).html(new Number(total).toString()); else if (type == "AVERAGE") { if (count) $(this).html(new Number(total / count).toString()); else $(this).html(""); } else if (type == "COUNT") { $(this).html(new Number(count).toString()); } }); }
JavaScript
var checkObjects = new Array(); var errors = ""; var RequiredMsg = ""; var returnVal = false; var ZipcodeMsg = ""; var EmailMsg = ""; var NumMsg = ""; var MoneyMsg = ""; var PhnMsg = ""; var ShipRateMsg = ""; var PwdMsg = ""; var StateMsg = ""; var SSNMsg=""; var DateMsg=""; var TimeMsg=""; var CCMsg = ""; var arrStates = new Array('AL','AK','AS','AZ','AR','CA','CO','CT','DE','DC','FM','FL','GA','GU', 'HI','ID','IL','IN','IA','KS','KY','LA','ME','MH','MD','MA','MI','MN','MS','MO','MT','NE','NV', 'NH','NJ','NM','NY','NC','ND','MP','OH','OK','OR','PW','PA','PR','RI','SC','SD','TN','TX','UT', 'VT','VI','VA','WA','WV','WI','WY'); // ----------------------------------------------------------------------------- // define - Call this function in the beginning of the page. I.e. onLoad. // n = name of the input field (Required) // type= IsRequired, IsNumeric, IsEmail, IsZipCode, IsDate, IsTime, IsPhoneNumber, // IsMoney, IsPassword (Required), IsSSN, IsState, IsCC // ----------------------------------------------------------------------------- function define(n, type, HTMLname) { if (document.editform != null) { var p = BuildFileName(n); if (document.editform[n]!=undefined) { var s="V_"+p+" = new formResult(document.editform[n], type, HTMLname);" eval(s); checkObjects[eval(checkObjects.length)] = eval("V_"+p); } } } function formResult(form, type, HTMLname) { this.form = form; this.type = type; this.HTMLname = HTMLname; } function BuildFileName(name) { var s=name; s = s.replace(/\s/g,""); s = s.replace(/\W/g,""); return s; } function validate() { if (checkObjects.length > 0) { errorObject = ""; for (i = 0; i < checkObjects.length; i++) { validateObject = new Object(); validateObject.form = checkObjects[i].form; validateObject.HTMLname = checkObjects[i].HTMLname; //this checks to see if the first three letters are cbo - for a drop //down - a special call is necessary to get the value in the drop down if (checkObjects[i].form.name.substring(0,3) == "cbo") { validateObject.val = checkObjects[i].form[checkObjects[i].form.selectedIndex].value; validateObject.len = checkObjects[i].form[checkObjects[i].form.selectedIndex].length; } else { validateObject.val = checkObjects[i].form.value; validateObject.len = checkObjects[i].form.value.length; } validateObject.type = checkObjects[i].type; // required field ? if (validateObject.type.indexOf("IsRequired")>=0) { if (isWhitespace(validateObject.val)) { // This builds one list of required fields errors += validateObject.HTMLname + "\n"; RequiredMsg += validateObject.HTMLname + "\n"; } validateObject.type = validateObject.type.substring(0,validateObject.type.indexOf("IsRequired")); } if (validateObject.type.indexOf("IsNumeric")>=0) { var sVal = validateObject.val; sVal = sVal.replace(/,/g,""); if ( validateObject.len > 0 && isNaN(sVal)) { errors += validateObject.HTMLname + "\n"; NumMsg += validateObject.HTMLname + "\n"; } } if (validateObject.type.indexOf("IsDate")>=0) { var dt = toDate(validateObject.val); if(dt==null || isNaN(dt)) { errors += validateObject.HTMLname + "\n"; DateMsg += validateObject.HTMLname + "\n"; } } if (validateObject.type.indexOf("IsTime")>=0) { if(validateObject.len>0) { var str=validateObject.val; var re=/\d+/g; var arr=str.match(re); var valid=true; if(arr==null || arr.length>3) valid=false; while(valid && arr.length<3) arr[arr.length]=0; if(valid && (arr[0]<0 || arr[0]>23 || arr[1]<0 || arr[1]>59 || arr[2]<0 || arr[2]>59)) valid=false; if(!valid) { errors += validateObject.HTMLname + "\n"; TimeMsg += validateObject.HTMLname + "\n"; } } } // 123-45-6789 or 123 45 6789 if (validateObject.type.indexOf("IsSSN")>=0 && isWhitespace(validateObject.val)!=true) { var bGood = true; if ( validateObject.len!=11) bGood = false; else { if (validateObject.val.charAt(3)!=" " && validateObject.val.charAt(3)!="-") bGood=false; if (validateObject.val.charAt(6)!=" " && validateObject.val.charAt(6)!="-") bGood=false; if (bGood) { var s=""; for (var j=0; j<validateObject.val.len;++j) if (!isNan(validateObject.val.charAt(j))) s+=validateObject.val.charAt(j); if (isNaN(s)) bGood = false; } } if (bGood==false) { errors += validateObject.HTMLname + "\n"; SSNMsg += validateObject.HTMLname + "\n"; } } else if(validateObject.type.indexOf("IsEmail")>=0) // Checking existense of "@" and ".". // Length of must >= 5 and the "." must // not directly precede or follow the "@" { if (isWhitespace(validateObject.val)!=true) { if ((validateObject.val.indexOf("@") == -1) || (validateObject.val.charAt(0) == ".") || (validateObject.val.charAt(0) == "@") || (validateObject.len < 6) || (validateObject.val.indexOf(".") == -1) || (validateObject.val.charAt(validateObject.val.indexOf("@")+1) == ".") || (validateObject.val.charAt(validateObject.val.indexOf("@")-1) == ".")) { errors += validateObject.HTMLname + "\n"; EmailMsg += validateObject.HTMLname + "\n"; } } } else if(validateObject.type.indexOf("IsState")>=0) { if (isWhitespace(validateObject.val)!=true) { var bFound = false; for (ind = 0; ind < arrStates.length; ind++) if (validateObject.val == arrStates[ind]) { bFound=true; break; } if (bFound==false) { errors += validateObject.HTMLname + "\n"; StateMsg += validateObject.HTMLname + "\n"; } } } else if(validateObject.type.indexOf("IsZipCode")>=0) { if (validateObject.len < 4 || validateObject.len > 10) { errors += validateObject.HTMLname + "\n"; ZipcodeMsg += validateObject.HTMLname + "\n"; } if (ZipcodeMsg == "") { for (var j=0; j < validateObject.len; j++) { if ((validateObject.val.charAt(j) < '0' || validateObject.val.charAt(j) > '9') && validateObject.val.charAt(j) != '-') { errors += validateObject.HTMLname + "\n"; ZipcodeMsg += validateObject.HTMLname + "\n"; j = validateObject.len; } } } } else if(validateObject.type.indexOf("IsPhoneNumber")>=0) //IsPhoneNumber tells whether the field is a Phone number or not //These Phone number fields are valid if there is nothing in the field { var strField = new String(validateObject.val); var numPass=true; var k = 0; for (k = 0; k < strField.length; k++) { if ((strField.charAt(k) < '0' || strField.charAt(k) > '9') && (strField.charAt(k) != '-') && (strField.charAt(k) != '(' && (strField.charAt(k) != ')' && (strField.charAt(k) != ' ')))) { errors += validateObject.HTMLname + "\n"; PhnMsg += validateObject.HTMLname + "\n"; k = strField.length; } } } else if(validateObject.type.indexOf("IsCC")>=0) { var white_space = " -"; var strCC=""; var check_char; if (validateObject.val.length != 0) { for (var ii = 0; ii < validateObject.val.length; ii++) { check_char = white_space.indexOf(validateObject.val.charAt(ii)) if (check_char < 0) strCC += validateObject.val.substring(ii, (ii + 1)); } if ( strCC.length == 0 || isNaN(strCC) ) { errors += validateObject.HTMLname + "\n"; CCMsg += validateObject.HTMLname + "\n"; } else { var doubledigit = strCC.length % 2 == 1 ? false : true; var checkdigit = 0; var tempdigit; for (var ii = 0; ii < strCC.length; ii++) { tempdigit = eval(strCC.charAt(ii)) if (doubledigit) { tempdigit *= 2; checkdigit += (tempdigit % 10); if ((tempdigit / 10) >= 1.0) { checkdigit++; } doubledigit = false; } else { checkdigit += tempdigit; doubledigit = true; } } if ((checkdigit % 10) != 0) { errors += validateObject.HTMLname + "\n"; CCMsg += validateObject.HTMLname + "\n"; } } } } else if(validateObject.type.indexOf("IsMoney")>=0) //IsMoney tells whether a field is a currency field or not { var moneyPass=true; var dotFound=false; var dotFoundAt=-1; var strField = new String(validateObject.val); var k = 0; for (k = 0; k < strField.length; k++) { var x=strField.charAt(k); if (x == ".") { dotFound = true; if (dotFoundAt < 0) { dotFoundAt=k; } } if (((x < '0') || (x > '9')) && (x != '.')) { errors += validateObject.HTMLname + "\n"; MoneyMsg += validateObject.HTMLname + "\n"; k = strField.length; } if ((x == '.') && (dotFoundAt != k)) { errors += validateObject.HTMLname + "\n"; MoneyMsg += validateObject.HTMLname + "\n"; k = strField.length; } } } else if(validateObject.type.indexOf("IsPassword")>=0) //IsPassword tells whehter a particular field is a password or not { var strField = new String(validateObject.val); var pwdPass=true; if (isWhitespace(strField)) { errors += validateObject.HTMLname + "\n"; PwdMsg += validateObject.HTMLname + "\n"; } else if (strField.length < 4) { errors += validateObject.HTMLname + "\n"; PwdMsg += validateObject.HTMLname + "\n"; } } } if (errors) { var errMsg=""; if (RequiredMsg != "" ) errMsg = errMsg + TEXT_FIELDS_REQUIRED + ": \r\n\r\n"+RequiredMsg + "\r\n\r\n"; if (ZipcodeMsg != "") errMsg = errMsg + TEXT_FIELDS_ZIPCODES + ": \r\n\r\n"+ZipcodeMsg + "\r\n\r\n"; if (EmailMsg != "") errMsg = errMsg + TEXT_FIELDS_EMAILS + ": \r\n\r\n"+EmailMsg + "\r\n\r\n"; if (NumMsg != "") errMsg = errMsg + TEXT_FIELDS_NUMBERS + ": \r\n\r\n"+ NumMsg + "\r\n\r\n"; if (MoneyMsg != "") errMsg=errMsg + TEXT_FIELDS_CURRENCY + ": \r\n\r\n" + MoneyMsg + "\r\n\r\n"; if (PhnMsg != "") errMsg = errMsg + TEXT_FIELDS_PHONE + ": \r\n\r\n" + PhnMsg +"\r\n\r\n"; if (PwdMsg != "") errMsg=errMsg + TEXT_FIELDS_PASSWORD1 + ": \r\n " + TEXT_FIELDS_PASSWORD2 + "\r\n " + TEXT_FIELDS_PASSWORD3 + ": \r\n\r\n" + PwdMsg + "\r\n\r\n"; if (StateMsg != "") errMsg=errMsg + TEXT_FIELDS_STATE + ": \r\n\r\n" + StateMsg +"\r\n\r\n"; if (SSNMsg != "") errMsg=errMsg + TEXT_FIELDS_SSN + ": \r\n\r\n" + SSNMsg +"\r\n\r\n"; if (DateMsg != "") errMsg=errMsg + TEXT_FIELDS_DATE + ": \r\n\r\n" + DateMsg +"\r\n\r\n"; if (TimeMsg != "") errMsg=errMsg + TEXT_FIELDS_TIME + ": \r\n\r\n" + TimeMsg +"\r\n\r\n"; if (CCMsg != "") errMsg=errMsg + TEXT_FIELDS_CC + ": \r\n\r\n" + CCMsg +"\r\n\r\n"; alert(errMsg); errors = ""; RequiredMsg = ""; ZipcodeMsg = ""; EmailMsg = ""; NumMsg = ""; MoneyMsg = ""; PhnMsg = ""; PwdMsg = ""; StateMsg = ""; SSNMsg = ""; DateMsg = ""; TimeMsg = ""; CCMsg = ""; errMsg = ""; returnVal = false; } else returnVal = true; return returnVal; } } // whitespace characters var whitespace = " \t\n\r"; /****************************************************************/ // Check whether string s is empty. function isEmpty(s) { return ((s == null) || (s.length == 0)) } /****************************************************************/ // Returns true if string s is empty or // whitespace characters only. function isWhitespace(s) { var i; // Is s empty? if (isEmpty(s)) return true; // Search through string's characters one by one // until we find a non-whitespace character. // When we do, return false; if we don't, return true. for (i = 0; i < s.length; i++) { // Check that current character isn't whitespace. var c = s.charAt(i); if (whitespace.indexOf(c) == -1) return false; } // All characters are whitespace. return true; } /****************************************************************/ // Checks to see if a required field is blank. If it is, a warning // message is displayed... function ForceEntry(objField, FieldName) { var strField = new String(objField.value); if (isWhitespace(strField) ) { alert("Please enter information for " + FieldName + "."); objField.focus(); return false; } return true; } function toDate(str) { var re=/\d+/g; var arr=str.match(re); var dt; if(arr==null || arr.length<3) return null; while(arr.length<6) arr[arr.length]=0; if(locale_dateformat==0) dt = new Date(arr[2],arr[0]-1,arr[1],arr[3],arr[4],arr[5]); else if(locale_dateformat==1) dt = new Date(arr[2],arr[1]-1,arr[0],arr[3],arr[4],arr[5]); else dt = new Date(arr[0],arr[1]-1,arr[2],arr[3],arr[4],arr[5]); if(isNaN(dt)) return null; // check date and month if(locale_dateformat==0) if(dt.getMonth()!=arr[0]-1 || dt.getDate()!=arr[1]); if(locale_dateformat==1) if(dt.getMonth()!=arr[1]-1 || dt.getDate()!=arr[0]); else if(dt.getMonth()!=arr[1]-1 || dt.getDate()!=arr[2]); return null; return dt; }
JavaScript
// Cross-Browser Rich Text Editor // http://www.kevinroth.com/rte/demo.htm // Written by Kevin Roth (kevin@NOSPAMkevinroth.com - remove NOSPAM) //init variables var isRichText = false; var rng; var currentRTE; var allRTEs = ""; var isIE; var isGecko; var isSafari; var isKonqueror; var imagesPath; var includesPath; var cssFile; function initRTE(imgPath, incPath, css) { //set browser vars var ua = navigator.userAgent.toLowerCase(); isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1)); isGecko = (ua.indexOf("gecko") != -1); isSafari = (ua.indexOf("safari") != -1); isKonqueror = (ua.indexOf("konqueror") != -1); //check to see if designMode mode is available if (document.getElementById && document.designMode && !isSafari && !isKonqueror) { isRichText = true; } if (!isIE) document.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT | Event.MOUSEDOWN | Event.MOUSEUP); document.onmouseover = raiseButton; document.onmouseout = normalButton; document.onmousedown = lowerButton; document.onmouseup = raiseButton; //set paths vars imagesPath = imgPath; includesPath = incPath; cssFile = css; if (isRichText) document.writeln('<style type="text/css">@import "' + includesPath + 'rte.css";</style>'); //for testing standard textarea, uncomment the following line //isRichText = false; } function writeRichText(rte, html, width, height, buttons, readOnly) { if (isRichText) { if (allRTEs.length > 0) allRTEs += ";"; allRTEs += rte; writeRTE(rte, html, width, height, buttons, readOnly); } else { writeDefault(rte, html, width, height, buttons, readOnly); } } function writeDefault(rte, html, width, height, buttons, readOnly) { if (!readOnly) { document.writeln('<textarea name="' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;">' + html + '</textarea>'); } else { document.writeln('<textarea name="' + rte + '" id="' + rte + '" style="width: ' + width + 'px; height: ' + height + 'px;" readonly>' + html + '</textarea>'); } } function raiseButton(e) { if (isIE) { var el = window.event.srcElement; } else { var el= e.target; } className = el.className; if (className == 'rteImage' || className == 'rteImageLowered') { el.className = 'rteImageRaised'; } } function normalButton(e) { if (isIE) { var el = window.event.srcElement; } else { var el= e.target; } className = el.className; if (className == 'rteImageRaised' || className == 'rteImageLowered') { el.className = 'rteImage'; } } function lowerButton(e) { if (isIE) { var el = window.event.srcElement; } else { var el= e.target; } className = el.className; if (className == 'rteImage' || className == 'rteImageRaised') { el.className = 'rteImageLowered'; } } function writeRTE(rte, html, width, height, buttons, readOnly) { if (readOnly) buttons = false; //adjust minimum table widths if (isIE) { if (buttons && (width < 600)) width = 600; var tablewidth = width; } else { if (buttons && (width < 500)) width = 500; var tablewidth = width + 4; } if (buttons == true) { document.writeln('<table class="rteBack" cellpadding=2 cellspacing=0 id="Buttons1_' + rte + '" width="' + tablewidth + '">'); document.writeln(' <tr>'); document.writeln(' <td>'); document.writeln(' <select id="formatblock_' + rte + '" onchange="Select(\'' + rte + '\', this.id);">'); document.writeln(' <option value="">[Style]</option>'); document.writeln(' <option value="<p>">Paragraph</option>'); document.writeln(' <option value="<h1>">Heading 1 <h1></option>'); document.writeln(' <option value="<h2>">Heading 2 <h2></option>'); document.writeln(' <option value="<h3>">Heading 3 <h3></option>'); document.writeln(' <option value="<h4>">Heading 4 <h4></option>'); document.writeln(' <option value="<h5>">Heading 5 <h5></option>'); document.writeln(' <option value="<h6>">Heading 6 <h6></option>'); document.writeln(' <option value="<address>">Address <ADDR></option>'); document.writeln(' <option value="<pre>">Formatted <pre></option>'); document.writeln(' </select>'); document.writeln(' </td>'); document.writeln(' <td>'); document.writeln(' <select id="fontname_' + rte + '" onchange="Select(\'' + rte + '\', this.id)">'); document.writeln(' <option value="Font" selected>[Font]</option>'); document.writeln(' <option value="Arial, Helvetica, sans-serif">Arial</option>'); document.writeln(' <option value="Courier New, Courier, mono">Courier New</option>'); document.writeln(' <option value="Times New Roman, Times, serif">Times New Roman</option>'); document.writeln(' <option value="Verdana, Arial, Helvetica, sans-serif">Verdana</option>'); document.writeln(' </select>'); document.writeln(' </td>'); document.writeln(' <td>'); document.writeln(' <select unselectable="on" id="fontsize_' + rte + '" onchange="Select(\'' + rte + '\', this.id);">'); document.writeln(' <option value="Size">[Size]</option>'); document.writeln(' <option value="1">1</option>'); document.writeln(' <option value="2">2</option>'); document.writeln(' <option value="3">3</option>'); document.writeln(' <option value="4">4</option>'); document.writeln(' <option value="5">5</option>'); document.writeln(' <option value="6">6</option>'); document.writeln(' <option value="7">7</option>'); document.writeln(' </select>'); document.writeln(' </td>'); document.writeln(' <td width="100%">'); document.writeln(' </td>'); document.writeln(' </tr>'); document.writeln('</table>'); document.writeln('<table class="rteBack" cellpadding="0" cellspacing="0" id="Buttons2_' + rte + '" width="' + tablewidth + '">'); document.writeln(' <tr>'); document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'bold.gif" width="25" height="24" alt="Bold" title="Bold" onClick="FormatText(\'' + rte + '\', \'bold\', \'\')"></td>'); document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'italic.gif" width="25" height="24" alt="Italic" title="Italic" onClick="FormatText(\'' + rte + '\', \'italic\', \'\')"></td>'); document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'underline.gif" width="25" height="24" alt="Underline" title="Underline" onClick="FormatText(\'' + rte + '\', \'underline\', \'\')"></td>'); document.writeln(' <td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>'); document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'left_just.gif" width="25" height="24" alt="Align Left" title="Align Left" onClick="FormatText(\'' + rte + '\', \'justifyleft\', \'\')"></td>'); document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'centre.gif" width="25" height="24" alt="Center" title="Center" onClick="FormatText(\'' + rte + '\', \'justifycenter\', \'\')"></td>'); document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'right_just.gif" width="25" height="24" alt="Align Right" title="Align Right" onClick="FormatText(\'' + rte + '\', \'justifyright\', \'\')"></td>'); document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'justifyfull.gif" width="25" height="24" alt="Justify Full" title="Justify Full" onclick="FormatText(\'' + rte + '\', \'justifyfull\', \'\')"></td>'); document.writeln(' <td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>'); document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'hr.gif" width="25" height="24" alt="Horizontal Rule" title="Horizontal Rule" onClick="FormatText(\'' + rte + '\', \'inserthorizontalrule\', \'\')"></td>'); document.writeln(' <td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>'); document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'numbered_list.gif" width="25" height="24" alt="Ordered List" title="Ordered List" onClick="FormatText(\'' + rte + '\', \'insertorderedlist\', \'\')"></td>'); document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'list.gif" width="25" height="24" alt="Unordered List" title="Unordered List" onClick="FormatText(\'' + rte + '\', \'insertunorderedlist\', \'\')"></td>'); document.writeln(' <td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>'); document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'outdent.gif" width="25" height="24" alt="Outdent" title="Outdent" onClick="FormatText(\'' + rte + '\', \'outdent\', \'\')"></td>'); document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'indent.gif" width="25" height="24" alt="Indent" title="Indent" onClick="FormatText(\'' + rte + '\', \'indent\', \'\')"></td>'); document.writeln(' <td><div id="forecolor_' + rte + '"><img class="rteImage" src="' + imagesPath + 'textcolor.gif" width="25" height="24" alt="Text Color" title="Text Color" onClick="FormatText(\'' + rte + '\', \'forecolor\', \'\')"></div></td>'); document.writeln(' <td><div id="hilitecolor_' + rte + '"><img class="rteImage" src="' + imagesPath + 'bgcolor.gif" width="25" height="24" alt="Background Color" title="Background Color" onClick="FormatText(\'' + rte + '\', \'hilitecolor\', \'\')"></div></td>'); document.writeln(' <td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>'); document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'hyperlink.gif" width="25" height="24" alt="Insert Link" title="Insert Link" onClick="FormatText(\'' + rte + '\', \'createlink\')"></td>'); document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'image.gif" width="25" height="24" alt="Add Image" title="Add Image" onClick="AddImage(\'' + rte + '\')"></td>'); if (isIE) { document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'spellcheck.gif" width="25" height="24" alt="Spell Check" title="Spell Check" onClick="checkspell()"></td>'); } // document.writeln(' <td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>'); // document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'cut.gif" width="25" height="24" alt="Cut" title="Cut" onClick="FormatText(\'' + rte + '\', \'cut\')"></td>'); // document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'copy.gif" width="25" height="24" alt="Copy" title="Copy" onClick="FormatText(\'' + rte + '\', \'copy\')"></td>'); // document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'paste.gif" width="25" height="24" alt="Paste" title="Paste" onClick="FormatText(\'' + rte + '\', \'paste\')"></td>'); // document.writeln(' <td><img class="rteVertSep" src="' + imagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>'); // document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'undo.gif" width="25" height="24" alt="Undo" title="Undo" onClick="FormatText(\'' + rte + '\', \'undo\')"></td>'); // document.writeln(' <td><img class="rteImage" src="' + imagesPath + 'redo.gif" width="25" height="24" alt="Redo" title="Redo" onClick="FormatText(\'' + rte + '\', \'redo\')"></td>'); document.writeln(' <td width="100%"></td>'); document.writeln(' </tr>'); document.writeln('</table>'); } document.writeln('<iframe id="' + rte + '" name="' + rte + '" src="./include/emptypage.html" width="' + width + 'px" height="' + height + 'px"></iframe>'); if (!readOnly) document.writeln('<br /><input type="checkbox" id="chkSrc' + rte + '" onclick="toggleHTMLSrc(\'' + rte + '\');" />&nbsp;'+TEXT_VIEW_SOURCE); document.writeln('<iframe width="154" height="104" id="cp' + rte + '" src="' + includesPath + 'palette.htm" marginwidth="0" marginheight="0" scrolling="no" style="visibility:hidden; display: none; position: absolute;"></iframe>'); document.writeln('<input type="hidden" id="hdn' + rte + '" name="' + rte + '" value="">'); document.getElementById('hdn' + rte).value = html; enableDesignMode(rte, html, readOnly); } function enableDesignMode(rte, html, readOnly) { var frameHtml = "<html id=\"" + rte + "\">\n"; frameHtml += "<head>\n"; //to reference your stylesheet, set href property below to your stylesheet path and uncomment if (cssFile.length > 0) { frameHtml += "<link media=\"all\" type=\"text/css\" href=\"" + cssFile + "\" rel=\"stylesheet\">\n"; } else { frameHtml += "<style>\n"; frameHtml += "body {\n"; frameHtml += " background: #FFFFFF;\n"; frameHtml += " margin: 0px;\n"; frameHtml += " padding: 0px;\n"; frameHtml += "}\n"; frameHtml += "</style>\n"; } frameHtml += "</head>\n"; frameHtml += "<body>\n"; frameHtml += html + "\n"; frameHtml += "</body>\n"; frameHtml += "</html>"; if (document.all) { var oRTE = frames[rte].document; oRTE.open(); oRTE.write(frameHtml); oRTE.close(); if (!readOnly) oRTE.designMode = "On"; } else { try { if (!readOnly) document.getElementById(rte).contentDocument.designMode = "on"; try { var oRTE = document.getElementById(rte).contentWindow.document; oRTE.open(); oRTE.write(frameHtml); oRTE.close(); if (isGecko && !readOnly) { //attach a keyboard handler for gecko browsers to make keyboard shortcuts work oRTE.addEventListener("keypress", kb_handler, true); } } catch (e) { alert("Error preloading content."); } } catch (e) { //gecko may take some time to enable design mode. //Keep looping until able to set. if (isGecko) { setTimeout("enableDesignMode('" + rte + "', '" + html + "', " + readOnly + ");", 10); } else { return false; } } } } function updateRTEs() { var vRTEs = allRTEs.split(";"); for (var i = 0; i < vRTEs.length; i++) { updateRTE(vRTEs[i]); } } function updateRTE(rte) { if (!isRichText) return; //set message value var oHdnMessage = document.getElementById('hdn' + rte); var oRTE = document.getElementById(rte); var readOnly = false; //check for readOnly mode if (document.all) { if (frames[rte].document.designMode != "On") readOnly = true; } else { if (document.getElementById(rte).contentDocument.designMode != "on") readOnly = true; } if (isRichText && !readOnly) { //if viewing source, switch back to design view if (document.getElementById("chkSrc" + rte).checked) { document.getElementById("chkSrc" + rte).checked = false; toggleHTMLSrc(rte); } if (oHdnMessage.value == null) oHdnMessage.value = ""; if (document.all) { oHdnMessage.value = frames[rte].document.body.innerHTML; } else { oHdnMessage.value = oRTE.contentWindow.document.body.innerHTML; } //if there is no content (other than formatting) set value to nothing if (stripHTML(oHdnMessage.value.replace("&nbsp;", " ")) == "" && oHdnMessage.value.toLowerCase().search("<hr") == -1 && oHdnMessage.value.toLowerCase().search("<img") == -1) oHdnMessage.value = ""; //fix for gecko if (escape(oHdnMessage.value) == "%3Cbr%3E%0D%0A%0D%0A%0D%0A") oHdnMessage.value = ""; } } function toggleHTMLSrc(rte) { //contributed by Bob Hutzel (thanks Bob!) var oRTE; if (document.all) { oRTE = frames[rte].document; } else { oRTE = document.getElementById(rte).contentWindow.document; } if (document.getElementById("chkSrc" + rte).checked) { document.getElementById("Buttons1_" + rte).style.visibility = "hidden"; document.getElementById("Buttons2_" + rte).style.visibility = "hidden"; if (document.all) { oRTE.body.innerText = oRTE.body.innerHTML; } else { var htmlSrc = oRTE.createTextNode(oRTE.body.innerHTML); oRTE.body.innerHTML = ""; oRTE.body.appendChild(htmlSrc); } } else { document.getElementById("Buttons1_" + rte).style.visibility = "visible"; document.getElementById("Buttons2_" + rte).style.visibility = "visible"; if (document.all) { //fix for IE var output = escape(oRTE.body.innerText); output = output.replace("%3CP%3E%0D%0A%3CHR%3E", "%3CHR%3E"); output = output.replace("%3CHR%3E%0D%0A%3C/P%3E", "%3CHR%3E"); oRTE.body.innerHTML = unescape(output); } else { var htmlSrc = oRTE.body.ownerDocument.createRange(); htmlSrc.selectNodeContents(oRTE.body); oRTE.body.innerHTML = htmlSrc.toString(); } } } //Function to format text in the text box function FormatText(rte, command, option) { var oRTE; if (document.all) { oRTE = frames[rte]; //get current selected range var selection = oRTE.document.selection; if (selection != null) { rng = selection.createRange(); } } else { oRTE = document.getElementById(rte).contentWindow; //get currently selected range var selection = oRTE.getSelection(); rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange(); } try { if ((command == "forecolor") || (command == "hilitecolor")) { //save current values parent.command = command; currentRTE = rte; //position and show color palette buttonElement = document.getElementById(command + '_' + rte); // Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div. document.getElementById('cp' + rte).style.left = getOffsetLeft(buttonElement, 4) + "px"; document.getElementById('cp' + rte).style.top = (getOffsetTop(buttonElement, 4) + buttonElement.offsetHeight + 4) + "px"; if (document.getElementById('cp' + rte).style.visibility == "hidden") { document.getElementById('cp' + rte).style.visibility = "visible"; document.getElementById('cp' + rte).style.display = "inline"; } else { document.getElementById('cp' + rte).style.visibility = "hidden"; document.getElementById('cp' + rte).style.display = "none"; } } else if (command == "createlink") { var szURL = prompt("Enter a URL:", ""); try { //ignore error for blank urls oRTE.document.execCommand("Unlink", false, null); oRTE.document.execCommand("CreateLink", false, szURL); } catch (e) { //do nothing } } else { oRTE.focus(); oRTE.document.execCommand(command, false, option); oRTE.focus(); } } catch (e) { alert(e); } } //Function to set color function setColor(color) { var rte = currentRTE; var oRTE; if (document.all) { oRTE = frames[rte]; } else { oRTE = document.getElementById(rte).contentWindow; } var parentCommand = parent.command; if (document.all) { //retrieve selected range var sel = oRTE.document.selection; if (parentCommand == "hilitecolor") parentCommand = "backcolor"; if (sel != null) { var newRng = sel.createRange(); newRng = rng; newRng.select(); } } oRTE.focus(); oRTE.document.execCommand(parentCommand, false, color); oRTE.focus(); document.getElementById('cp' + rte).style.visibility = "hidden"; document.getElementById('cp' + rte).style.display = "none"; } //Function to add image function AddImage(rte) { var oRTE; if (document.all) { oRTE = frames[rte]; //get current selected range var selection = oRTE.document.selection; if (selection != null) { rng = selection.createRange(); } } else { oRTE = document.getElementById(rte).contentWindow; //get currently selected range var selection = oRTE.getSelection(); rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange(); } imagePath = prompt('Enter Image URL:', 'http://'); if ((imagePath != null) && (imagePath != "")) { oRTE.focus(); oRTE.document.execCommand('InsertImage', false, imagePath); oRTE.focus(); } } //function to perform spell check function checkspell() { try { var tmpis = new ActiveXObject("ieSpell.ieSpellExtension"); tmpis.CheckAllLinkedDocuments(document); } catch(exception) { if(exception.number==-2146827859) { if (confirm("ieSpell not detected. Click Ok to go to download page.")) window.open("http://www.iespell.com/download.php","DownLoad"); } else { alert("Error Loading ieSpell: Exception " + exception.number); } } } // Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div. function getOffsetTop(elm, parents_up) { var mOffsetTop = elm.offsetTop; var mOffsetParent = elm.offsetParent; if(!parents_up) { parents_up = 10000; // arbitrary big number } while(parents_up>0 && mOffsetParent) { mOffsetTop += mOffsetParent.offsetTop; mOffsetParent = mOffsetParent.offsetParent; parents_up--; } return mOffsetTop; } // Ernst de Moor: Fix the amount of digging parents up, in case the RTE editor itself is displayed in a div. function getOffsetLeft(elm, parents_up) { var mOffsetLeft = elm.offsetLeft; var mOffsetParent = elm.offsetParent; if(!parents_up) { parents_up = 10000; // arbitrary big number } while(parents_up>0 && mOffsetParent) { mOffsetLeft += mOffsetParent.offsetLeft; mOffsetParent = mOffsetParent.offsetParent; parents_up--; } return mOffsetLeft; } function Select(rte, selectname) { var oRTE; if (document.all) { oRTE = frames[rte]; //get current selected range var selection = oRTE.document.selection; if (selection != null) { rng = selection.createRange(); } } else { oRTE = document.getElementById(rte).contentWindow; //get currently selected range var selection = oRTE.getSelection(); rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange(); } var idx = document.getElementById(selectname).selectedIndex; // First one is always a label if (idx != 0) { var selected = document.getElementById(selectname).options[idx].value; var cmd = selectname.replace('_' + rte, ''); oRTE.focus(); oRTE.document.execCommand(cmd, false, selected); oRTE.focus(); document.getElementById(selectname).selectedIndex = 0; } } function kb_handler(evt) { var rte = evt.target.id; //contributed by Anti Veeranna (thanks Anti!) if (evt.ctrlKey) { var key = String.fromCharCode(evt.charCode).toLowerCase(); var cmd = ''; switch (key) { case 'b': cmd = "bold"; break; case 'i': cmd = "italic"; break; case 'u': cmd = "underline"; break; }; if (cmd) { FormatText(rte, cmd, true); //evt.target.ownerDocument.execCommand(cmd, false, true); // stop the event bubble evt.preventDefault(); evt.stopPropagation(); } } } function docChanged (evt) { alert('changed'); } function stripHTML(oldString) { var newString = oldString.replace(/(<([^>]+)>)/ig,""); //replace carriage returns and line feeds newString = newString.replace(/\r\n/g," "); newString = newString.replace(/\n/g," "); newString = newString.replace(/\r/g," "); //trim string newString = trim(newString); return newString; } function trim(inputString) { // Removes leading and trailing spaces from the passed string. Also removes // consecutive spaces and replaces it with one space. If something besides // a string is passed in (null, custom object, etc.) then return the input. if (typeof inputString != "string") return inputString; var retValue = inputString; var ch = retValue.substring(0, 1); while (ch == " ") { // Check for spaces at the beginning of the string retValue = retValue.substring(1, retValue.length); ch = retValue.substring(0, 1); } ch = retValue.substring(retValue.length-1, retValue.length); while (ch == " ") { // Check for spaces at the end of the string retValue = retValue.substring(0, retValue.length-1); ch = retValue.substring(retValue.length-1, retValue.length); } // Note that there are two spaces in the string - look for multiple spaces within the string while (retValue.indexOf(" ") != -1) { // Again, there are two spaces in each of the strings retValue = retValue.substring(0, retValue.indexOf(" ")) + retValue.substring(retValue.indexOf(" ")+1, retValue.length); } return retValue; // Return the trimmed string back to the user }
JavaScript
var debug=false; var removeflyframe; function DisplayPage(event,page, control,field,tablename,category) { flyid++; var id = flyid; var x,y; if($.browser.msie) { y = event.y; x = event.x; } else { y = event.clientY; x = event.clientX; } var params; var pagetype; if(page.indexOf("_add.")>0) { params={ editType:"onthefly", id:id, rndval: Math.random(), editType: "onthefly", control: control, field: field, table: tablename, category: category }; pagetype="add"; } else if(page.indexOf("_list.")>0) { params={ id:id, rndval: Math.random(), mode: "lookup", control: control, field: field, table: tablename, category: category, firsttime: 1 }; pagetype="list"; } else return; $.get(page, params, function(xml) { var i=xml.indexOf("\n"); var js=""; if(i>=0) { js = slashdecode(xml.substr(0,i)); xml = xml.substr(i+1); } if(debug) { $(document.body).append("<textarea id=htm"+id+" cols=50 rows=10></textarea>"); $("#htm"+id).text(xml); } DisplayFlyDiv(xml,js,id,control,x,y-20,pagetype); } ); return false; } function IsIE6() { var browserName=navigator.appName; var browserVer=parseInt(navigator.appVersion); if (browserName=="Microsoft Internet Explorer" && browserVer<7) return true; return false; } function RemoveFlyDiv(id, dontremoveiframe) { $("#fly" + id).remove(); if(!dontremoveiframe) { removeflyframe = $("#flyframe" + id)[0]; setTimeout('$(removeflyframe).remove()',1); } if(IsIE6()) $("#fli"+id).remove(); } function DisplayFlyDiv(html,js,id,control,x,y,pagetype) { if(IsIE6()) $(document.body).append("<iframe id=fli"+id+" style='background:white; position:absolute;display:none;' > </iframe>"); var w='width:inherit;'; if($.browser.msie && false) { w = 'width:55%;'; } $(document.body).append("<div id='flycontainer"+id+"' style='position:absolute;'>" +"<div align=center pagetype='"+pagetype+"' id=fly"+id+" style='"+w+"border:solid black 1px; background:white; background-repeat:no-repeat' control='"+control+"' onmousedown='flydivonclick(this);'></div></div>"); var title=""; var titlebar="<div id=display_fly"+id+" onmousedown='fly_mousedown_func(event,this.parentNode)' class=blackshade style='padding:5px 10px;border-bottom:solid black 1px;text-align:right;'><span style='float:left'> "+title+"</span><img src='images/cross.gif' onclick=\"RemoveFlyDiv('"+id+"');\"></div>"; var container="<div id='flycontents"+id+"' style='padding: 0px 10px 10px 10px; margin=0;'>"; html=titlebar+container+html+"</div>"; $("#fly"+id).html(html); var flydiv=$("#fly"+id)[0]; $(flydiv).css("top","-1000000px"); w = flydiv.offsetWidth; var h = flydiv.offsetHeight; var scroll=false; if(w>document.body.offsetWidth*.66) { w=document.body.offsetWidth*.66; $(flydiv).css("width",""+w+"px"); h = flydiv.offsetHeight; } if(h>screen.height*0.8) { h=screen.height*0.8; scroll=true; } x+=document.body.scrollLeft; y+=document.body.scrollTop; if(document.body.scrollLeft + document.body.clientWidth<x+flydiv.offsetWidth) x= document.body.scrollLeft + document.body.clientWidth - flydiv.offsetWidth-20; if( x<document.body.scrollLeft) x=document.body.scrollLeft+20; if(document.body.scrollTop + document.body.clientHeight<y+flydiv.offsetHeight) y= document.body.scrollTop + document.body.clientHeight - flydiv.offsetHeight-20; if( y<document.body.scrollTop) y=document.body.scrollTop+20; if(IsIE6()) { var flyframe=document.getElementById("fli"+id); $(flyframe).css("left","" + (x) + "px"); $(flyframe).css("top",""+(y)+"px"); $(flyframe).css("width","" + (w) + "px"); $(flyframe).css("height",""+(h)+"px"); $(flyframe).show(); } var flycontainer = document.getElementById("flycontainer"+id); $(document.body).append($(flydiv).remove()); document.body.removeChild(flycontainer); flydiv=$("#fly"+id)[0]; $(flydiv).css("position","absolute"); $(flydiv).css("left","" + (x) + "px"); $(flydiv).css("top",""+(y)+"px"); $(flydiv).css("width","" + (w) + "px"); $(flydiv).css("height",""+(h)+"px"); if(scroll) { var flycontents=$("#flycontents"+id)[0]; $(flycontents).css("overflow","scroll"); var scrollerWidth = flycontents.offsetWidth-flycontents.clientWidth; var scrollerHeight = flycontents.offsetHeight-flycontents.clientHeight; if(scrollerWidth>16) scrollerWidth=16; if(scrollerHeight>16) scrollerHeight=16; $(flycontents).css("width","" + (w-scrollerWidth-3) + "px"); $(flycontents).css("height",""+(h-18-scrollerHeight)+"px"); } flydivonclick(flydiv); var io = createAddIframe(id,control); var form=$("form[@name=editform"+id+"]")[0]; if(form!=undefined) { $("input[@type=text],input[@type=password],input[@type=hidden],input[@type=file],select",form).each(function(i){ if ( this.type == "select-multiple" ) { this.id = this.name.replace(/\[\]$/,"") + "_" + id; } else { this.id = this.name + "_" + id; } }); } if(js.length) { if(debug) { $(document.body).append("<textarea id=txt"+id+" cols=50 rows=10> </textarea>"); $("#txt"+id).text(js); } eval(js); } } function createAddIframe(id,control) { //create frame var frameId = 'flyframe' + id; // iframe already exists - reset load counter only if($('#'+frameId).length) { delete $('#'+frameId).loadCount; // delete window.frames[frameId].loadCount; return; } if ( window.ActiveXObject ) { var iframetxt='<iframe style="background:white; position:absolute;filter:alpha(opacity=0);" onload="if (typeof this.loadCount == \'undefined\') { this.loadCount = 0; return;} var ioDocument = window.frames[\''+frameId+'\'].document;'+ 'ProcessReturn(ioDocument,\''+control+'\','+id+');" id="' + frameId + '" name="' + frameId + '" />'; var io = document.createElement(iframetxt); } else { var io = document.createElement('iframe'); io.id = frameId; io.name = frameId; $(io).load(function(){ if (typeof this.loadCount == 'undefined') { this.loadCount = 0; return; } var ioDocument = $("#"+frameId).get(0).contentDocument; ProcessReturn(ioDocument,control,id); }); } io.style.position = 'absolute'; io.style.top = '-1000px'; io.style.left = '-1000px'; document.body.appendChild(io); return io; } function ProcessReturn(doc,control,id) { if(debug) { $(document.body).append("<textarea id=err"+id+" cols=50 rows=10></textarea>"); $("#err"+id).text(doc.body.innerHTML); } var pagetype=$("#fly"+id).attr("pagetype"); var txt; if($("#data",doc).length) txt = $("#data",doc).text(); else txt="error"+doc.body.innerHTML; if(txt.substr(0,5)=='added') { txt=txt.substr(5); var blocks=txt.split("\n"); $.each(blocks,function(i,n){ blocks[i] = slashdecode(n); }); var fields=blocks[0].split("\n"); $.each(fields,function(i,n){ fields[i] = slashdecode(n); }); var lookup = document.getElementById(control); if(lookup.tagName=='SELECT') { create_option(lookup,fields[1],fields[0]); if(!lookup.multiple) lookup.selectedIndex=lookup.options.length-1; else lookup.options[lookup.options.length-1].selected=true; } else { lookup.value=fields[0]; document.getElementById("display_"+control).value=fields[1]; } if(lookup.onchange) lookup.onchange(); RemoveFlyDiv(id); } else if(txt.substr(0,5)=='decli') { txt = txt.substr(5); var y = document.getElementById("fly"+id).offsetTop; var x = document.getElementById("fly"+id).offsetLeft; $("#data",doc).remove(); RemoveFlyDiv(id,true); DisplayFlyDiv(doc.body.innerHTML,txt,id,control,x,y,pagetype); } else { txt = txt.substr(5); var y = document.getElementById("fly"+id).offsetTop; var x = document.getElementById("fly"+id).offsetLeft; RemoveFlyDiv(id,true); DisplayFlyDiv(txt,"",id,control,x,y,pagetype); } } function flydivonclick(div) { if($.browser.msie) div.style.zIndex=++zindex_max; else $(div).css("z-index",++zindex_max); } var fly_mousedown=false; var fly_offsetx,fly_offsety; var fly_movingdiv; var fly_initmove=false; function fly_mousedown_func(e,div) { if(!e) e=window.event; if(!fly_initmove) { document.body.oldmousemove=document.body.onmousemove; if($.browser.msie) { document.body.onmousemove = function() { var e=window.event if(fly_mousedown) { fly_movingdiv.style.left=""+(e.x-fly_offsetx)+"px"; fly_movingdiv.style.top=""+(e.y-fly_offsety)+"px"; if(IsIE6()) { var flyframe=document.getElementById("fli"+fly_movingdiv.id.substr(3)); flyframe.style.left=""+(e.x-fly_offsetx)+"px"; flyframe.style.top=""+(e.y-fly_offsety)+"px"; } } if(document.body.oldmousemove!=null) document.body.oldmousemove(); } } else { document.body.onmousemove = function(e) { if(fly_mousedown) { fly_movingdiv.style.left=(e.clientX-fly_offsetx); fly_movingdiv.style.top=(e.clientY-fly_offsety); } if(document.body.oldmousemove!=null) document.body.oldmousemove(); } } document.body.oldmouseup=document.body.onmouseup; document.body.onmouseup=function() { fly_mousedown=false; if(document.body.oldmousemove) document.body.oldmousemove(); } fly_initmove=true; } fly_mousedown=true; if($.browser.msie) { fly_offsetx = e.x-div.offsetLeft; fly_offsety = e.y-div.offsetTop; } else { fly_offsetx = e.clientX-div.offsetLeft; fly_offsety = e.clientY-div.offsetTop; } fly_movingdiv = div; } function define_fly(id, type) { var obj=document.getElementById(id); if(!obj) return; obj.validatetype=type; } function validate_fly(form) { var isValid = true; $("div",form).remove(".error"); $.each(form.elements,function(i){ if ( this.validatetype == undefined ) { return; } if ( this.validatetype.indexOf("IsRequired") >= 0 ) { var sVal = $(this).val(); var regexp = /.+/; if ( !sVal.match(regexp) ) { isValid = false; $(this).after('<div class="error">' + TEXT_INLINE_FIELD_REQUIRED + '</div>'); } } if ( $("input[@type=text]",this).length ) { var sVal = $(this).val(); if ( this.validatetype.indexOf("IsNumeric") >= 0 ) { sVal = sVal.replace(/,/g,""); if (isNaN(sVal)) { isValid = false; $(this).after('<div class="error">' + TEXT_INLINE_FIELD_NUMBER + '</div>'); } } else if ( this.validatetype.indexOf("IsPassword") >= 0 ) { var regexp1 = /^password$/; var regexp2 = /.{4,}/; if ( sVal.match(/.+/) ) { if ( sVal.match(regexp1) ) { isValid = false; $(this).after('<div class="error">' + TEXT_INLINE_FIELD_PASSWORD1 + '</div>'); } else if ( !sVal.match(regexp2) ) { isValid = false; $(this).after('<div class="error">' + TEXT_INLINE_FIELD_PASSWORD2 + '</div>'); } } } else if ( this.validatetype.indexOf("IsEmail") >= 0 ) { var regexp = /^[A-z0-9_-]+([.][A-z0-9_-]+)*[@][A-z0-9_-]+([.][A-z0-9_-]+)*[.][A-z]{2,4}$/; if ( sVal.match(/.+/) && !sVal.match(regexp) ) { isValid = false; $(this).after('<div class="error">' + TEXT_INLINE_FIELD_EMAIL + '</div>'); } } else if ( this.validatetype.indexOf("IsMoney") >= 0 ) { var regexp = /^(\d*)\.?(\d*)$/; if ( sVal.match(/.+/) && !sVal.match(regexp) ) { isValid = false; $(this).after('<div class="error">' + TEXT_INLINE_FIELD_CURRENCY + '</div>'); } } else if ( this.validatetype.indexOf("IsZipCode") >= 0 ) { var regexp = /^\d{5}([\-]\d{4})?$/; if ( sVal.match(/.+/) && !sVal.match(regexp) ) { isValid = false; $(this).after('<div class="error">' + TEXT_INLINE_FIELD_ZIPCODE + '</div>'); } } else if ( this.validatetype.indexOf("IsPhoneNumber") >= 0 ) { var regexp = /^\(\d{3}\)\s?\d{3}\-\d{4}$/; var stripped = sVal.replace(/[\(\)\.\-\ ]/g, ''); if ( sVal.match(/.+/) && (isNaN(parseInt(stripped)) || stripped.length != 10) ) { isValid = false; $(this).after('<div class="error">' + TEXT_INLINE_FIELD_PHONE + '</div>'); } } else if ( this.validatetype.indexOf("IsState") >= 0 ) { if ( sVal.match(/.+/) && !arrStates.inArray(sVal,false) ) { isValid = false; $(this).after('<div class="error">' + TEXT_INLINE_FIELD_STATE + '</div>'); } } else if ( this.validatetype.indexOf("IsSSN") >= 0 ) { // 123-45-6789 or 123 45 6789 var regexp = /^\d{3}(-|\s)\d{2}(-|\s)\d{4}$/; if ( sVal.match(/.+/) && !sVal.match(regexp) ) { isValid = false; $(this).after('<div class="error">' + TEXT_INLINE_FIELD_SSN + '</div>'); } } else if ( this.validatetype.indexOf("IsCC") >= 0 ) { //Visa, Master Card, American Express var regexp = /^((4\d{3})|(5[1-5]\d{2}))(-?|\040?)(\d{4}(-?|\040?)){3}|^(3[4,7]\d{2})(-?|\040?)\d{6}(-?|\040?)\d{5}/; if ( sVal.match(/.+/) && !sVal.match(regexp) ) { isValid = false; $(this).after('<div class="error">' + TEXT_INLINE_FIELD_CC + '</div>'); } } else if ( this.validatetype.indexOf("IsTime") >= 0 ) { if ( sVal.match(/.+/) ) { var regexp = /\d+/g; var arr = sVal.match(regexp); var bFlag = true; if ( arr==null || arr.length > 3 ) { bFlag = false; } while ( bFlag && arr.length < 3 ) { arr[arr.length] = 0; } if( bFlag && (arr[0]<0 || arr[0]>23 || arr[1]<0 || arr[1]>59 || arr[2]<0 || arr[2]>59) ) { bFlag = false; } if ( !bFlag ) { isValid = false; $(this).after('<div class="error">' + TEXT_INLINE_FIELD_TIME + '</div>'); } } } else if ( this.validatetype.indexOf("IsDate") >= 0 ) { var fmt = ""; switch (locale_dateformat) { case 0 : fmt="MDY"; break; case 1 : fmt="DMY"; break; default: fmt="YMD"; break; }; if ( sVal.match(/.+/) && !isValidDate( sVal, fmt ) ) { isValid = false; $(this).after('<div class="error">' + TEXT_INLINE_FIELD_DATE + '</div>'); } } } }); return isValid; } var onthefly_included=true;
JavaScript
var detailspreview_included=true; function preview_inline(link) { var tparents=$(link).parents("tr"); if(!tparents.length) return; var i; for(i=0;i<tparents.length;i++) if($(tparents[i]).attr("rowid")) break; if(i==tparents.length) return; var tr=tparents[i]; var rowid=$(tr).attr("rowid"); // determine record id var pos = link.id.lastIndexOf("_preview"); if(pos<0) return; var recid = new Number(link.id.substring(pos+8)); var dtable=link.id.substring(0,pos); // check if preview TR is created var previewtr=document.getElementById("dpreviewrow_"+rowid); if(!previewtr) { // count number if cells in TR, find current record in row var tchildren=$(tr).children("td"); varcolscount= new Array(); var start=0; tparents=$(link).parents("td"); if(!tparents.length) return; var tdparent=tparents[0]; var myplace=0; for(i=0;i<tchildren.length;i++) { if(tdparent==tchildren[i]) myplace=varcolscount.length; if($(tchildren[i]).attr("colid")=="endrecord") { varcolscount[varcolscount.length]=i-start; start=i+1; } } varcolscount[varcolscount.length]=i-start; // create new TR previewtr=$(tr).clone(); $(previewtr).attr("id","dpreviewrow_"+rowid); $(previewtr).insertAfter(tr); previewtr=document.getElementById("dpreviewrow_"+rowid); // remove all unnecessary TDs $("td[@colid!=endrecord]",previewtr).remove(); // fill row with new TDs tchildren=$(previewtr).children("td"); for(i=0;i<tchildren.length;i++) { $(tchildren[i]).before("<td id=\"dpreview_"+(recid+i-myplace)+"\" colspan="+varcolscount[i]+"></td>"); } if(i) $(tchildren[i-1]).after("<td id=\"dpreview_"+(recid+i-myplace)+"\" colspan="+varcolscount[i]+"></td>"); else $(previewtr).html("<td id=\"dpreview_"+(recid+i-myplace)+"\" colspan="+varcolscount[i]+"></td>"); } // get details page contents var tdpreview = document.getElementById("dpreview_"+recid); if(!tdpreview) return; pos = link.href.indexOf("?"); if(pos<0) return; var url=dtable+"_detailspreview.aspx"+link.href.substr(pos); tdpreview.style.borderWidth="1px"; tdpreview.style.borderStyle="solid"; tdpreview.style.borderColor="darkgray"; if(!tdpreview.innerHTML.length) $(tdpreview).html(TEXT_LOADING + "..."); // change other links to "preview" $("[@id$=_preview"+recid+"]").each(function (){ this.innerHTML=TEXT_PREVIEW; this.onclick=function() {preview_inline(this); return false;}; }); $.get(url, { counter: 0, mode: "inline", rndVal: (new Date().getTime()) }, function(txt){ $(tdpreview).html(txt); $(link).html(TEXT_HIDE); link.onclick=function() {hide_inline(link); return false;}; }); } function hide_inline(link) { $(link).html(TEXT_PREVIEW); link.onclick=function() {preview_inline(link); return false;}; // determine record id var pos = link.id.lastIndexOf("_preview"); if(pos<0) return; var recid = new Number(link.id.substring(pos+8)); var dtable=link.id.substring(0,pos); var tdpreview = document.getElementById("dpreview_"+recid); if(!tdpreview) return; tdpreview.innerHTML=""; tdpreview.style.borderStyle="none"; // check if whole row can be removed var tparents=$(tdpreview).parents("tr"); if(!tparents.length) return; var previewtr=tparents[0]; var tchildren=$(previewtr).children("td"); for(i=0;i<tchildren.length;i++) if($(tchildren[i]).attr("colid")!="endrecord" && tchildren[i].innerHTML.length) break; if(i<tchildren.length) return; $(previewtr).remove(); }
JavaScript
/* prevent execution of jQuery if included more than once */ if(typeof window.jQuery == "undefined") { /* * jQuery 1.1.2 - New Wave Javascript * * Copyright (c) 2007 John Resig (jquery.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * $Date: 2008/07/19 17:30:05 $ * $Rev: 1465 $ */ // Global undefined variable window.undefined = window.undefined; var jQuery = function(a,c) { // If the context is global, return a new object if ( window == this ) return new jQuery(a,c); // Make sure that a selection was provided a = a || document; // HANDLE: $(function) // Shortcut for document ready if ( jQuery.isFunction(a) ) return new jQuery(document)[ jQuery.fn.ready ? "ready" : "load" ]( a ); // Handle HTML strings if ( typeof a == "string" ) { // HANDLE: $(html) -> $(array) var m = /^[^<]*(<(.|\s)+>)[^>]*$/.exec(a); if ( m ) a = jQuery.clean( [ m[1] ] ); // HANDLE: $(expr) else return new jQuery( c ).find( a ); } return this.setArray( // HANDLE: $(array) a.constructor == Array && a || // HANDLE: $(arraylike) // Watch for when an array-like object is passed as the selector (a.jquery || a.length && a != window && !a.nodeType && a[0] != undefined && a[0].nodeType) && jQuery.makeArray( a ) || // HANDLE: $(*) [ a ] ); }; // Map over the $ in case of overwrite if ( typeof $ != "undefined" ) jQuery._$ = $; // Map the jQuery namespace to the '$' one var $ = jQuery; jQuery.fn = jQuery.prototype = { jquery: "1.1.2", size: function() { return this.length; }, length: 0, get: function( num ) { return num == undefined ? // Return a 'clean' array jQuery.makeArray( this ) : // Return just the object this[num]; }, pushStack: function( a ) { var ret = jQuery(a); ret.prevObject = this; return ret; }, setArray: function( a ) { this.length = 0; [].push.apply( this, a ); return this; }, each: function( fn, args ) { return jQuery.each( this, fn, args ); }, index: function( obj ) { var pos = -1; this.each(function(i){ if ( this == obj ) pos = i; }); return pos; }, attr: function( key, value, type ) { var obj = key; // Look for the case where we're accessing a style value if ( key.constructor == String ) if ( value == undefined ) return this.length && jQuery[ type || "attr" ]( this[0], key ) || undefined; else { obj = {}; obj[ key ] = value; } // Check to see if we're setting style values return this.each(function(index){ // Set all the styles for ( var prop in obj ) jQuery.attr( type ? this.style : this, prop, jQuery.prop(this, obj[prop], type, index, prop) ); }); }, css: function( key, value ) { return this.attr( key, value, "curCSS" ); }, text: function(e) { if ( typeof e == "string" ) return this.empty().append( document.createTextNode( e ) ); var t = ""; jQuery.each( e || this, function(){ jQuery.each( this.childNodes, function(){ if ( this.nodeType != 8 ) t += this.nodeType != 1 ? this.nodeValue : jQuery.fn.text([ this ]); }); }); return t; }, wrap: function() { // The elements to wrap the target around var a = jQuery.clean(arguments); // Wrap each of the matched elements individually return this.each(function(){ // Clone the structure that we're using to wrap var b = a[0].cloneNode(true); // Insert it before the element to be wrapped this.parentNode.insertBefore( b, this ); // Find the deepest point in the wrap structure while ( b.firstChild ) b = b.firstChild; // Move the matched element to within the wrap structure b.appendChild( this ); }); }, append: function() { return this.domManip(arguments, true, 1, function(a){ this.appendChild( a ); }); }, prepend: function() { return this.domManip(arguments, true, -1, function(a){ this.insertBefore( a, this.firstChild ); }); }, before: function() { return this.domManip(arguments, false, 1, function(a){ this.parentNode.insertBefore( a, this ); }); }, after: function() { return this.domManip(arguments, false, -1, function(a){ this.parentNode.insertBefore( a, this.nextSibling ); }); }, end: function() { return this.prevObject || jQuery([]); }, find: function(t) { return this.pushStack( jQuery.map( this, function(a){ return jQuery.find(t,a); }), t ); }, clone: function(deep) { return this.pushStack( jQuery.map( this, function(a){ var a = a.cloneNode( deep != undefined ? deep : true ); a.$events = null; // drop $events expando to avoid firing incorrect events return a; }) ); }, filter: function(t) { return this.pushStack( jQuery.isFunction( t ) && jQuery.grep(this, function(el, index){ return t.apply(el, [index]) }) || jQuery.multiFilter(t,this) ); }, not: function(t) { return this.pushStack( t.constructor == String && jQuery.multiFilter(t, this, true) || jQuery.grep(this, function(a) { return ( t.constructor == Array || t.jquery ) ? jQuery.inArray( a, t ) < 0 : a != t; }) ); }, add: function(t) { return this.pushStack( jQuery.merge( this.get(), t.constructor == String ? jQuery(t).get() : t.length != undefined && (!t.nodeName || t.nodeName == "FORM") ? t : [t] ) ); }, is: function(expr) { return expr ? jQuery.filter(expr,this).r.length > 0 : false; }, val: function( val ) { return val == undefined ? ( this.length ? this[0].value : null ) : this.attr( "value", val ); }, html: function( val ) { return val == undefined ? ( this.length ? this[0].innerHTML : null ) : this.empty().append( val ); }, domManip: function(args, table, dir, fn){ var clone = this.length > 1; var a = jQuery.clean(args); if ( dir < 0 ) a.reverse(); return this.each(function(){ var obj = this; if ( table && jQuery.nodeName(this, "table") && jQuery.nodeName(a[0], "tr") ) obj = this.getElementsByTagName("tbody")[0] || this.appendChild(document.createElement("tbody")); jQuery.each( a, function(){ fn.apply( obj, [ clone ? this.cloneNode(true) : this ] ); }); }); } }; jQuery.extend = jQuery.fn.extend = function() { // copy reference to target object var target = arguments[0], a = 1; // extend jQuery itself if only one argument is passed if ( arguments.length == 1 ) { target = this; a = 0; } var prop; while (prop = arguments[a++]) // Extend the base object for ( var i in prop ) target[i] = prop[i]; // Return the modified object return target; }; jQuery.extend({ noConflict: function() { if ( jQuery._$ ) $ = jQuery._$; return jQuery; }, // This may seem like some crazy code, but trust me when I say that this // is the only cross-browser way to do this. --John isFunction: function( fn ) { return !!fn && typeof fn != "string" && !fn.nodeName && typeof fn[0] == "undefined" && /function/i.test( fn + "" ); }, // check if an element is in a XML document isXMLDoc: function(elem) { return elem.tagName && elem.ownerDocument && !elem.ownerDocument.body; }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase(); }, // args is for internal usage only each: function( obj, fn, args ) { if ( obj.length == undefined ) for ( var i in obj ) fn.apply( obj[i], args || [i, obj[i]] ); else for ( var i = 0, ol = obj.length; i < ol; i++ ) if ( fn.apply( obj[i], args || [i, obj[i]] ) === false ) break; return obj; }, prop: function(elem, value, type, index, prop){ // Handle executable functions if ( jQuery.isFunction( value ) ) value = value.call( elem, [index] ); // exclude the following css properties to add px var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i; // Handle passing in a number to a CSS property return value && value.constructor == Number && type == "curCSS" && !exclude.test(prop) ? value + "px" : value; }, className: { // internal only, use addClass("class") add: function( elem, c ){ jQuery.each( c.split(/\s+/), function(i, cur){ if ( !jQuery.className.has( elem.className, cur ) ) elem.className += ( elem.className ? " " : "" ) + cur; }); }, // internal only, use removeClass("class") remove: function( elem, c ){ elem.className = c ? jQuery.grep( elem.className.split(/\s+/), function(cur){ return !jQuery.className.has( c, cur ); }).join(" ") : ""; }, // internal only, use is(".class") has: function( t, c ) { t = t.className || t; // escape regex characters c = c.replace(/([\.\\\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1"); return t && new RegExp("(^|\\s)" + c + "(\\s|$)").test( t ); } }, swap: function(e,o,f) { for ( var i in o ) { e.style["old"+i] = e.style[i]; e.style[i] = o[i]; } f.apply( e, [] ); for ( var i in o ) e.style[i] = e.style["old"+i]; }, css: function(e,p) { if ( p == "height" || p == "width" ) { var old = {}, oHeight, oWidth, d = ["Top","Bottom","Right","Left"]; jQuery.each( d, function(){ old["padding" + this] = 0; old["border" + this + "Width"] = 0; }); jQuery.swap( e, old, function() { if (jQuery.css(e,"display") != "none") { oHeight = e.offsetHeight; oWidth = e.offsetWidth; } else { e = jQuery(e.cloneNode(true)) .find(":radio").removeAttr("checked").end() .css({ visibility: "hidden", position: "absolute", display: "block", right: "0", left: "0" }).appendTo(e.parentNode)[0]; var parPos = jQuery.css(e.parentNode,"position"); if ( parPos == "" || parPos == "static" ) e.parentNode.style.position = "relative"; oHeight = e.clientHeight; oWidth = e.clientWidth; if ( parPos == "" || parPos == "static" ) e.parentNode.style.position = "static"; e.parentNode.removeChild(e); } }); return p == "height" ? oHeight : oWidth; } return jQuery.curCSS( e, p ); }, curCSS: function(elem, prop, force) { var ret; if (prop == "opacity" && jQuery.browser.msie) return jQuery.attr(elem.style, "opacity"); if (prop == "float" || prop == "cssFloat") prop = jQuery.browser.msie ? "styleFloat" : "cssFloat"; if (!force && elem.style[prop]) ret = elem.style[prop]; else if (document.defaultView && document.defaultView.getComputedStyle) { if (prop == "cssFloat" || prop == "styleFloat") prop = "float"; prop = prop.replace(/([A-Z])/g,"-$1").toLowerCase(); var cur = document.defaultView.getComputedStyle(elem, null); if ( cur ) ret = cur.getPropertyValue(prop); else if ( prop == "display" ) ret = "none"; else jQuery.swap(elem, { display: "block" }, function() { var c = document.defaultView.getComputedStyle(this, ""); ret = c && c.getPropertyValue(prop) || ""; }); } else if (elem.currentStyle) { var newProp = prop.replace(/\-(\w)/g,function(m,c){return c.toUpperCase();}); ret = elem.currentStyle[prop] || elem.currentStyle[newProp]; } return ret; }, clean: function(a) { var r = []; jQuery.each( a, function(i,arg){ if ( !arg ) return; if ( arg.constructor == Number ) arg = arg.toString(); // Convert html string into DOM nodes if ( typeof arg == "string" ) { // Trim whitespace, otherwise indexOf won't work as expected var s = jQuery.trim(arg), div = document.createElement("div"), tb = []; var wrap = // option or optgroup !s.indexOf("<opt") && [1, "<select>", "</select>"] || (!s.indexOf("<thead") || !s.indexOf("<tbody") || !s.indexOf("<tfoot")) && [1, "<table>", "</table>"] || !s.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] || // <thead> matched above (!s.indexOf("<td") || !s.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] || [0,"",""]; // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + s + wrap[2]; // Move to the right depth while ( wrap[0]-- ) div = div.firstChild; // Remove IE's autoinserted <tbody> from table fragments if ( jQuery.browser.msie ) { // String was a <table>, *may* have spurious <tbody> if ( !s.indexOf("<table") && s.indexOf("<tbody") < 0 ) tb = div.firstChild && div.firstChild.childNodes; // String was a bare <thead> or <tfoot> else if ( wrap[1] == "<table>" && s.indexOf("<tbody") < 0 ) tb = div.childNodes; for ( var n = tb.length-1; n >= 0 ; --n ) if ( jQuery.nodeName(tb[n], "tbody") && !tb[n].childNodes.length ) tb[n].parentNode.removeChild(tb[n]); } arg = []; for (var i=0, l=div.childNodes.length; i<l; i++) arg.push(div.childNodes[i]); } if ( arg.length === 0 && !jQuery.nodeName(arg, "form") ) return; if ( arg[0] == undefined || jQuery.nodeName(arg, "form") ) r.push( arg ); else r = jQuery.merge( r, arg ); }); return r; }, attr: function(elem, name, value){ var fix = jQuery.isXMLDoc(elem) ? {} : { "for": "htmlFor", "class": "className", "float": jQuery.browser.msie ? "styleFloat" : "cssFloat", cssFloat: jQuery.browser.msie ? "styleFloat" : "cssFloat", innerHTML: "innerHTML", className: "className", value: "value", disabled: "disabled", checked: "checked", readonly: "readOnly", selected: "selected" }; // IE actually uses filters for opacity ... elem is actually elem.style if ( name == "opacity" && jQuery.browser.msie && value != undefined ) { // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level elem.zoom = 1; // Set the alpha filter to set the opacity return elem.filter = elem.filter.replace(/alpha\([^\)]*\)/gi,"") + ( value == 1 ? "" : "alpha(opacity=" + value * 100 + ")" ); } else if ( name == "opacity" && jQuery.browser.msie ) return elem.filter ? parseFloat( elem.filter.match(/alpha\(opacity=(.*)\)/)[1] ) / 100 : 1; // Mozilla doesn't play well with opacity 1 if ( name == "opacity" && jQuery.browser.mozilla && value == 1 ) value = 0.9999; // Certain attributes only work when accessed via the old DOM 0 way if ( fix[name] ) { if ( value != undefined ) elem[fix[name]] = value; return elem[fix[name]]; } else if ( value == undefined && jQuery.browser.msie && jQuery.nodeName(elem, "form") && (name == "action" || name == "method") ) return elem.getAttributeNode(name).nodeValue; // IE elem.getAttribute passes even for style else if ( elem.tagName ) { if ( value != undefined ) elem.setAttribute( name, value ); if ( jQuery.browser.msie && /href|src/.test(name) && !jQuery.isXMLDoc(elem) ) return elem.getAttribute( name, 2 ); return elem.getAttribute( name ); // elem is actually elem.style ... set the style } else { name = name.replace(/-([a-z])/ig,function(z,b){return b.toUpperCase();}); if ( value != undefined ) elem[name] = value; return elem[name]; } }, trim: function(t){ return t.replace(/^\s+|\s+$/g, ""); }, makeArray: function( a ) { var r = []; if ( a.constructor != Array ) for ( var i = 0, al = a.length; i < al; i++ ) r.push( a[i] ); else r = a.slice( 0 ); return r; }, inArray: function( b, a ) { for ( var i = 0, al = a.length; i < al; i++ ) if ( a[i] == b ) return i; return -1; }, merge: function(first, second) { var r = [].slice.call( first, 0 ); // Now check for duplicates between the two arrays // and only add the unique items for ( var i = 0, sl = second.length; i < sl; i++ ) // Check for duplicates if ( jQuery.inArray( second[i], r ) == -1 ) // The item is unique, add it first.push( second[i] ); return first; }, grep: function(elems, fn, inv) { // If a string is passed in for the function, make a function // for it (a handy shortcut) if ( typeof fn == "string" ) fn = new Function("a","i","return " + fn); var result = []; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, el = elems.length; i < el; i++ ) if ( !inv && fn(elems[i],i) || inv && !fn(elems[i],i) ) result.push( elems[i] ); return result; }, map: function(elems, fn) { // If a string is passed in for the function, make a function // for it (a handy shortcut) if ( typeof fn == "string" ) fn = new Function("a","return " + fn); var result = [], r = []; // Go through the array, translating each of the items to their // new value (or values). for ( var i = 0, el = elems.length; i < el; i++ ) { var val = fn(elems[i],i); if ( val !== null && val != undefined ) { if ( val.constructor != Array ) val = [val]; result = result.concat( val ); } } var r = result.length ? [ result[0] ] : []; check: for ( var i = 1, rl = result.length; i < rl; i++ ) { for ( var j = 0; j < i; j++ ) if ( result[i] == r[j] ) continue check; r.push( result[i] ); } return r; } }); /* * Whether the W3C compliant box model is being used. * * @property * @name $.boxModel * @type Boolean * @cat JavaScript */ new function() { var b = navigator.userAgent.toLowerCase(); // Figure out what browser is being used jQuery.browser = { safari: /webkit/.test(b), opera: /opera/.test(b), msie: /msie/.test(b) && !/opera/.test(b), mozilla: /mozilla/.test(b) && !/(compatible|webkit)/.test(b) }; // Check to see if the W3C box model is being used jQuery.boxModel = !jQuery.browser.msie || document.compatMode == "CSS1Compat"; }; jQuery.each({ parent: "a.parentNode", parents: "jQuery.parents(a)", next: "jQuery.nth(a,2,'nextSibling')", prev: "jQuery.nth(a,2,'previousSibling')", siblings: "jQuery.sibling(a.parentNode.firstChild,a)", children: "jQuery.sibling(a.firstChild)" }, function(i,n){ jQuery.fn[ i ] = function(a) { var ret = jQuery.map(this,n); if ( a && typeof a == "string" ) ret = jQuery.multiFilter(a,ret); return this.pushStack( ret ); }; }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after" }, function(i,n){ jQuery.fn[ i ] = function(){ var a = arguments; return this.each(function(){ for ( var j = 0, al = a.length; j < al; j++ ) jQuery(a[j])[n]( this ); }); }; }); jQuery.each( { removeAttr: function( key ) { jQuery.attr( this, key, "" ); this.removeAttribute( key ); }, addClass: function(c){ jQuery.className.add(this,c); }, removeClass: function(c){ jQuery.className.remove(this,c); }, toggleClass: function( c ){ jQuery.className[ jQuery.className.has(this,c) ? "remove" : "add" ](this, c); }, remove: function(a){ if ( !a || jQuery.filter( a, [this] ).r.length ) this.parentNode.removeChild( this ); }, empty: function() { while ( this.firstChild ) this.removeChild( this.firstChild ); } }, function(i,n){ jQuery.fn[ i ] = function() { return this.each( n, arguments ); }; }); jQuery.each( [ "eq", "lt", "gt", "contains" ], function(i,n){ jQuery.fn[ n ] = function(num,fn) { return this.filter( ":" + n + "(" + num + ")", fn ); }; }); jQuery.each( [ "height", "width" ], function(i,n){ jQuery.fn[ n ] = function(h) { return h == undefined ? ( this.length ? jQuery.css( this[0], n ) : null ) : this.css( n, h.constructor == String ? h : h + "px" ); }; }); jQuery.extend({ expr: { "": "m[2]=='*'||jQuery.nodeName(a,m[2])", "#": "a.getAttribute('id')==m[2]", ":": { // Position Checks lt: "i<m[3]-0", gt: "i>m[3]-0", nth: "m[3]-0==i", eq: "m[3]-0==i", first: "i==0", last: "i==r.length-1", even: "i%2==0", odd: "i%2", // Child Checks "nth-child": "jQuery.nth(a.parentNode.firstChild,m[3],'nextSibling',a)==a", "first-child": "jQuery.nth(a.parentNode.firstChild,1,'nextSibling')==a", "last-child": "jQuery.nth(a.parentNode.lastChild,1,'previousSibling')==a", "only-child": "jQuery.sibling(a.parentNode.firstChild).length==1", // Parent Checks parent: "a.firstChild", empty: "!a.firstChild", // Text Check contains: "jQuery.fn.text.apply([a]).indexOf(m[3])>=0", // Visibility visible: 'a.type!="hidden"&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden"', hidden: 'a.type=="hidden"||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden"', // Form attributes enabled: "!a.disabled", disabled: "a.disabled", checked: "a.checked", selected: "a.selected||jQuery.attr(a,'selected')", // Form elements text: "a.type=='text'", radio: "a.type=='radio'", checkbox: "a.type=='checkbox'", file: "a.type=='file'", password: "a.type=='password'", submit: "a.type=='submit'", image: "a.type=='image'", reset: "a.type=='reset'", button: 'a.type=="button"||jQuery.nodeName(a,"button")', input: "/input|select|textarea|button/i.test(a.nodeName)" }, ".": "jQuery.className.has(a,m[2])", "@": { "=": "z==m[4]", "!=": "z!=m[4]", "^=": "z&&!z.indexOf(m[4])", "$=": "z&&z.substr(z.length - m[4].length,m[4].length)==m[4]", "*=": "z&&z.indexOf(m[4])>=0", "": "z", _resort: function(m){ return ["", m[1], m[3], m[2], m[5]]; }, _prefix: "z=a[m[3]];if(!z||/href|src/.test(m[3]))z=jQuery.attr(a,m[3]);" }, "[": "jQuery.find(m[2],a).length" }, // The regular expressions that power the parsing engine parse: [ // Match: [@value='test'], [@foo] /^\[ *(@)([a-z0-9_-]*) *([!*$^=]*) *('?"?)(.*?)\4 *\]/i, // Match: [div], [div p] /^(\[)\s*(.*?(\[.*?\])?[^[]*?)\s*\]/, // Match: :contains('foo') /^(:)([a-z0-9_-]*)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/i, // Match: :even, :last-chlid /^([:.#]*)([a-z0-9_*-]*)/i ], token: [ /^(\/?\.\.)/, "a.parentNode", /^(>|\/)/, "jQuery.sibling(a.firstChild)", /^(\+)/, "jQuery.nth(a,2,'nextSibling')", /^(~)/, function(a){ var s = jQuery.sibling(a.parentNode.firstChild); return s.slice(jQuery.inArray(a,s) + 1); } ], multiFilter: function( expr, elems, not ) { var old, cur = []; while ( expr && expr != old ) { old = expr; var f = jQuery.filter( expr, elems, not ); expr = f.t.replace(/^\s*,\s*/, "" ); cur = not ? elems = f.r : jQuery.merge( cur, f.r ); } return cur; }, find: function( t, context ) { // Quickly handle non-string expressions if ( typeof t != "string" ) return [ t ]; // Make sure that the context is a DOM Element if ( context && !context.nodeType ) context = null; // Set the correct context (if none is provided) context = context || document; // Handle the common XPath // expression if ( !t.indexOf("//") ) { context = context.documentElement; t = t.substr(2,t.length); // And the / root expression } else if ( !t.indexOf("/") ) { context = context.documentElement; t = t.substr(1,t.length); if ( t.indexOf("/") >= 1 ) t = t.substr(t.indexOf("/"),t.length); } // Initialize the search var ret = [context], done = [], last = null; // Continue while a selector expression exists, and while // we're no longer looping upon ourselves while ( t && last != t ) { var r = []; last = t; t = jQuery.trim(t).replace( /^\/\//i, "" ); var foundToken = false; // An attempt at speeding up child selectors that // point to a specific element tag var re = /^[\/>]\s*([a-z0-9*-]+)/i; var m = re.exec(t); if ( m ) { // Perform our own iteration and filter jQuery.each( ret, function(){ for ( var c = this.firstChild; c; c = c.nextSibling ) if ( c.nodeType == 1 && ( jQuery.nodeName(c, m[1]) || m[1] == "*" ) ) r.push( c ); }); ret = r; t = t.replace( re, "" ); if ( t.indexOf(" ") == 0 ) continue; foundToken = true; } else { // Look for pre-defined expression tokens for ( var i = 0; i < jQuery.token.length; i += 2 ) { // Attempt to match each, individual, token in // the specified order var re = jQuery.token[i]; var m = re.exec(t); // If the token match was found if ( m ) { // Map it against the token's handler r = ret = jQuery.map( ret, jQuery.isFunction( jQuery.token[i+1] ) ? jQuery.token[i+1] : function(a){ return eval(jQuery.token[i+1]); }); // And remove the token t = jQuery.trim( t.replace( re, "" ) ); foundToken = true; break; } } } // See if there's still an expression, and that we haven't already // matched a token if ( t && !foundToken ) { // Handle multiple expressions if ( !t.indexOf(",") ) { // Clean the result set if ( ret[0] == context ) ret.shift(); // Merge the result sets jQuery.merge( done, ret ); // Reset the context r = ret = [context]; // Touch up the selector string t = " " + t.substr(1,t.length); } else { // Optomize for the case nodeName#idName var re2 = /^([a-z0-9_-]+)(#)([a-z0-9\\*_-]*)/i; var m = re2.exec(t); // Re-organize the results, so that they're consistent if ( m ) { m = [ 0, m[2], m[3], m[1] ]; } else { // Otherwise, do a traditional filter check for // ID, class, and element selectors re2 = /^([#.]?)([a-z0-9\\*_-]*)/i; m = re2.exec(t); } // Try to do a global search by ID, where we can if ( m[1] == "#" && ret[ret.length-1].getElementById ) { // Optimization for HTML document case var oid = ret[ret.length-1].getElementById(m[2]); // Do a quick check for the existence of the actual ID attribute // to avoid selecting by the name attribute in IE if ( jQuery.browser.msie && oid && oid.id != m[2] ) oid = jQuery('[@id="'+m[2]+'"]', ret[ret.length-1])[0]; // Do a quick check for node name (where applicable) so // that div#foo searches will be really fast ret = r = oid && (!m[3] || jQuery.nodeName(oid, m[3])) ? [oid] : []; } else { // Pre-compile a regular expression to handle class searches if ( m[1] == "." ) var rec = new RegExp("(^|\\s)" + m[2] + "(\\s|$)"); // We need to find all descendant elements, it is more // efficient to use getAll() when we are already further down // the tree - we try to recognize that here jQuery.each( ret, function(){ // Grab the tag name being searched for var tag = m[1] != "" || m[0] == "" ? "*" : m[2]; // Handle IE7 being really dumb about <object>s if ( jQuery.nodeName(this, "object") && tag == "*" ) tag = "param"; jQuery.merge( r, m[1] != "" && ret.length != 1 ? jQuery.getAll( this, [], m[1], m[2], rec ) : this.getElementsByTagName( tag ) ); }); // It's faster to filter by class and be done with it if ( m[1] == "." && ret.length == 1 ) r = jQuery.grep( r, function(e) { return rec.test(e.className); }); // Same with ID filtering if ( m[1] == "#" && ret.length == 1 ) { // Remember, then wipe out, the result set var tmp = r; r = []; // Then try to find the element with the ID jQuery.each( tmp, function(){ if ( this.getAttribute("id") == m[2] ) { r = [ this ]; return false; } }); } ret = r; } t = t.replace( re2, "" ); } } // If a selector string still exists if ( t ) { // Attempt to filter it var val = jQuery.filter(t,r); ret = r = val.r; t = jQuery.trim(val.t); } } // Remove the root context if ( ret && ret[0] == context ) ret.shift(); // And combine the results jQuery.merge( done, ret ); return done; }, filter: function(t,r,not) { // Look for common filter expressions while ( t && /^[a-z[({<*:.#]/i.test(t) ) { var p = jQuery.parse, m; jQuery.each( p, function(i,re){ // Look for, and replace, string-like sequences // and finally build a regexp out of it m = re.exec( t ); if ( m ) { // Remove what we just matched t = t.substring( m[0].length ); // Re-organize the first match if ( jQuery.expr[ m[1] ]._resort ) m = jQuery.expr[ m[1] ]._resort( m ); return false; } }); // :not() is a special case that can be optimized by // keeping it out of the expression list if ( m[1] == ":" && m[2] == "not" ) r = jQuery.filter(m[3], r, true).r; // Handle classes as a special case (this will help to // improve the speed, as the regexp will only be compiled once) else if ( m[1] == "." ) { var re = new RegExp("(^|\\s)" + m[2] + "(\\s|$)"); r = jQuery.grep( r, function(e){ return re.test(e.className || ""); }, not); // Otherwise, find the expression to execute } else { var f = jQuery.expr[m[1]]; if ( typeof f != "string" ) f = jQuery.expr[m[1]][m[2]]; // Build a custom macro to enclose it eval("f = function(a,i){" + ( jQuery.expr[ m[1] ]._prefix || "" ) + "return " + f + "}"); // Execute it against the current filter r = jQuery.grep( r, f, not ); } } // Return an array of filtered elements (r) // and the modified expression string (t) return { r: r, t: t }; }, getAll: function( o, r, token, name, re ) { for ( var s = o.firstChild; s; s = s.nextSibling ) if ( s.nodeType == 1 ) { var add = true; if ( token == "." ) add = s.className && re.test(s.className); else if ( token == "#" ) add = s.getAttribute("id") == name; if ( add ) r.push( s ); if ( token == "#" && r.length ) break; if ( s.firstChild ) jQuery.getAll( s, r, token, name, re ); } return r; }, parents: function( elem ){ var matched = []; var cur = elem.parentNode; while ( cur && cur != document ) { matched.push( cur ); cur = cur.parentNode; } return matched; }, nth: function(cur,result,dir,elem){ result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType == 1 ) num++; if ( num == result || result == "even" && num % 2 == 0 && num > 1 && cur == elem || result == "odd" && num % 2 == 1 && cur == elem ) return cur; } }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType == 1 && (!elem || n != elem) ) r.push( n ); } return r; } }); /* * A number of helper functions used for managing events. * Many of the ideas behind this code orignated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function(element, type, handler, data) { // For whatever reason, IE has trouble passing the window object // around, causing it to be cloned in the process if ( jQuery.browser.msie && element.setInterval != undefined ) element = window; // if data is passed, bind to handler if( data ) handler.data = data; // Make sure that the function being executed has a unique ID if ( !handler.guid ) handler.guid = this.guid++; // Init the element's event structure if (!element.$events) element.$events = {}; // Get the current list of functions bound to this event var handlers = element.$events[type]; // If it hasn't been initialized yet if (!handlers) { // Init the event handler queue handlers = element.$events[type] = {}; // Remember an existing handler, if it's already there if (element["on" + type]) handlers[0] = element["on" + type]; } // Add the function to the element's handler list handlers[handler.guid] = handler; // And bind the global event handler to the element element["on" + type] = this.handle; // Remember the function in a global list (for triggering) if (!this.global[type]) this.global[type] = []; this.global[type].push( element ); }, guid: 1, global: {}, // Detach an event or set of events from an element remove: function(element, type, handler) { if (element.$events) { var i,j,k; if ( type && type.type ) { // type is actually an event object here handler = type.handler; type = type.type; } if (type && element.$events[type]) // remove the given handler for the given type if ( handler ) delete element.$events[type][handler.guid]; // remove all handlers for the given type else for ( i in element.$events[type] ) delete element.$events[type][i]; // remove all handlers else for ( j in element.$events ) this.remove( element, j ); // remove event handler if no more handlers exist for ( k in element.$events[type] ) if (k) { k = true; break; } if (!k) element["on" + type] = null; } }, trigger: function(type, data, element) { // Clone the incoming data, if any data = jQuery.makeArray(data || []); // Handle a global trigger if ( !element ) jQuery.each( this.global[type] || [], function(){ jQuery.event.trigger( type, data, this ); }); // Handle triggering a single element else { var handler = element["on" + type ], val, fn = jQuery.isFunction( element[ type ] ); if ( handler ) { // Pass along a fake event data.unshift( this.fix({ type: type, target: element }) ); // Trigger the event if ( (val = handler.apply( element, data )) !== false ) this.triggered = true; } if ( fn && val !== false ) element[ type ](); this.triggered = false; } }, handle: function(event) { // Handle the second event of a trigger and when // an event is called after a page has unloaded if ( typeof jQuery == "undefined" || jQuery.event.triggered ) return; // Empty object is for triggered events with no data event = jQuery.event.fix( event || window.event || {} ); // returned undefined or false var returnValue; var c = this.$events[event.type]; var args = [].slice.call( arguments, 1 ); args.unshift( event ); for ( var j in c ) { // Pass in a reference to the handler function itself // So that we can later remove it args[0].handler = c[j]; args[0].data = c[j].data; if ( c[j].apply( this, args ) === false ) { event.preventDefault(); event.stopPropagation(); returnValue = false; } } // Clean up added properties in IE to prevent memory leak if (jQuery.browser.msie) event.target = event.preventDefault = event.stopPropagation = event.handler = event.data = null; return returnValue; }, fix: function(event) { // Fix target property, if necessary if ( !event.target && event.srcElement ) event.target = event.srcElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == undefined && event.clientX != undefined ) { var e = document.documentElement, b = document.body; event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft); event.pageY = event.clientY + (e.scrollTop || b.scrollTop); } // check if target is a textnode (safari) if (jQuery.browser.safari && event.target.nodeType == 3) { // store a copy of the original event object // and clone because target is read only var originalEvent = event; event = jQuery.extend({}, originalEvent); // get parentnode from textnode event.target = originalEvent.target.parentNode; // add preventDefault and stopPropagation since // they will not work on the clone event.preventDefault = function() { return originalEvent.preventDefault(); }; event.stopPropagation = function() { return originalEvent.stopPropagation(); }; } // fix preventDefault and stopPropagation if (!event.preventDefault) event.preventDefault = function() { this.returnValue = false; }; if (!event.stopPropagation) event.stopPropagation = function() { this.cancelBubble = true; }; return event; } }; jQuery.fn.extend({ bind: function( type, data, fn ) { return this.each(function(){ jQuery.event.add( this, type, fn || data, data ); }); }, one: function( type, data, fn ) { return this.each(function(){ jQuery.event.add( this, type, function(event) { jQuery(this).unbind(event); return (fn || data).apply( this, arguments); }, data); }); }, unbind: function( type, fn ) { return this.each(function(){ jQuery.event.remove( this, type, fn ); }); }, trigger: function( type, data ) { return this.each(function(){ jQuery.event.trigger( type, data, this ); }); }, toggle: function() { // Save reference to arguments for access in closure var a = arguments; return this.click(function(e) { // Figure out which function to execute this.lastToggle = this.lastToggle == 0 ? 1 : 0; // Make sure that clicks stop e.preventDefault(); // and execute the function return a[this.lastToggle].apply( this, [e] ) || false; }); }, hover: function(f,g) { // A private function for handling mouse 'hovering' function handleHover(e) { // Check if mouse(over|out) are still within the same parent element var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget; // Traverse up the tree while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; }; // If we actually just moused on to a sub-element, ignore it if ( p == this ) return false; // Execute the right function return (e.type == "mouseover" ? f : g).apply(this, [e]); } // Bind the function to the two event listeners return this.mouseover(handleHover).mouseout(handleHover); }, ready: function(f) { // If the DOM is already ready if ( jQuery.isReady ) // Execute the function immediately f.apply( document, [jQuery] ); // Otherwise, remember the function for later else { // Add the function to the wait list jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } ); } return this; } }); jQuery.extend({ /* * All the code that makes DOM Ready work nicely. */ isReady: false, readyList: [], // Handle when the DOM is ready ready: function() { // Make sure that the DOM is not already loaded if ( !jQuery.isReady ) { // Remember that the DOM is ready jQuery.isReady = true; // If there are functions bound, to execute if ( jQuery.readyList ) { // Execute all of them jQuery.each( jQuery.readyList, function(){ this.apply( document ); }); // Reset the list of functions jQuery.readyList = null; } // Remove event lisenter to avoid memory leak if ( jQuery.browser.mozilla || jQuery.browser.opera ) document.removeEventListener( "DOMContentLoaded", jQuery.ready, false ); } } }); new function(){ jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," + "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," + "submit,keydown,keypress,keyup,error").split(","), function(i,o){ // Handle event binding jQuery.fn[o] = function(f){ return f ? this.bind(o, f) : this.trigger(o); }; }); // If Mozilla is used if ( jQuery.browser.mozilla || jQuery.browser.opera ) // Use the handy event callback document.addEventListener( "DOMContentLoaded", jQuery.ready, false ); // If IE is used, use the excellent hack by Matthias Miller // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited else if ( jQuery.browser.msie ) { // Only works if you document.write() it document.write("<scr" + "ipt id=__ie_init defer=true " + "src=//:><\/script>"); // Use the defer script hack var script = document.getElementById("__ie_init"); // script does not exist if jQuery is loaded dynamically if ( script ) script.onreadystatechange = function() { if ( this.readyState != "complete" ) return; this.parentNode.removeChild( this ); jQuery.ready(); }; // Clear from memory script = null; // If Safari is used } else if ( jQuery.browser.safari ) // Continually check to see if the document.readyState is valid jQuery.safariTimer = setInterval(function(){ // loaded and complete are both valid states if ( document.readyState == "loaded" || document.readyState == "complete" ) { // If either one are found, remove the timer clearInterval( jQuery.safariTimer ); jQuery.safariTimer = null; // and execute any waiting functions jQuery.ready(); } }, 10); // A fallback to window.onload, that will always work jQuery.event.add( window, "load", jQuery.ready ); }; // Clean up after IE to avoid memory leaks if (jQuery.browser.msie) jQuery(window).one("unload", function() { var global = jQuery.event.global; for ( var type in global ) { var els = global[type], i = els.length; if ( i && type != 'unload' ) do jQuery.event.remove(els[i-1], type); while (--i); } }); jQuery.fn.extend({ loadIfModified: function( url, params, callback ) { this.load( url, params, callback, 1 ); }, load: function( url, params, callback, ifModified ) { if ( jQuery.isFunction( url ) ) return this.bind("load", url); callback = callback || function(){}; // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = null; // Otherwise, build a param string } else { params = jQuery.param( params ); type = "POST"; } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, data: params, ifModified: ifModified, complete: function(res, status){ if ( status == "success" || !ifModified && status == "notmodified" ) // Inject the HTML into all the matched elements self.attr("innerHTML", res.responseText) // Execute all the scripts inside of the newly-injected HTML .evalScripts() // Execute callback .each( callback, [res.responseText, status, res] ); else callback.apply( self, [res.responseText, status, res] ); } }); return this; }, serialize: function() { return jQuery.param( this ); }, evalScripts: function() { return this.find("script").each(function(){ if ( this.src ) jQuery.getScript( this.src ); else jQuery.globalEval( this.text || this.textContent || this.innerHTML || "" ); }).end(); } }); // If IE is used, create a wrapper for the XMLHttpRequest object if ( !window.XMLHttpRequest ) XMLHttpRequest = function(){ return new ActiveXObject("Microsoft.XMLHTTP"); }; // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){ jQuery.fn[o] = function(f){ return this.bind(o, f); }; }); jQuery.extend({ get: function( url, data, callback, type, ifModified ) { // shift arguments if data argument was ommited if ( jQuery.isFunction( data ) ) { callback = data; data = null; } return jQuery.ajax({ url: url, data: data, success: callback, dataType: type, ifModified: ifModified }); }, getIfModified: function( url, data, callback, type ) { return jQuery.get(url, data, callback, type, 1); }, getScript: function( url, callback ) { return jQuery.get(url, null, callback, "script"); }, getJSON: function( url, data, callback ) { return jQuery.get(url, data, callback, "json"); }, post: function( url, data, callback, type ) { if ( jQuery.isFunction( data ) ) { callback = data; data = {}; } return jQuery.ajax({ type: "POST", url: url, data: data, success: callback, dataType: type }); }, // timeout (ms) //timeout: 0, ajaxTimeout: function( timeout ) { jQuery.ajaxSettings.timeout = timeout; }, ajaxSetup: function( settings ) { jQuery.extend( jQuery.ajaxSettings, settings ); }, ajaxSettings: { global: true, type: "GET", timeout: 0, contentType: "application/x-www-form-urlencoded", processData: true, async: true, data: null }, // Last-Modified header cache for next request lastModified: {}, ajax: function( s ) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); // if data available if ( s.data ) { // convert data if not already a string if (s.processData && typeof s.data != "string") s.data = jQuery.param(s.data); // append data to url for get requests if( s.type.toLowerCase() == "get" ) { // "?" + data or "&" + data (in case there are already params) s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + s.data; // IE likes to send both get and post data, prevent this s.data = null; } } // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) jQuery.event.trigger( "ajaxStart" ); var requestDone = false; // Create the request object var xml = new XMLHttpRequest(); // Open the socket xml.open(s.type, s.url, s.async); // Set the correct header, if data is being sent if ( s.data ) xml.setRequestHeader("Content-Type", s.contentType); // Set the If-Modified-Since header, if ifModified mode. if ( s.ifModified ) xml.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" ); // Set header so the called script knows that it's an XMLHttpRequest xml.setRequestHeader("X-Requested-With", "XMLHttpRequest"); // Make sure the browser sends the right content length if ( xml.overrideMimeType ) xml.setRequestHeader("Connection", "close"); // Allow custom headers/mimetypes if( s.beforeSend ) s.beforeSend(xml); if ( s.global ) jQuery.event.trigger("ajaxSend", [xml, s]); // Wait for a response to come back var onreadystatechange = function(isTimeout){ // The transfer is complete and the data is available, or the request timed out if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) { requestDone = true; // clear poll interval if (ival) { clearInterval(ival); ival = null; } var status; try { status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ? s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error"; // Make sure that the request was successful or notmodified if ( status != "error" ) { // Cache Last-Modified header, if ifModified mode. var modRes; try { modRes = xml.getResponseHeader("Last-Modified"); } catch(e) {} // swallow exception thrown by FF if header is not available if ( s.ifModified && modRes ) jQuery.lastModified[s.url] = modRes; // process the data (runs the xml through httpData regardless of callback) var data = jQuery.httpData( xml, s.dataType ); // If a local callback was specified, fire it and pass it the data if ( s.success ) s.success( data, status ); // Fire the global callback if( s.global ) jQuery.event.trigger( "ajaxSuccess", [xml, s] ); } else jQuery.handleError(s, xml, status); } catch(e) { status = "error"; jQuery.handleError(s, xml, status, e); } // The request was completed if( s.global ) jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) jQuery.event.trigger( "ajaxStop" ); // Process result if ( s.complete ) s.complete(xml, status); // Stop memory leaks if(s.async) xml = null; } }; // don't attach the handler to the request, just poll it instead var ival = setInterval(onreadystatechange, 13); // Timeout checker if ( s.timeout > 0 ) setTimeout(function(){ // Check to see if the request is still happening if ( xml ) { // Cancel the request xml.abort(); if( !requestDone ) onreadystatechange( "timeout" ); } }, s.timeout); // Send the data try { xml.send(s.data); } catch(e) { jQuery.handleError(s, xml, null, e); } // firefox 1.5 doesn't fire statechange for sync requests if ( !s.async ) onreadystatechange(); // return XMLHttpRequest to allow aborting the request etc. return xml; }, handleError: function( s, xml, status, e ) { // If a local callback was specified, fire it if ( s.error ) s.error( xml, status, e ); // Fire the global callback if ( s.global ) jQuery.event.trigger( "ajaxError", [xml, s, e] ); }, // Counter for holding the number of active queries active: 0, // Determines if an XMLHttpRequest was successful or not httpSuccess: function( r ) { try { return !r.status && location.protocol == "file:" || ( r.status >= 200 && r.status < 300 ) || r.status == 304 || jQuery.browser.safari && r.status == undefined; } catch(e){} return false; }, // Determines if an XMLHttpRequest returns NotModified httpNotModified: function( xml, url ) { try { var xmlRes = xml.getResponseHeader("Last-Modified"); // Firefox always returns 200. check Last-Modified date return xml.status == 304 || xmlRes == jQuery.lastModified[url] || jQuery.browser.safari && xml.status == undefined; } catch(e){} return false; }, /* Get the data out of an XMLHttpRequest. * Return parsed XML if content-type header is "xml" and type is "xml" or omitted, * otherwise return plain text. * (String) data - The type of data that you're expecting back, * (e.g. "xml", "html", "script") */ httpData: function( r, type ) { var ct = r.getResponseHeader("content-type"); var data = !type && ct && ct.indexOf("xml") >= 0; data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context if ( type == "script" ) jQuery.globalEval( data ); // Get the JavaScript object, if JSON is used. if ( type == "json" ) eval( "data = " + data ); // evaluate scripts within html if ( type == "html" ) jQuery("<div>").html(data).evalScripts(); return data; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a ) { var s = []; // If an array was passed in, assume that it is an array // of form elements if ( a.constructor == Array || a.jquery ) // Serialize the form elements jQuery.each( a, function(){ s.push( this.name + "=" + this.value ); }); // Otherwise, assume that it's an object of key/value pairs else // Serialize the key/values for ( var j in a ) // If the value is an array then the key names need to be repeated if ( a[j] && a[j].constructor == Array ) jQuery.each( a[j], function(){ s.push( j + "=" + this ); }); else s.push( j + "=" + a[j] ); // Return the resulting serialization return s.join("&"); }, // evalulates a script in global context // not reliable for safari globalEval: function( data ) { if ( window.execScript ) window.execScript( data ); else if ( jQuery.browser.safari ) // safari doesn't provide a synchronous global eval window.setTimeout( data, 0 ); else eval.call( window, data ); } }); jQuery.fn.extend({ show: function(speed,callback){ var hidden = this.filter(":hidden"); speed ? hidden.animate({ height: "show", width: "show", opacity: "show" }, speed, callback) : hidden.each(function(){ this.style.display = this.oldblock ? this.oldblock : ""; if ( jQuery.css(this,"display") == "none" ) this.style.display = "block"; }); return this; }, hide: function(speed,callback){ var visible = this.filter(":visible"); speed ? visible.animate({ height: "hide", width: "hide", opacity: "hide" }, speed, callback) : visible.each(function(){ this.oldblock = this.oldblock || jQuery.css(this,"display"); if ( this.oldblock == "none" ) this.oldblock = "block"; this.style.display = "none"; }); return this; }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2 ){ var args = arguments; return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ? this._toggle( fn, fn2 ) : this.each(function(){ jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ] .apply( jQuery(this), args ); }); }, slideDown: function(speed,callback){ return this.animate({height: "show"}, speed, callback); }, slideUp: function(speed,callback){ return this.animate({height: "hide"}, speed, callback); }, slideToggle: function(speed, callback){ return this.each(function(){ var state = jQuery(this).is(":hidden") ? "show" : "hide"; jQuery(this).animate({height: state}, speed, callback); }); }, fadeIn: function(speed, callback){ return this.animate({opacity: "show"}, speed, callback); }, fadeOut: function(speed, callback){ return this.animate({opacity: "hide"}, speed, callback); }, fadeTo: function(speed,to,callback){ return this.animate({opacity: to}, speed, callback); }, animate: function( prop, speed, easing, callback ) { return this.queue(function(){ this.curAnim = jQuery.extend({}, prop); var opt = jQuery.speed(speed, easing, callback); for ( var p in prop ) { var e = new jQuery.fx( this, opt, p ); if ( prop[p].constructor == Number ) e.custom( e.cur(), prop[p] ); else e[ prop[p] ]( prop ); } }); }, queue: function(type,fn){ if ( !fn ) { fn = type; type = "fx"; } return this.each(function(){ if ( !this.queue ) this.queue = {}; if ( !this.queue[type] ) this.queue[type] = []; this.queue[type].push( fn ); if ( this.queue[type].length == 1 ) fn.apply(this); }); } }); jQuery.extend({ speed: function(speed, easing, fn) { var opt = speed && speed.constructor == Object ? speed : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && easing.constructor != Function && easing }; opt.duration = (opt.duration && opt.duration.constructor == Number ? opt.duration : { slow: 600, fast: 200 }[opt.duration]) || 400; // Queueing opt.old = opt.complete; opt.complete = function(){ jQuery.dequeue(this, "fx"); if ( jQuery.isFunction( opt.old ) ) opt.old.apply( this ); }; return opt; }, easing: {}, queue: {}, dequeue: function(elem,type){ type = type || "fx"; if ( elem.queue && elem.queue[type] ) { // Remove self elem.queue[type].shift(); // Get next function var f = elem.queue[type][0]; if ( f ) f.apply( elem ); } }, /* * I originally wrote fx() as a clone of moo.fx and in the process * of making it small in size the code became illegible to sane * people. You've been warned. */ fx: function( elem, options, prop ){ var z = this; // The styles var y = elem.style; // Store display property var oldDisplay = jQuery.css(elem, "display"); // Make sure that nothing sneaks out y.overflow = "hidden"; // Simple function for setting a style value z.a = function(){ if ( options.step ) options.step.apply( elem, [ z.now ] ); if ( prop == "opacity" ) jQuery.attr(y, "opacity", z.now); // Let attr handle opacity else if ( parseInt(z.now) ) // My hate for IE will never die y[prop] = parseInt(z.now) + "px"; y.display = "block"; // Set display property to block for animation }; // Figure out the maximum number to run to z.max = function(){ return parseFloat( jQuery.css(elem,prop) ); }; // Get the current size z.cur = function(){ var r = parseFloat( jQuery.curCSS(elem, prop) ); return r && r > -10000 ? r : z.max(); }; // Start an animation from one number to another z.custom = function(from,to){ z.startTime = (new Date()).getTime(); z.now = from; z.a(); z.timer = setInterval(function(){ z.step(from, to); }, 13); }; // Simple 'show' function z.show = function(){ if ( !elem.orig ) elem.orig = {}; // Remember where we started, so that we can go back to it later elem.orig[prop] = this.cur(); options.show = true; // Begin the animation z.custom(0, elem.orig[prop]); // Stupid IE, look what you made me do if ( prop != "opacity" ) y[prop] = "1px"; }; // Simple 'hide' function z.hide = function(){ if ( !elem.orig ) elem.orig = {}; // Remember where we started, so that we can go back to it later elem.orig[prop] = this.cur(); options.hide = true; // Begin the animation z.custom(elem.orig[prop], 0); }; //Simple 'toggle' function z.toggle = function() { if ( !elem.orig ) elem.orig = {}; // Remember where we started, so that we can go back to it later elem.orig[prop] = this.cur(); if(oldDisplay == "none") { options.show = true; // Stupid IE, look what you made me do if ( prop != "opacity" ) y[prop] = "1px"; // Begin the animation z.custom(0, elem.orig[prop]); } else { options.hide = true; // Begin the animation z.custom(elem.orig[prop], 0); } }; // Each step of an animation z.step = function(firstNum, lastNum){ var t = (new Date()).getTime(); if (t > options.duration + z.startTime) { // Stop the timer clearInterval(z.timer); z.timer = null; z.now = lastNum; z.a(); if (elem.curAnim) elem.curAnim[ prop ] = true; var done = true; for ( var i in elem.curAnim ) if ( elem.curAnim[i] !== true ) done = false; if ( done ) { // Reset the overflow y.overflow = ""; // Reset the display y.display = oldDisplay; if (jQuery.css(elem, "display") == "none") y.display = "block"; // Hide the element if the "hide" operation was done if ( options.hide ) y.display = "none"; // Reset the properties, if the item has been hidden or shown if ( options.hide || options.show ) for ( var p in elem.curAnim ) if (p == "opacity") jQuery.attr(y, p, elem.orig[p]); else y[p] = ""; } // If a callback was provided, execute it if ( done && jQuery.isFunction( options.complete ) ) // Execute the complete function options.complete.apply( elem ); } else { var n = t - this.startTime; // Figure out where in the animation we are and set the number var p = n / options.duration; // If the easing function exists, then use it z.now = options.easing && jQuery.easing[options.easing] ? jQuery.easing[options.easing](p, n, firstNum, (lastNum-firstNum), options.duration) : // else use default linear easing ((-Math.cos(p*Math.PI)/2) + 0.5) * (lastNum-firstNum) + firstNum; // Perform the next step of the animation z.a(); } }; } }); }
JavaScript
/******************************************************** For more info & download: http://www.ibegin.com/blog/p_ibox.html Created for iBegin.com - local search done right MIT Licensed Style *********************************************************/ var indicator_img_path = "include/images/indicator.gif"; var indicator_img_html = "<img name=\"ibox_indicator\" src=\""+indicator_img_path+"\" alt=\"Loading...\" style=\"width:128px;height:128px;\"/>"; // don't remove the name var opacity_level = 8; // how transparent our overlay bg is var ibAttr = "rel"; // our attribute identifier for our iBox elements var imgPreloader = new Image(); // create an preloader object function init_ibox() { var elem_wrapper = "ibox"; createIbox(document.getElementsByTagName("body")[0]); //create our ibox // elements here start the look up from the start non <a> tags //var docRoot = (document.all) ? document.all : document.getElementsByTagName("*"); // Or make sure we only check <a> tags var docRoot = document.getElementsByTagName("a"); var e; for (var i = 0; i < docRoot.length - 1; i++) { e = docRoot[i]; if(e.getAttribute(ibAttr)) { var t = e.getAttribute(ibAttr); if ((t.indexOf("ibox") != -1) || t.toLowerCase() == "ibox") { // check if this element is an iBox element e.onclick = function() { // rather assign an onclick event var t = this.getAttribute(ibAttr); var params = parseQuery(t.substr(5,999)); var url = this.href; if(this.target != "") {url = this.target} var title = this.title; if(showIbox(url,title,params)) { showBG(); window.onscroll = maintPos; window.onresize = maintPos; } return false; }; } } } } showBG = function() { var box_w = getElem('ibox_w'); box_w.style.opacity = 0; box_w.style.filter = 'alpha(opacity=0)'; setBGOpacity = setOpacity; for (var i=0;i<=opacity_level;i++) {setTimeout("setIboxOpacity('ibox_w',"+i+")",70*i);} // from quirksmode.org box_w.style.display = ""; var pagesize = new getPageSize(); var scrollPos = new getScrollPos(); var ua = navigator.userAgent; if(ua.indexOf("MSIE ") != -1) {box_w.style.width = pagesize.width+'px';} /*else {box_w.style.width = pagesize.width-20+'px';}*/ // scrollbars removed! Hurray! box_w.style.height = pagesize.height+scrollPos.scrollY+'px'; var selectElems = document.getElementsByTagName('select'); for(var i = 0; i < selectElems.length; ++i) { selectElems[i].style.visibility = 'hidden'; } } hideBG = function() { var box_w = getElem('ibox_w'); box_w.style.display = "none"; var selectElems = document.getElementsByTagName('select'); for(var i = 0; i < selectElems.length; ++i) { selectElems[i].style.visibility = 'visible'; } } var loadCancelled = false; showIndicator = function() { var ibox_p = getElem('ibox_progress'); ibox_p.style.display = ""; posToCenter(ibox_p); ibox_p.onclick = function() {hideIbox();hideIndicator();loadCancelled = true;} } hideIndicator = function() { var ibox_p = getElem('ibox_progress'); ibox_p.style.display = "none"; ibox_p.onclick = null; } createIbox = function(elem) { // a trick on just creating an ibox wrapper then doing an innerHTML on our root ibox element var strHTML = "<div id=\"ibox_w\" style=\"display:none;\"></div>"; strHTML += "<div id=\"ibox_progress\" style=\"display:none;\">"; strHTML += indicator_img_html; strHTML += "</div>"; strHTML += "<div id=\"ibox_wrapper\" style=\"display:none\">"; strHTML += "<div id=\"ibox_content\"></div>"; strHTML += "<div id=\"ibox_footer_wrapper\"><div id=\"ibox_close\" style=\"float:right;\">"; strHTML += "<a id=\"ibox_close_a\" href=\"javascript:void(null);\" >Click here to close</a></div>"; strHTML += "<div id=\"ibox_footer\">&nbsp;</div></div></div></div>"; var docBody = document.getElementsByTagName("body")[0]; var ibox = document.createElement("div"); ibox.setAttribute("id","ibox"); ibox.style.display = ''; ibox.innerHTML = strHTML; elem.appendChild(ibox); } var ibox_w_height = 0; showIbox = function(url,title,params) { var ibox = getElem('ibox_wrapper'); var ibox_type = 0; // set title here var ibox_footer = getElem('ibox_footer'); if(title != "") {ibox_footer.innerHTML = title;} else {ibox_footer.innerHTML = "&nbsp;";} // file checking code borrowed from thickbox var urlString = /\.jpg|\.jpeg|\.png|\.gif|\.html|\.htm|\.php|\.cfm|\.asp|\.aspx|\.jsp|\.jst|\.rb|\.rhtml|\.txt/g; var url2 = url; var urlType = url2.toLowerCase().match(urlString); if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif'){ ibox_type = 1; } else if(url.indexOf("#") != -1) { ibox_type = 2; } else if(urlType=='.htm'||urlType=='.html'||urlType=='.php'|| urlType=='.asp'||urlType=='.aspx'||urlType=='.jsp'|| urlType=='.jst'||urlType=='.rb'||urlType=='.txt'||urlType=='.rhtml'|| urlType=='.cfm') { ibox_type = 3; } else { // override our ibox type if forced param exist if(params['type']) {ibox_type = parseInt(params['type']);} else{hideIbox();return false;} } // added by Sergey Kornilov on 11/05/2007 ibox_type=1; ibox_type = parseInt(ibox_type); switch(ibox_type) { case 1: showIndicator(); imgPreloader = new Image(); imgPreloader.onload = function(){ imgPreloader = resizeImageToScreen(imgPreloader); hideIndicator(); var strHTML = "<img name=\"ibox_img\" src=\""+url+"\" style=\"width:"+imgPreloader.width+"px;height:"+imgPreloader.height+"px;border:0;cursor:hand;margin:0;padding:0;position:absolute;\"/>"; if(loadCancelled == false) { // added by Sergey Kornilov on 11/05/2007 var ua = navigator.userAgent; if(ua.indexOf("MSIE ") != -1) { imgPreloader.width+=28; imgPreloader.height+=48; } // set width and height ibox.style.height = imgPreloader.height+'px'; ibox.style.width = imgPreloader.width+'px'; ibox.style.display = ""; ibox.style.visibility = "hidden"; posToCenter(ibox); ibox.style.visibility = "visible"; setIBoxContent(strHTML); } } loadCancelled = false; imgPreloader.src = url; break; case 2: var strHTML = ""; if(params['height']) {ibox.style.height = params['height']+'px';} else {ibox.style.height = '280px';} if(params['width']) {ibox.style.width = params['width']+'px';} else {ibox.style.width = '450px';} ibox.style.display = ""; ibox.style.visibility = "hidden"; posToCenter(ibox); ibox.style.visibility = "visible"; getElem('ibox_content').style.overflow = "auto"; var elemSrcId = url.substr(url.indexOf("#") + 1,1000); var elemSrc = getElem(elemSrcId); if(elemSrc) {strHTML = elemSrc.innerHTML;} setIBoxContent(strHTML); break; case 3: showIndicator(); http.open('get',url,true); http.onreadystatechange = function() { if(http.readyState == 4){ hideIndicator(); if(params['height']) {ibox.style.height = params['height']+'px';} else {ibox.style.height = '280px';} if(params['width']) {ibox.style.width = params['width']+'px';} else {ibox.style.width = '450px';} ibox.style.display = ""; ibox.style.visibility = "hidden"; posToCenter(ibox); ibox.style.visibility = "visible"; getElem('ibox_content').style.overflow = "auto"; var response = http.responseText; setIBoxContent(response); } } http.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); http.send(null); break; default: } ibox.style.opacity = 0; ibox.style.filter = 'alpha(opacity=0)'; var ibox_op_level = 10; setIboxOpacity = setOpacity; for (var i=0;i<=ibox_op_level;i++) {setTimeout("setIboxOpacity('ibox_wrapper',"+i+")",30*i);} if(ibox_type == 2 || ibox_type == 3) { ibox.onclick = null;getElem("ibox_close_a").onclick = function() {hideIbox();} } else {ibox.onclick = hideIbox;getElem("ibox_close_a").onclick = null;} return true; } setOpacity = function (elemid,value) { var e = getElem(elemid); e.style.opacity = value/10; e.style.filter = 'alpha(opacity=' + value*10 + ')'; } resizeImageToScreen = function(objImg) { var pagesize = new getPageSize(); var x = pagesize.width - 100; var y = pagesize.height - 100; if(objImg.width > x) { objImg.height = objImg.height * (x/objImg.width); objImg.width = x; if(objImg.height > y) { objImg.width = objImg.width * (y/objImg.height); objImg.height = y; } } else if(objImg.height > y) { objImg.width = objImg.width * (y/objImg.height); objImg.height = y; if(objImg.width > x) { objImg.height = objImg.height * (x/objImg.width); objImg.width = x; } } return objImg; } maintPos = function() { var ibox = getElem('ibox_wrapper'); var box_w = getElem('ibox_w'); var pagesize = new getPageSize(); var scrollPos = new getScrollPos(); var ua = navigator.userAgent; if(ua.indexOf("MSIE ") != -1) {box_w.style.width = pagesize.width+'px';} /*else {box_w.style.width = pagesize.width-20+'px';}*/ if(ua.indexOf("Opera/9") != -1) {box_w.style.height = document.body.scrollHeight+'px';} else {box_w.style.height = pagesize.height+scrollPos.scrollY+'px';} // alternative 1 //box_w.style.height = document.body.scrollHeight+50+'px'; posToCenter(ibox); } hideIbox = function() { hideBG(); var ibox = getElem('ibox_wrapper'); ibox.style.display = "none"; clearIboxContent(); window.onscroll = null; } posToCenter = function(elem) { var scrollPos = new getScrollPos(); var pageSize = new getPageSize(); var emSize = new getElementSize(elem); var x = Math.round(pageSize.width/2) - (emSize.width /2) + scrollPos.scrollX; var y = Math.round(pageSize.height/2) - (emSize.height /2) + scrollPos.scrollY; elem.style.left = x+'px'; elem.style.top = y+'px'; } getScrollPos = function() { var docElem = document.documentElement; this.scrollX = self.pageXOffset || (docElem&&docElem.scrollLeft) || document.body.scrollLeft; this.scrollY = self.pageYOffset || (docElem&&docElem.scrollTop) || document.body.scrollTop; } getPageSize = function() { var docElem = document.documentElement this.width = self.innerWidth || (docElem&&docElem.clientWidth) || document.body.clientWidth; this.height = self.innerHeight || (docElem&&docElem.clientHeight) || document.body.clientHeight; } getElementSize = function(elem) { this.width = elem.offsetWidth || elem.style.pixelWidth; this.height = elem.offsetHeight || elem.style.pixelHeight; } setIBoxContent = function(str) { clearIboxContent(); var e = getElem('ibox_content'); e.style.overflow = "auto"; e.innerHTML = str; } clearIboxContent = function() { var e = getElem('ibox_content'); e.innerHTML = ""; } getElem = function(elemId) { return document.getElementById(elemId); } // parseQuery code borrowed from thickbox, Thanks Cody! parseQuery = function(query) { var Params = new Object (); if (!query) return Params; var Pairs = query.split(/[;&]/); for ( var i = 0; i < Pairs.length; i++ ) { var KeyVal = Pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) continue; var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ); val = val.replace(/\+/g, ' '); Params[key] = val; } return Params; } /******************************************************** Make this IE7 Compatible ;) http://ajaxian.com/archives/ajax-on-ie-7-check-native-first *********************************************************/ createRequestObject = function() { var xmlhttp; /*@cc_on @if (@_jscript_version>= 5) try {xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try {xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");} catch (E) {xmlhttp = false;} } @else xmlhttp = false; @end @*/ if (!xmlhttp && typeof XMLHttpRequest != "undefined") { try {xmlhttp = new XMLHttpRequest();} catch (e) {xmlhttp = false;} } return xmlhttp; } var http = createRequestObject(); function addEvent(obj, evType, fn){ if (obj.addEventListener){ obj.addEventListener(evType, fn, false); return true; } else if (obj.attachEvent){ var r = obj.attachEvent("on"+evType, fn); return r; } else { return false; } } addEvent(window, 'load', init_ibox);
JavaScript
var maxwidth,maxheight; function CalcMaxPage() { maxwidth=0; maxheight=0; var pages; if($.browser.msie) pages=document.all; else pages=document.getElementsByTagName('*'); for(i=0;i<pages.length;i++) { if(pages[i].name!="page") continue; if(pages[i].offsetWidth>maxwidth) maxwidth = pages[i].offsetWidth; if(pages[i].offsetHeight>maxheight) maxheight = pages[i].offsetHeight; } if(!maxwidth || !maxheight) { maxwidth=document.body.scrollWidth; maxheight=document.body.scrollHeight; } } function RunPDF() { CalcMaxPage(); window.frames['pdf'].location.href=page+'&width='+maxwidth+'&height='+maxheight; // display progress div var pdiv=document.getElementById("progress"); pdiv.innerHTML = "<p>Building PDF<br><span style=\"display:block;background:white;border:solid black 1px;width:100px;height:20px;\"><span id=progress_bar style=\"display:block;background:#6080FF;width:1px;height:100%\"></span></span><br><span id=progress_percent></span>% done</p>"; CheckProgress(); } window.pdfbuilt=0; window.counter=0; var pr_time=(new Date()).valueOf(); var speed=-1; function CheckProgress() { if(window.pdfbuilt) return; $.get("pdfprogress.php",{rndval: Math.random()}, function(txt) { setTimeout("CheckProgress();",1000); var numbers=txt.split(" "); if(numbers.length!=2) return; var total = parseInt(numbers[0]); var progress = parseInt(numbers[1]); if(isNaN(total) || isNaN(progress)) return; var count = Math.floor(progress*100/total); if(speed>0) { var alpha = 0.5-count*0.5/100; count = Math.floor(speed*alpha*((new Date()).valueOf()-pr_time) + count*(1-alpha)); } var pbar=document.getElementById("progress_bar"); var dtime = (new Date()).valueOf()-pr_time; if(dtime) speed = 1.0*count/dtime; pbar.style.width=""+count+"px"; document.getElementById("progress_percent").innerHTML=""+count; }); }
JavaScript
/* * Lazy Load - jQuery plugin for lazy loading images * * Copyright (c) 2007-2013 Mika Tuupola * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Project home: * http://www.appelsiini.net/projects/lazyload * * Version: 1.9.3 * */ (function($, window, document, undefined) { var $window = $(window); $.fn.lazyload = function(options) { var elements = this; var $container; var settings = { threshold : 0, failure_limit : 0, event : "scroll", effect : "show", container : window, data_attribute : "original", skip_invisible : true, appear : null, load : null, placeholder : "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" }; function update() { var counter = 0; elements.each(function() { var $this = $(this); if (settings.skip_invisible && !$this.is(":visible")) { return; } if ($.abovethetop(this, settings) || $.leftofbegin(this, settings)) { /* Nothing. */ } else if (!$.belowthefold(this, settings) && !$.rightoffold(this, settings)) { $this.trigger("appear"); /* if we found an image we'll load, reset the counter */ counter = 0; } else { if (++counter > settings.failure_limit) { return false; } } }); } if(options) { /* Maintain BC for a couple of versions. */ if (undefined !== options.failurelimit) { options.failure_limit = options.failurelimit; delete options.failurelimit; } if (undefined !== options.effectspeed) { options.effect_speed = options.effectspeed; delete options.effectspeed; } $.extend(settings, options); } /* Cache container as jQuery as object. */ $container = (settings.container === undefined || settings.container === window) ? $window : $(settings.container); /* Fire one scroll event per scroll. Not one scroll event per image. */ if (0 === settings.event.indexOf("scroll")) { $container.bind(settings.event, function() { return update(); }); } this.each(function() { var self = this; var $self = $(self); self.loaded = false; /* If no src attribute given use data:uri. */ if ($self.attr("src") === undefined || $self.attr("src") === false) { if ($self.is("img")) { $self.attr("src", settings.placeholder); } } /* When appear is triggered load original image. */ $self.one("appear", function() { if (!this.loaded) { if (settings.appear) { var elements_left = elements.length; settings.appear.call(self, elements_left, settings); } $("<img />") .bind("load", function() { var original = $self.attr("data-" + settings.data_attribute); $self.hide(); if ($self.is("img")) { $self.attr("src", original); } else { $self.css("background-image", "url('" + original + "')"); } $self[settings.effect](settings.effect_speed); self.loaded = true; /* Remove image from array so it is not looped next time. */ var temp = $.grep(elements, function(element) { return !element.loaded; }); elements = $(temp); if (settings.load) { var elements_left = elements.length; settings.load.call(self, elements_left, settings); } }) .attr("src", $self.attr("data-" + settings.data_attribute)); } }); /* When wanted event is triggered load original image */ /* by triggering appear. */ if (0 !== settings.event.indexOf("scroll")) { $self.bind(settings.event, function() { if (!self.loaded) { $self.trigger("appear"); } }); } }); /* Check if something appears when window is resized. */ $window.bind("resize", function() { update(); }); /* With IOS5 force loading images when navigating with back button. */ /* Non optimal workaround. */ if ((/(?:iphone|ipod|ipad).*os 5/gi).test(navigator.appVersion)) { $window.bind("pageshow", function(event) { if (event.originalEvent && event.originalEvent.persisted) { elements.each(function() { $(this).trigger("appear"); }); } }); } /* Force initial check if images should appear. */ $(document).ready(function() { update(); }); return this; }; /* Convenience methods in jQuery namespace. */ /* Use as $.belowthefold(element, {threshold : 100, container : window}) */ $.belowthefold = function(element, settings) { var fold; if (settings.container === undefined || settings.container === window) { fold = (window.innerHeight ? window.innerHeight : $window.height()) + $window.scrollTop(); } else { fold = $(settings.container).offset().top + $(settings.container).height(); } return fold <= $(element).offset().top - settings.threshold; }; $.rightoffold = function(element, settings) { var fold; if (settings.container === undefined || settings.container === window) { fold = $window.width() + $window.scrollLeft(); } else { fold = $(settings.container).offset().left + $(settings.container).width(); } return fold <= $(element).offset().left - settings.threshold; }; $.abovethetop = function(element, settings) { var fold; if (settings.container === undefined || settings.container === window) { fold = $window.scrollTop(); } else { fold = $(settings.container).offset().top; } return fold >= $(element).offset().top + settings.threshold + $(element).height(); }; $.leftofbegin = function(element, settings) { var fold; if (settings.container === undefined || settings.container === window) { fold = $window.scrollLeft(); } else { fold = $(settings.container).offset().left; } return fold >= $(element).offset().left + settings.threshold + $(element).width(); }; $.inviewport = function(element, settings) { return !$.rightoffold(element, settings) && !$.leftofbegin(element, settings) && !$.belowthefold(element, settings) && !$.abovethetop(element, settings); }; /* Custom selectors for your convenience. */ /* Use as $("img:below-the-fold").something() or */ /* $("img").filter(":below-the-fold").something() which is faster */ $.extend($.expr[":"], { "below-the-fold" : function(a) { return $.belowthefold(a, {threshold : 0}); }, "above-the-top" : function(a) { return !$.belowthefold(a, {threshold : 0}); }, "right-of-screen": function(a) { return $.rightoffold(a, {threshold : 0}); }, "left-of-screen" : function(a) { return !$.rightoffold(a, {threshold : 0}); }, "in-viewport" : function(a) { return $.inviewport(a, {threshold : 0}); }, /* Maintain BC for couple of versions. */ "above-the-fold" : function(a) { return !$.belowthefold(a, {threshold : 0}); }, "right-of-fold" : function(a) { return $.rightoffold(a, {threshold : 0}); }, "left-of-fold" : function(a) { return !$.rightoffold(a, {threshold : 0}); } }); })(jQuery, window, document);
JavaScript
/* SWFObject v2.2 <http://code.google.com/p/swfobject/> is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ ;var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null; if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true; X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10); ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0;}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version"); if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)];}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}; }(),k=function(){if(!M.w3){return;}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f(); }if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false);}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee); f();}});if(O==top){(function(){if(J){return;}try{j.documentElement.doScroll("left");}catch(X){setTimeout(arguments.callee,0);return;}f();})();}}if(M.wk){(function(){if(J){return; }if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return;}f();})();}s(f);}}();function f(){if(J){return;}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span")); Z.parentNode.removeChild(Z);}catch(aa){return;}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]();}}function K(X){if(J){X();}else{U[U.length]=X;}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false); }else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false);}else{if(typeof O.attachEvent!=D){i(O,"onload",Y);}else{if(typeof O.onload=="function"){var X=O.onload; O.onload=function(){X();Y();};}else{O.onload=Y;}}}}}function h(){if(T){V();}else{H();}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r); aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(","); M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)];}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return;}}X.removeChild(aa);Z=null;H(); })();}else{H();}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y); if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa);}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall; ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class");}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align"); }var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value"); }}P(ai,ah,Y,ab);}else{p(ae);if(ab){ab(aa);}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z;}ab(aa);}}}}}function z(aa){var X=null; var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y;}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z;}}}return X;}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312); }function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null;}else{l=ae;Q=X;}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"; }if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137";}j.title=j.title.slice(0,47)+" - Flash Player Installation"; var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac; }else{ab.flashvars=ac;}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none"; (function(){if(ae.readyState==4){ae.parentNode.removeChild(ae);}else{setTimeout(arguments.callee,10);}})();}u(aa,ab,X);}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div"); Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y);}else{setTimeout(arguments.callee,10); }})();}else{Y.parentNode.replaceChild(g(Y),Y);}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML;}else{var Y=ab.getElementsByTagName(r)[0]; if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true)); }}}}}return aa;}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X;}if(aa){if(typeof ai.id==D){ai.id=Y;}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]; }else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"';}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"';}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'; }}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id);}else{var Z=C(r);Z.setAttribute("type",q); for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac]);}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac]); }}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab]);}}aa.parentNode.replaceChild(Z,aa);X=Z;}}return X;}function e(Z,X,Y){var aa=C("param"); aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa);}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none"; (function(){if(X.readyState==4){b(Y);}else{setTimeout(arguments.callee,10);}})();}else{X.parentNode.removeChild(X);}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null; }}Y.parentNode.removeChild(Y);}}function c(Z){var X=null;try{X=j.getElementById(Z);}catch(Y){}return X;}function C(X){return j.createElement(X);}function i(Z,X,Y){Z.attachEvent(X,Y); I[I.length]=[Z,X,Y];}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false; }function v(ac,Y,ad,ab){if(M.ie&&M.mac){return;}var aa=j.getElementsByTagName("head")[0];if(!aa){return;}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null; G=null;}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]; }G=X;}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y);}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}")); }}}function w(Z,X){if(!m){return;}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y;}else{v("#"+Z,"visibility:"+Y);}}function L(Y){var Z=/[\\\"<>\.;]/; var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y;}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length; for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2]);}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa]);}for(var Y in M){M[Y]=null;}M=null;for(var X in swfobject){swfobject[X]=null; }swfobject=null;});}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y; w(ab,false);}else{if(Z){Z({success:false,id:ab});}}},getObjectById:function(X){if(M.w3){return z(X);}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah}; if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al];}}aj.data=ab; aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak];}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]; }else{am.flashvars=ai+"="+Z[ai];}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true);}X.success=true;X.ref=an;}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac); return;}else{w(ah,true);}}if(ac){ac(X);}});}else{if(ac){ac(X);}}},switchOffAutoHideShow:function(){m=false;},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}; },hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X);}else{return undefined;}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y); }},removeSWF:function(X){if(M.w3){y(X);}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X);}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash; if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1];}if(aa==null){return L(Z);}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1))); }}}return"";},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"; }}if(E){E(B);}}a=false;}}};}(); /* SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/ SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilzén and Mammon Media and is released under the MIT License: http://www.opensource.org/licenses/mit-license.php SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License: http://www.opensource.org/licenses/mit-license.php */ var SWFUpload;if(SWFUpload==undefined){SWFUpload=function(a){this.initSWFUpload(a)}}SWFUpload.prototype.initSWFUpload=function(b){try{this.customSettings={};this.settings=b;this.eventQueue=[];this.movieName="SWFUpload_"+SWFUpload.movieCount++;this.movieElement=null;SWFUpload.instances[this.movieName]=this;this.initSettings();this.loadFlash();this.displayDebugInfo()}catch(a){delete SWFUpload.instances[this.movieName];throw a}};SWFUpload.instances={};SWFUpload.movieCount=0;SWFUpload.version="2.2.0 2009-03-25";SWFUpload.QUEUE_ERROR={QUEUE_LIMIT_EXCEEDED:-100,FILE_EXCEEDS_SIZE_LIMIT:-110,ZERO_BYTE_FILE:-120,INVALID_FILETYPE:-130};SWFUpload.UPLOAD_ERROR={HTTP_ERROR:-200,MISSING_UPLOAD_URL:-210,IO_ERROR:-220,SECURITY_ERROR:-230,UPLOAD_LIMIT_EXCEEDED:-240,UPLOAD_FAILED:-250,SPECIFIED_FILE_ID_NOT_FOUND:-260,FILE_VALIDATION_FAILED:-270,FILE_CANCELLED:-280,UPLOAD_STOPPED:-290};SWFUpload.FILE_STATUS={QUEUED:-1,IN_PROGRESS:-2,ERROR:-3,COMPLETE:-4,CANCELLED:-5};SWFUpload.BUTTON_ACTION={SELECT_FILE:-100,SELECT_FILES:-110,START_UPLOAD:-120};SWFUpload.CURSOR={ARROW:-1,HAND:-2};SWFUpload.WINDOW_MODE={WINDOW:"window",TRANSPARENT:"transparent",OPAQUE:"opaque"};SWFUpload.completeURL=function(a){if(typeof(a)!=="string"||a.match(/^https?:\/\//i)||a.match(/^\//)){return a}var c=window.location.protocol+"//"+window.location.hostname+(window.location.port?":"+window.location.port:"");var b=window.location.pathname.lastIndexOf("/");if(b<=0){path="/"}else{path=window.location.pathname.substr(0,b)+"/"}return path+a};SWFUpload.prototype.initSettings=function(){this.ensureDefault=function(b,a){this.settings[b]=(this.settings[b]==undefined)?a:this.settings[b]};this.ensureDefault("upload_url","");this.ensureDefault("preserve_relative_urls",false);this.ensureDefault("file_post_name","Filedata");this.ensureDefault("post_params",{});this.ensureDefault("use_query_string",false);this.ensureDefault("requeue_on_error",false);this.ensureDefault("http_success",[]);this.ensureDefault("assume_success_timeout",0);this.ensureDefault("file_types","*.*");this.ensureDefault("file_types_description","All Files");this.ensureDefault("file_size_limit",0);this.ensureDefault("file_upload_limit",0);this.ensureDefault("file_queue_limit",0);this.ensureDefault("flash_url","swfupload.swf");this.ensureDefault("prevent_swf_caching",true);this.ensureDefault("button_image_url","");this.ensureDefault("button_width",1);this.ensureDefault("button_height",1);this.ensureDefault("button_text","");this.ensureDefault("button_text_style","color: #000000; font-size: 16pt;");this.ensureDefault("button_text_top_padding",0);this.ensureDefault("button_text_left_padding",0);this.ensureDefault("button_action",SWFUpload.BUTTON_ACTION.SELECT_FILES);this.ensureDefault("button_disabled",false);this.ensureDefault("button_placeholder_id","");this.ensureDefault("button_placeholder",null);this.ensureDefault("button_cursor",SWFUpload.CURSOR.ARROW);this.ensureDefault("button_window_mode",SWFUpload.WINDOW_MODE.WINDOW);this.ensureDefault("debug",false);this.settings.debug_enabled=this.settings.debug;this.settings.return_upload_start_handler=this.returnUploadStart;this.ensureDefault("swfupload_loaded_handler",null);this.ensureDefault("file_dialog_start_handler",null);this.ensureDefault("file_queued_handler",null);this.ensureDefault("file_queue_error_handler",null);this.ensureDefault("file_dialog_complete_handler",null);this.ensureDefault("upload_start_handler",null);this.ensureDefault("upload_progress_handler",null);this.ensureDefault("upload_error_handler",null);this.ensureDefault("upload_success_handler",null);this.ensureDefault("upload_complete_handler",null);this.ensureDefault("debug_handler",this.debugMessage);this.ensureDefault("custom_settings",{});this.customSettings=this.settings.custom_settings;if(!!this.settings.prevent_swf_caching){this.settings.flash_url=this.settings.flash_url+(this.settings.flash_url.indexOf("?")<0?"?":"&")+"preventswfcaching="+new Date().getTime()}if(!this.settings.preserve_relative_urls){this.settings.upload_url=SWFUpload.completeURL(this.settings.upload_url);this.settings.button_image_url=SWFUpload.completeURL(this.settings.button_image_url)}delete this.ensureDefault};SWFUpload.prototype.loadFlash=function(){var a,b;if(document.getElementById(this.movieName)!==null){throw"ID "+this.movieName+" is already in use. The Flash Object could not be added"}a=document.getElementById(this.settings.button_placeholder_id)||this.settings.button_placeholder;if(a==undefined){throw"Could not find the placeholder element: "+this.settings.button_placeholder_id}b=document.createElement("div");b.innerHTML=this.getFlashHTML();a.parentNode.replaceChild(b.firstChild,a);if(window[this.movieName]==undefined){window[this.movieName]=this.getMovieElement()}};SWFUpload.prototype.getFlashHTML=function(){return['<object id="',this.movieName,'" type="application/x-shockwave-flash" data="',this.settings.flash_url,'" width="',this.settings.button_width,'" height="',this.settings.button_height,'" class="swfupload">','<param name="wmode" value="',this.settings.button_window_mode,'" />','<param name="movie" value="',this.settings.flash_url,'" />','<param name="quality" value="high" />','<param name="menu" value="false" />','<param name="allowScriptAccess" value="always" />','<param name="flashvars" value="'+this.getFlashVars()+'" />',"</object>"].join("")};SWFUpload.prototype.getFlashVars=function(){var b=this.buildParamString();var a=this.settings.http_success.join(",");return["movieName=",encodeURIComponent(this.movieName),"&amp;uploadURL=",encodeURIComponent(this.settings.upload_url),"&amp;useQueryString=",encodeURIComponent(this.settings.use_query_string),"&amp;requeueOnError=",encodeURIComponent(this.settings.requeue_on_error),"&amp;httpSuccess=",encodeURIComponent(a),"&amp;assumeSuccessTimeout=",encodeURIComponent(this.settings.assume_success_timeout),"&amp;params=",encodeURIComponent(b),"&amp;filePostName=",encodeURIComponent(this.settings.file_post_name),"&amp;fileTypes=",encodeURIComponent(this.settings.file_types),"&amp;fileTypesDescription=",encodeURIComponent(this.settings.file_types_description),"&amp;fileSizeLimit=",encodeURIComponent(this.settings.file_size_limit),"&amp;fileUploadLimit=",encodeURIComponent(this.settings.file_upload_limit),"&amp;fileQueueLimit=",encodeURIComponent(this.settings.file_queue_limit),"&amp;debugEnabled=",encodeURIComponent(this.settings.debug_enabled),"&amp;buttonImageURL=",encodeURIComponent(this.settings.button_image_url),"&amp;buttonWidth=",encodeURIComponent(this.settings.button_width),"&amp;buttonHeight=",encodeURIComponent(this.settings.button_height),"&amp;buttonText=",encodeURIComponent(this.settings.button_text),"&amp;buttonTextTopPadding=",encodeURIComponent(this.settings.button_text_top_padding),"&amp;buttonTextLeftPadding=",encodeURIComponent(this.settings.button_text_left_padding),"&amp;buttonTextStyle=",encodeURIComponent(this.settings.button_text_style),"&amp;buttonAction=",encodeURIComponent(this.settings.button_action),"&amp;buttonDisabled=",encodeURIComponent(this.settings.button_disabled),"&amp;buttonCursor=",encodeURIComponent(this.settings.button_cursor)].join("")};SWFUpload.prototype.getMovieElement=function(){if(this.movieElement==undefined){this.movieElement=document.getElementById(this.movieName)}if(this.movieElement===null){throw"Could not find Flash element"}return this.movieElement};SWFUpload.prototype.buildParamString=function(){var c=this.settings.post_params;var b=[];if(typeof(c)==="object"){for(var a in c){if(c.hasOwnProperty(a)){b.push(encodeURIComponent(a.toString())+"="+encodeURIComponent(c[a].toString()))}}}return b.join("&amp;")};SWFUpload.prototype.destroy=function(){try{this.cancelUpload(null,false);var a=null;a=this.getMovieElement();if(a&&typeof(a.CallFunction)==="unknown"){for(var c in a){try{if(typeof(a[c])==="function"){a[c]=null}}catch(e){}}try{a.parentNode.removeChild(a)}catch(b){}}window[this.movieName]=null;SWFUpload.instances[this.movieName]=null;delete SWFUpload.instances[this.movieName];this.movieElement=null;this.settings=null;this.customSettings=null;this.eventQueue=null;this.movieName=null;return true}catch(d){return false}};SWFUpload.prototype.displayDebugInfo=function(){this.debug(["---SWFUpload Instance Info---\n","Version: ",SWFUpload.version,"\n","Movie Name: ",this.movieName,"\n","Settings:\n","\t","upload_url: ",this.settings.upload_url,"\n","\t","flash_url: ",this.settings.flash_url,"\n","\t","use_query_string: ",this.settings.use_query_string.toString(),"\n","\t","requeue_on_error: ",this.settings.requeue_on_error.toString(),"\n","\t","http_success: ",this.settings.http_success.join(", "),"\n","\t","assume_success_timeout: ",this.settings.assume_success_timeout,"\n","\t","file_post_name: ",this.settings.file_post_name,"\n","\t","post_params: ",this.settings.post_params.toString(),"\n","\t","file_types: ",this.settings.file_types,"\n","\t","file_types_description: ",this.settings.file_types_description,"\n","\t","file_size_limit: ",this.settings.file_size_limit,"\n","\t","file_upload_limit: ",this.settings.file_upload_limit,"\n","\t","file_queue_limit: ",this.settings.file_queue_limit,"\n","\t","debug: ",this.settings.debug.toString(),"\n","\t","prevent_swf_caching: ",this.settings.prevent_swf_caching.toString(),"\n","\t","button_placeholder_id: ",this.settings.button_placeholder_id.toString(),"\n","\t","button_placeholder: ",(this.settings.button_placeholder?"Set":"Not Set"),"\n","\t","button_image_url: ",this.settings.button_image_url.toString(),"\n","\t","button_width: ",this.settings.button_width.toString(),"\n","\t","button_height: ",this.settings.button_height.toString(),"\n","\t","button_text: ",this.settings.button_text.toString(),"\n","\t","button_text_style: ",this.settings.button_text_style.toString(),"\n","\t","button_text_top_padding: ",this.settings.button_text_top_padding.toString(),"\n","\t","button_text_left_padding: ",this.settings.button_text_left_padding.toString(),"\n","\t","button_action: ",this.settings.button_action.toString(),"\n","\t","button_disabled: ",this.settings.button_disabled.toString(),"\n","\t","custom_settings: ",this.settings.custom_settings.toString(),"\n","Event Handlers:\n","\t","swfupload_loaded_handler assigned: ",(typeof this.settings.swfupload_loaded_handler==="function").toString(),"\n","\t","file_dialog_start_handler assigned: ",(typeof this.settings.file_dialog_start_handler==="function").toString(),"\n","\t","file_queued_handler assigned: ",(typeof this.settings.file_queued_handler==="function").toString(),"\n","\t","file_queue_error_handler assigned: ",(typeof this.settings.file_queue_error_handler==="function").toString(),"\n","\t","upload_start_handler assigned: ",(typeof this.settings.upload_start_handler==="function").toString(),"\n","\t","upload_progress_handler assigned: ",(typeof this.settings.upload_progress_handler==="function").toString(),"\n","\t","upload_error_handler assigned: ",(typeof this.settings.upload_error_handler==="function").toString(),"\n","\t","upload_success_handler assigned: ",(typeof this.settings.upload_success_handler==="function").toString(),"\n","\t","upload_complete_handler assigned: ",(typeof this.settings.upload_complete_handler==="function").toString(),"\n","\t","debug_handler assigned: ",(typeof this.settings.debug_handler==="function").toString(),"\n"].join(""))};SWFUpload.prototype.addSetting=function(b,c,a){if(c==undefined){return(this.settings[b]=a)}else{return(this.settings[b]=c)}};SWFUpload.prototype.getSetting=function(a){if(this.settings[a]!=undefined){return this.settings[a]}return""};SWFUpload.prototype.callFlash=function(functionName,argumentArray){argumentArray=argumentArray||[];var movieElement=this.getMovieElement();var returnValue,returnString;try{returnString=movieElement.CallFunction('<invoke name="'+functionName+'" returntype="javascript">'+__flash__argumentsToXML(argumentArray,0)+"</invoke>");returnValue=eval(returnString)}catch(ex){throw"Call to "+functionName+" failed"}if(returnValue!=undefined&&typeof returnValue.post==="object"){returnValue=this.unescapeFilePostParams(returnValue)}return returnValue};SWFUpload.prototype.selectFile=function(){this.callFlash("SelectFile")};SWFUpload.prototype.selectFiles=function(){this.callFlash("SelectFiles")};SWFUpload.prototype.startUpload=function(a){this.callFlash("StartUpload",[a])};SWFUpload.prototype.cancelUpload=function(a,b){if(b!==false){b=true}this.callFlash("CancelUpload",[a,b])};SWFUpload.prototype.stopUpload=function(){this.callFlash("StopUpload")};SWFUpload.prototype.getStats=function(){return this.callFlash("GetStats")};SWFUpload.prototype.setStats=function(a){this.callFlash("SetStats",[a])};SWFUpload.prototype.getFile=function(a){if(typeof(a)==="number"){return this.callFlash("GetFileByIndex",[a])}else{return this.callFlash("GetFile",[a])}};SWFUpload.prototype.addFileParam=function(a,b,c){return this.callFlash("AddFileParam",[a,b,c])};SWFUpload.prototype.removeFileParam=function(a,b){this.callFlash("RemoveFileParam",[a,b])};SWFUpload.prototype.setUploadURL=function(a){this.settings.upload_url=a.toString();this.callFlash("SetUploadURL",[a])};SWFUpload.prototype.setPostParams=function(a){this.settings.post_params=a;this.callFlash("SetPostParams",[a])};SWFUpload.prototype.addPostParam=function(a,b){this.settings.post_params[a]=b;this.callFlash("SetPostParams",[this.settings.post_params])};SWFUpload.prototype.removePostParam=function(a){delete this.settings.post_params[a];this.callFlash("SetPostParams",[this.settings.post_params])};SWFUpload.prototype.setFileTypes=function(a,b){this.settings.file_types=a;this.settings.file_types_description=b;this.callFlash("SetFileTypes",[a,b])};SWFUpload.prototype.setFileSizeLimit=function(a){this.settings.file_size_limit=a;this.callFlash("SetFileSizeLimit",[a])};SWFUpload.prototype.setFileUploadLimit=function(a){this.settings.file_upload_limit=a;this.callFlash("SetFileUploadLimit",[a])};SWFUpload.prototype.setFileQueueLimit=function(a){this.settings.file_queue_limit=a;this.callFlash("SetFileQueueLimit",[a])};SWFUpload.prototype.setFilePostName=function(a){this.settings.file_post_name=a;this.callFlash("SetFilePostName",[a])};SWFUpload.prototype.setUseQueryString=function(a){this.settings.use_query_string=a;this.callFlash("SetUseQueryString",[a])};SWFUpload.prototype.setRequeueOnError=function(a){this.settings.requeue_on_error=a;this.callFlash("SetRequeueOnError",[a])};SWFUpload.prototype.setHTTPSuccess=function(a){if(typeof a==="string"){a=a.replace(" ","").split(",")}this.settings.http_success=a;this.callFlash("SetHTTPSuccess",[a])};SWFUpload.prototype.setAssumeSuccessTimeout=function(a){this.settings.assume_success_timeout=a;this.callFlash("SetAssumeSuccessTimeout",[a])};SWFUpload.prototype.setDebugEnabled=function(a){this.settings.debug_enabled=a;this.callFlash("SetDebugEnabled",[a])};SWFUpload.prototype.setButtonImageURL=function(a){if(a==undefined){a=""}this.settings.button_image_url=a;this.callFlash("SetButtonImageURL",[a])};SWFUpload.prototype.setButtonDimensions=function(c,a){this.settings.button_width=c;this.settings.button_height=a;var b=this.getMovieElement();if(b!=undefined){b.style.width=c+"px";b.style.height=a+"px"}this.callFlash("SetButtonDimensions",[c,a])};SWFUpload.prototype.setButtonText=function(a){this.settings.button_text=a;this.callFlash("SetButtonText",[a])};SWFUpload.prototype.setButtonTextPadding=function(b,a){this.settings.button_text_top_padding=a;this.settings.button_text_left_padding=b;this.callFlash("SetButtonTextPadding",[b,a])};SWFUpload.prototype.setButtonTextStyle=function(a){this.settings.button_text_style=a;this.callFlash("SetButtonTextStyle",[a])};SWFUpload.prototype.setButtonDisabled=function(a){this.settings.button_disabled=a;this.callFlash("SetButtonDisabled",[a])};SWFUpload.prototype.setButtonAction=function(a){this.settings.button_action=a;this.callFlash("SetButtonAction",[a])};SWFUpload.prototype.setButtonCursor=function(a){this.settings.button_cursor=a;this.callFlash("SetButtonCursor",[a])};SWFUpload.prototype.queueEvent=function(b,c){if(c==undefined){c=[]}else{if(!(c instanceof Array)){c=[c]}}var a=this;if(typeof this.settings[b]==="function"){this.eventQueue.push(function(){this.settings[b].apply(this,c)});setTimeout(function(){a.executeNextEvent()},0)}else{if(this.settings[b]!==null){throw"Event handler "+b+" is unknown or is not a function"}}};SWFUpload.prototype.executeNextEvent=function(){var a=this.eventQueue?this.eventQueue.shift():null;if(typeof(a)==="function"){a.apply(this)}};SWFUpload.prototype.unescapeFilePostParams=function(c){var e=/[$]([0-9a-f]{4})/i;var f={};var d;if(c!=undefined){for(var a in c.post){if(c.post.hasOwnProperty(a)){d=a;var b;while((b=e.exec(d))!==null){d=d.replace(b[0],String.fromCharCode(parseInt("0x"+b[1],16)))}f[d]=c.post[a]}}c.post=f}return c};SWFUpload.prototype.testExternalInterface=function(){try{return this.callFlash("TestExternalInterface")}catch(a){return false}};SWFUpload.prototype.flashReady=function(){var a=this.getMovieElement();if(!a){this.debug("Flash called back ready but the flash movie can't be found.");return}this.cleanUp(a);this.queueEvent("swfupload_loaded_handler")};SWFUpload.prototype.cleanUp=function(a){try{if(this.movieElement&&typeof(a.CallFunction)==="unknown"){this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");for(var c in a){try{if(typeof(a[c])==="function"){a[c]=null}}catch(b){}}}}catch(d){}window.__flash__removeCallback=function(e,f){try{if(e){e[f]=null}}catch(g){}}};SWFUpload.prototype.fileDialogStart=function(){this.queueEvent("file_dialog_start_handler")};SWFUpload.prototype.fileQueued=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("file_queued_handler",a)};SWFUpload.prototype.fileQueueError=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("file_queue_error_handler",[a,c,b])};SWFUpload.prototype.fileDialogComplete=function(b,c,a){this.queueEvent("file_dialog_complete_handler",[b,c,a])};SWFUpload.prototype.uploadStart=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("return_upload_start_handler",a)};SWFUpload.prototype.returnUploadStart=function(a){var b;if(typeof this.settings.upload_start_handler==="function"){a=this.unescapeFilePostParams(a);b=this.settings.upload_start_handler.call(this,a)}else{if(this.settings.upload_start_handler!=undefined){throw"upload_start_handler must be a function"}}if(b===undefined){b=true}b=!!b;this.callFlash("ReturnUploadStart",[b])};SWFUpload.prototype.uploadProgress=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("upload_progress_handler",[a,c,b])};SWFUpload.prototype.uploadError=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("upload_error_handler",[a,c,b])};SWFUpload.prototype.uploadSuccess=function(b,a,c){b=this.unescapeFilePostParams(b);this.queueEvent("upload_success_handler",[b,a,c])};SWFUpload.prototype.uploadComplete=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("upload_complete_handler",a)};SWFUpload.prototype.debug=function(a){this.queueEvent("debug_handler",a)};SWFUpload.prototype.debugMessage=function(c){if(this.settings.debug){var a,d=[];if(typeof c==="object"&&typeof c.name==="string"&&typeof c.message==="string"){for(var b in c){if(c.hasOwnProperty(b)){d.push(b+": "+c[b])}}a=d.join("\n")||"";d=a.split("\n");a="EXCEPTION: "+d.join("\nEXCEPTION: ");SWFUpload.Console.writeLine(a)}else{SWFUpload.Console.writeLine(c)}}};SWFUpload.Console={};SWFUpload.Console.writeLine=function(d){var b,a;try{b=document.getElementById("SWFUpload_Console");if(!b){a=document.createElement("form");document.getElementsByTagName("body")[0].appendChild(a);b=document.createElement("textarea");b.id="SWFUpload_Console";b.style.fontFamily="monospace";b.setAttribute("wrap","off");b.wrap="off";b.style.overflow="auto";b.style.width="700px";b.style.height="350px";b.style.margin="5px";a.appendChild(b)}b.value+=d+"\n";b.scrollTop=b.scrollHeight-b.clientHeight}catch(c){alert("Exception: "+c.name+" Message: "+c.message)}}; /* Uploadify v3.2 Copyright (c) 2012 Reactive Apps, Ronnie Garcia Released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ (function($) { // These methods can be called by adding them as the first argument in the uploadify plugin call var methods = { init : function(options, swfUploadOptions) { return this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this); // Clone the original DOM object var $clone = $this.clone(); // Setup the default options var settings = $.extend({ // Required Settings id : $this.attr('id'), // The ID of the DOM object swf : 'uploadify.swf', // The path to the uploadify SWF file uploader : 'uploadify.php', // The path to the server-side upload script // Options auto : true, // Automatically upload files when added to the queue buttonClass : '', // A class name to add to the browse button DOM object buttonCursor : 'hand', // The cursor to use with the browse button buttonImage : null, // (String or null) The path to an image to use for the Flash browse button if not using CSS to style the button buttonText : 'SELECT FILES', // The text to use for the browse button checkExisting : false, // The path to a server-side script that checks for existing files on the server debug : false, // Turn on swfUpload debugging mode fileObjName : 'Filedata', // The name of the file object to use in your server-side script fileSizeLimit : 0, // The maximum size of an uploadable file in KB (Accepts units B KB MB GB if string, 0 for no limit) fileTypeDesc : 'All Files', // The description for file types in the browse dialog fileTypeExts : '*.*', // Allowed extensions in the browse dialog (server-side validation should also be used) height : 30, // The height of the browse button itemTemplate : false, // The template for the file item in the queue method : 'post', // The method to use when sending files to the server-side upload script multi : true, // Allow multiple file selection in the browse dialog formData : {}, // An object with additional data to send to the server-side upload script with every file upload preventCaching : true, // Adds a random value to the Flash URL to prevent caching of it (conflicts with existing parameters) progressData : 'percentage', // ('percentage' or 'speed') Data to show in the queue item during a file upload queueID : false, // The ID of the DOM object to use as a file queue (without the #) queueSizeLimit : 999, // The maximum number of files that can be in the queue at one time removeCompleted : true, // Remove queue items from the queue when they are done uploading removeTimeout : 3, // The delay in seconds before removing a queue item if removeCompleted is set to true requeueErrors : false, // Keep errored files in the queue and keep trying to upload them successTimeout : 30, // The number of seconds to wait for Flash to detect the server's response after the file has finished uploading uploadLimit : 0, // The maximum number of files you can upload width : 120, // The width of the browse button // Events overrideEvents : [] // (Array) A list of default event handlers to skip /* onCancel // Triggered when a file is cancelled from the queue onClearQueue // Triggered during the 'clear queue' method onDestroy // Triggered when the uploadify object is destroyed onDialogClose // Triggered when the browse dialog is closed onDialogOpen // Triggered when the browse dialog is opened onDisable // Triggered when the browse button gets disabled onEnable // Triggered when the browse button gets enabled onFallback // Triggered is Flash is not detected onInit // Triggered when Uploadify is initialized onQueueComplete // Triggered when all files in the queue have been uploaded onSelectError // Triggered when an error occurs while selecting a file (file size, queue size limit, etc.) onSelect // Triggered for each file that is selected onSWFReady // Triggered when the SWF button is loaded onUploadComplete // Triggered when a file upload completes (success or error) onUploadError // Triggered when a file upload returns an error onUploadSuccess // Triggered when a file is uploaded successfully onUploadProgress // Triggered every time a file progress is updated onUploadStart // Triggered immediately before a file upload starts */ }, options); // Prepare settings for SWFUpload var swfUploadSettings = { assume_success_timeout : settings.successTimeout, button_placeholder_id : settings.id, button_width : settings.width, button_height : settings.height, button_text : null, button_text_style : null, button_text_top_padding : 0, button_text_left_padding : 0, button_action : (settings.multi ? SWFUpload.BUTTON_ACTION.SELECT_FILES : SWFUpload.BUTTON_ACTION.SELECT_FILE), button_disabled : false, button_cursor : (settings.buttonCursor == 'arrow' ? SWFUpload.CURSOR.ARROW : SWFUpload.CURSOR.HAND), button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT, debug : settings.debug, requeue_on_error : settings.requeueErrors, file_post_name : settings.fileObjName, file_size_limit : settings.fileSizeLimit, file_types : settings.fileTypeExts, file_types_description : settings.fileTypeDesc, file_queue_limit : settings.queueSizeLimit, file_upload_limit : settings.uploadLimit, flash_url : settings.swf, prevent_swf_caching : settings.preventCaching, post_params : settings.formData, upload_url : settings.uploader, use_query_string : (settings.method == 'get'), // Event Handlers file_dialog_complete_handler : handlers.onDialogClose, file_dialog_start_handler : handlers.onDialogOpen, file_queued_handler : handlers.onSelect, file_queue_error_handler : handlers.onSelectError, swfupload_loaded_handler : settings.onSWFReady, upload_complete_handler : handlers.onUploadComplete, upload_error_handler : handlers.onUploadError, upload_progress_handler : handlers.onUploadProgress, upload_start_handler : handlers.onUploadStart, upload_success_handler : handlers.onUploadSuccess } // Merge the user-defined options with the defaults if (swfUploadOptions) { swfUploadSettings = $.extend(swfUploadSettings, swfUploadOptions); } // Add the user-defined settings to the swfupload object swfUploadSettings = $.extend(swfUploadSettings, settings); // Detect if Flash is available var playerVersion = swfobject.getFlashPlayerVersion(); var flashInstalled = (playerVersion.major >= 9); if (flashInstalled) { // Create the swfUpload instance window['uploadify_' + settings.id] = new SWFUpload(swfUploadSettings); var swfuploadify = window['uploadify_' + settings.id]; // Add the SWFUpload object to the elements data object $this.data('uploadify', swfuploadify); // Wrap the instance var $wrapper = $('<div />', { 'id' : settings.id, 'class' : 'uploadify', 'css' : { 'height' : settings.height + 'px', 'width' : settings.width + 'px' } }); $('#' + swfuploadify.movieName).wrap($wrapper); // Recreate the reference to wrapper $wrapper = $('#' + settings.id); // Add the data object to the wrapper $wrapper.data('uploadify', swfuploadify); // Create the button var $button = $('<div />', { 'id' : settings.id + '-button', 'class' : 'uploadify-button ' + settings.buttonClass }); if (settings.buttonImage) { $button.css({ 'background-image' : "url('" + settings.buttonImage + "')", 'text-indent' : '-9999px' }); } $button.html('<span class="uploadify-button-text">' + settings.buttonText + '</span>') .css({ 'height' : settings.height + 'px', 'line-height' : settings.height + 'px', 'width' : settings.width + 'px' }); // Append the button to the wrapper $wrapper.append($button); // Adjust the styles of the movie $('#' + swfuploadify.movieName).css({ 'position' : 'absolute', 'z-index' : 1 }); // Create the file queue if (!settings.queueID) { var $queue = $('<div />', { 'id' : settings.id + '-queue', 'class' : 'uploadify-queue' }); $wrapper.after($queue); swfuploadify.settings.queueID = settings.id + '-queue'; swfuploadify.settings.defaultQueue = true; } // Create some queue related objects and variables swfuploadify.queueData = { files : {}, // The files in the queue filesSelected : 0, // The number of files selected in the last select operation filesQueued : 0, // The number of files added to the queue in the last select operation filesReplaced : 0, // The number of files replaced in the last select operation filesCancelled : 0, // The number of files that were cancelled instead of replaced filesErrored : 0, // The number of files that caused error in the last select operation uploadsSuccessful : 0, // The number of files that were successfully uploaded uploadsErrored : 0, // The number of files that returned errors during upload averageSpeed : 0, // The average speed of the uploads in KB queueLength : 0, // The number of files in the queue queueSize : 0, // The size in bytes of the entire queue uploadSize : 0, // The size in bytes of the upload queue queueBytesUploaded : 0, // The size in bytes that have been uploaded for the current upload queue uploadQueue : [], // The files currently to be uploaded errorMsg : 'Some files were not added to the queue:' }; // Save references to all the objects swfuploadify.original = $clone; swfuploadify.wrapper = $wrapper; swfuploadify.button = $button; swfuploadify.queue = $queue; // Call the user-defined init event handler if (settings.onInit) settings.onInit.call($this, swfuploadify); } else { // Call the fallback function if (settings.onFallback) settings.onFallback.call($this); } }); }, // Stop a file upload and remove it from the queue cancel : function(fileID, supressEvent) { var args = arguments; this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'), settings = swfuploadify.settings, delay = -1; if (args[0]) { // Clear the queue if (args[0] == '*') { var queueItemCount = swfuploadify.queueData.queueLength; $('#' + settings.queueID).find('.uploadify-queue-item').each(function() { delay++; if (args[1] === true) { swfuploadify.cancelUpload($(this).attr('id'), false); } else { swfuploadify.cancelUpload($(this).attr('id')); } $(this).find('.data').removeClass('data').html(' - Cancelled'); $(this).find('.uploadify-progress-bar').remove(); $(this).delay(1000 + 100 * delay).fadeOut(500, function() { $(this).remove(); }); }); swfuploadify.queueData.queueSize = 0; swfuploadify.queueData.queueLength = 0; // Trigger the onClearQueue event if (settings.onClearQueue) settings.onClearQueue.call($this, queueItemCount); } else { for (var n = 0; n < args.length; n++) { swfuploadify.cancelUpload(args[n]); $('#' + args[n]).find('.data').removeClass('data').html(' - Cancelled'); $('#' + args[n]).find('.uploadify-progress-bar').remove(); $('#' + args[n]).delay(1000 + 100 * n).fadeOut(500, function() { $(this).remove(); }); } } } else { var item = $('#' + settings.queueID).find('.uploadify-queue-item').get(0); $item = $(item); swfuploadify.cancelUpload($item.attr('id')); $item.find('.data').removeClass('data').html(' - Cancelled'); $item.find('.uploadify-progress-bar').remove(); $item.delay(1000).fadeOut(500, function() { $(this).remove(); }); } }); }, // Revert the DOM object back to its original state destroy : function() { this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'), settings = swfuploadify.settings; // Destroy the SWF object and swfuploadify.destroy(); // Destroy the queue if (settings.defaultQueue) { $('#' + settings.queueID).remove(); } // Reload the original DOM element $('#' + settings.id).replaceWith(swfuploadify.original); // Call the user-defined event handler if (settings.onDestroy) settings.onDestroy.call(this); delete swfuploadify; }); }, // Disable the select button disable : function(isDisabled) { this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'), settings = swfuploadify.settings; // Call the user-defined event handlers if (isDisabled) { swfuploadify.button.addClass('disabled'); if (settings.onDisable) settings.onDisable.call(this); } else { swfuploadify.button.removeClass('disabled'); if (settings.onEnable) settings.onEnable.call(this); } // Enable/disable the browse button swfuploadify.setButtonDisabled(isDisabled); }); }, // Get or set the settings data settings : function(name, value, resetObjects) { var args = arguments; var returnValue = value; this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'), settings = swfuploadify.settings; if (typeof(args[0]) == 'object') { for (var n in value) { setData(n,value[n]); } } if (args.length === 1) { returnValue = settings[name]; } else { switch (name) { case 'uploader': swfuploadify.setUploadURL(value); break; case 'formData': if (!resetObjects) { value = $.extend(settings.formData, value); } swfuploadify.setPostParams(settings.formData); break; case 'method': if (value == 'get') { swfuploadify.setUseQueryString(true); } else { swfuploadify.setUseQueryString(false); } break; case 'fileObjName': swfuploadify.setFilePostName(value); break; case 'fileTypeExts': swfuploadify.setFileTypes(value, settings.fileTypeDesc); break; case 'fileTypeDesc': swfuploadify.setFileTypes(settings.fileTypeExts, value); break; case 'fileSizeLimit': swfuploadify.setFileSizeLimit(value); break; case 'uploadLimit': swfuploadify.setFileUploadLimit(value); break; case 'queueSizeLimit': swfuploadify.setFileQueueLimit(value); break; case 'buttonImage': swfuploadify.button.css('background-image', settingValue); break; case 'buttonCursor': if (value == 'arrow') { swfuploadify.setButtonCursor(SWFUpload.CURSOR.ARROW); } else { swfuploadify.setButtonCursor(SWFUpload.CURSOR.HAND); } break; case 'buttonText': $('#' + settings.id + '-button').find('.uploadify-button-text').html(value); break; case 'width': swfuploadify.setButtonDimensions(value, settings.height); break; case 'height': swfuploadify.setButtonDimensions(settings.width, value); break; case 'multi': if (value) { swfuploadify.setButtonAction(SWFUpload.BUTTON_ACTION.SELECT_FILES); } else { swfuploadify.setButtonAction(SWFUpload.BUTTON_ACTION.SELECT_FILE); } break; } settings[name] = value; } }); if (args.length === 1) { return returnValue; } }, // Stop the current uploads and requeue what is in progress stop : function() { this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'); // Reset the queue information swfuploadify.queueData.averageSpeed = 0; swfuploadify.queueData.uploadSize = 0; swfuploadify.queueData.bytesUploaded = 0; swfuploadify.queueData.uploadQueue = []; swfuploadify.stopUpload(); }); }, // Start uploading files in the queue upload : function() { var args = arguments; this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'); // Reset the queue information swfuploadify.queueData.averageSpeed = 0; swfuploadify.queueData.uploadSize = 0; swfuploadify.queueData.bytesUploaded = 0; swfuploadify.queueData.uploadQueue = []; // Upload the files if (args[0]) { if (args[0] == '*') { swfuploadify.queueData.uploadSize = swfuploadify.queueData.queueSize; swfuploadify.queueData.uploadQueue.push('*'); swfuploadify.startUpload(); } else { for (var n = 0; n < args.length; n++) { swfuploadify.queueData.uploadSize += swfuploadify.queueData.files[args[n]].size; swfuploadify.queueData.uploadQueue.push(args[n]); } swfuploadify.startUpload(swfuploadify.queueData.uploadQueue.shift()); } } else { swfuploadify.startUpload(); } }); } } // These functions handle all the events that occur with the file uploader var handlers = { // Triggered when the file dialog is opened onDialogOpen : function() { // Load the swfupload settings var settings = this.settings; // Reset some queue info this.queueData.errorMsg = 'Some files were not added to the queue:'; this.queueData.filesReplaced = 0; this.queueData.filesCancelled = 0; // Call the user-defined event handler if (settings.onDialogOpen) settings.onDialogOpen.call(this); }, // Triggered when the browse dialog is closed onDialogClose : function(filesSelected, filesQueued, queueLength) { // Load the swfupload settings var settings = this.settings; // Update the queue information this.queueData.filesErrored = filesSelected - filesQueued; this.queueData.filesSelected = filesSelected; this.queueData.filesQueued = filesQueued - this.queueData.filesCancelled; this.queueData.queueLength = queueLength; // Run the default event handler if ($.inArray('onDialogClose', settings.overrideEvents) < 0) { if (this.queueData.filesErrored > 0) { alert(this.queueData.errorMsg); } } // Call the user-defined event handler if (settings.onDialogClose) settings.onDialogClose.call(this, this.queueData); // Upload the files if auto is true if (settings.auto) $('#' + settings.id).uploadify('upload', '*'); }, // Triggered once for each file added to the queue onSelect : function(file) { // Load the swfupload settings var settings = this.settings; // Check if a file with the same name exists in the queue var queuedFile = {}; for (var n in this.queueData.files) { queuedFile = this.queueData.files[n]; if (queuedFile.uploaded != true && queuedFile.name == file.name) { var replaceQueueItem = confirm('The file named "' + file.name + '" is already in the queue.\nDo you want to replace the existing item in the queue?'); if (!replaceQueueItem) { this.cancelUpload(file.id); this.queueData.filesCancelled++; return false; } else { $('#' + queuedFile.id).remove(); this.cancelUpload(queuedFile.id); this.queueData.filesReplaced++; } } } // Get the size of the file var fileSize = Math.round(file.size / 1024); var suffix = 'KB'; if (fileSize > 1000) { fileSize = Math.round(fileSize / 1000); suffix = 'MB'; } var fileSizeParts = fileSize.toString().split('.'); fileSize = fileSizeParts[0]; if (fileSizeParts.length > 1) { fileSize += '.' + fileSizeParts[1].substr(0,2); } fileSize += suffix; // Truncate the filename if it's too long var fileName = file.name; if (fileName.length > 25) { fileName = fileName.substr(0,25) + '...'; } // Create the file data object itemData = { 'fileID' : file.id, 'instanceID' : settings.id, 'fileName' : fileName, 'fileSize' : fileSize } // Create the file item template if (settings.itemTemplate == false) { settings.itemTemplate = '<div id="${fileID}" class="uploadify-queue-item">\ <div class="cancel">\ <a href="javascript:$(\'#${instanceID}\').uploadify(\'cancel\', \'${fileID}\')">X</a>\ </div>\ <span class="fileName">${fileName} (${fileSize})</span><span class="data"></span>\ <div class="uploadify-progress">\ <div class="uploadify-progress-bar"><!--Progress Bar--></div>\ </div>\ </div>'; } // Run the default event handler if ($.inArray('onSelect', settings.overrideEvents) < 0) { // Replace the item data in the template itemHTML = settings.itemTemplate; for (var d in itemData) { itemHTML = itemHTML.replace(new RegExp('\\$\\{' + d + '\\}', 'g'), itemData[d]); } // Add the file item to the queue $('#' + settings.queueID).append(itemHTML); } this.queueData.queueSize += file.size; this.queueData.files[file.id] = file; // Call the user-defined event handler if (settings.onSelect) settings.onSelect.apply(this, arguments); }, // Triggered when a file is not added to the queue onSelectError : function(file, errorCode, errorMsg) { // Load the swfupload settings var settings = this.settings; // Run the default event handler if ($.inArray('onSelectError', settings.overrideEvents) < 0) { switch(errorCode) { case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED: if (settings.queueSizeLimit > errorMsg) { this.queueData.errorMsg += '\nThe number of files selected exceeds the remaining upload limit (' + errorMsg + ').'; } else { this.queueData.errorMsg += '\nThe number of files selected exceeds the queue size limit (' + settings.queueSizeLimit + ').'; } break; case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: this.queueData.errorMsg += '\nThe file "' + file.name + '" exceeds the size limit (' + settings.fileSizeLimit + ').'; break; case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: this.queueData.errorMsg += '\nThe file "' + file.name + '" is empty.'; break; case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: this.queueData.errorMsg += '\nThe file "' + file.name + '" is not an accepted file type (' + settings.fileTypeDesc + ').'; break; } } if (errorCode != SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) { delete this.queueData.files[file.id]; } // Call the user-defined event handler if (settings.onSelectError) settings.onSelectError.apply(this, arguments); }, // Triggered when all the files in the queue have been processed onQueueComplete : function() { if (this.settings.onQueueComplete) this.settings.onQueueComplete.call(this, this.settings.queueData); }, // Triggered when a file upload successfully completes onUploadComplete : function(file) { // Load the swfupload settings var settings = this.settings, swfuploadify = this; // Check if all the files have completed uploading var stats = this.getStats(); this.queueData.queueLength = stats.files_queued; if (this.queueData.uploadQueue[0] == '*') { if (this.queueData.queueLength > 0) { this.startUpload(); } else { this.queueData.uploadQueue = []; // Call the user-defined event handler for queue complete if (settings.onQueueComplete) settings.onQueueComplete.call(this, this.queueData); } } else { if (this.queueData.uploadQueue.length > 0) { this.startUpload(this.queueData.uploadQueue.shift()); } else { this.queueData.uploadQueue = []; // Call the user-defined event handler for queue complete if (settings.onQueueComplete) settings.onQueueComplete.call(this, this.queueData); } } // Call the default event handler if ($.inArray('onUploadComplete', settings.overrideEvents) < 0) { if (settings.removeCompleted) { switch (file.filestatus) { case SWFUpload.FILE_STATUS.COMPLETE: setTimeout(function() { if ($('#' + file.id)) { swfuploadify.queueData.queueSize -= file.size; swfuploadify.queueData.queueLength -= 1; delete swfuploadify.queueData.files[file.id] $('#' + file.id).fadeOut(500, function() { $(this).remove(); }); } }, settings.removeTimeout * 1000); break; case SWFUpload.FILE_STATUS.ERROR: if (!settings.requeueErrors) { setTimeout(function() { if ($('#' + file.id)) { swfuploadify.queueData.queueSize -= file.size; swfuploadify.queueData.queueLength -= 1; delete swfuploadify.queueData.files[file.id]; $('#' + file.id).fadeOut(500, function() { $(this).remove(); }); } }, settings.removeTimeout * 1000); } break; } } else { file.uploaded = true; } } // Call the user-defined event handler if (settings.onUploadComplete) settings.onUploadComplete.call(this, file); }, // Triggered when a file upload returns an error onUploadError : function(file, errorCode, errorMsg) { // Load the swfupload settings var settings = this.settings; // Set the error string var errorString = 'Error'; switch(errorCode) { case SWFUpload.UPLOAD_ERROR.HTTP_ERROR: errorString = 'HTTP Error (' + errorMsg + ')'; break; case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL: errorString = 'Missing Upload URL'; break; case SWFUpload.UPLOAD_ERROR.IO_ERROR: errorString = 'IO Error'; break; case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR: errorString = 'Security Error'; break; case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: alert('The upload limit has been reached (' + errorMsg + ').'); errorString = 'Exceeds Upload Limit'; break; case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED: errorString = 'Failed'; break; case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND: break; case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED: errorString = 'Validation Error'; break; case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED: errorString = 'Cancelled'; this.queueData.queueSize -= file.size; this.queueData.queueLength -= 1; if (file.status == SWFUpload.FILE_STATUS.IN_PROGRESS || $.inArray(file.id, this.queueData.uploadQueue) >= 0) { this.queueData.uploadSize -= file.size; } // Trigger the onCancel event if (settings.onCancel) settings.onCancel.call(this, file); delete this.queueData.files[file.id]; break; case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED: errorString = 'Stopped'; break; } // Call the default event handler if ($.inArray('onUploadError', settings.overrideEvents) < 0) { if (errorCode != SWFUpload.UPLOAD_ERROR.FILE_CANCELLED && errorCode != SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) { $('#' + file.id).addClass('uploadify-error'); } // Reset the progress bar $('#' + file.id).find('.uploadify-progress-bar').css('width','1px'); // Add the error message to the queue item if (errorCode != SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND && file.status != SWFUpload.FILE_STATUS.COMPLETE) { $('#' + file.id).find('.data').html(' - ' + errorString); } } var stats = this.getStats(); this.queueData.uploadsErrored = stats.upload_errors; // Call the user-defined event handler if (settings.onUploadError) settings.onUploadError.call(this, file, errorCode, errorMsg, errorString); }, // Triggered periodically during a file upload onUploadProgress : function(file, fileBytesLoaded, fileTotalBytes) { // Load the swfupload settings var settings = this.settings; // Setup all the variables var timer = new Date(); var newTime = timer.getTime(); var lapsedTime = newTime - this.timer; if (lapsedTime > 500) { this.timer = newTime; } var lapsedBytes = fileBytesLoaded - this.bytesLoaded; this.bytesLoaded = fileBytesLoaded; var queueBytesLoaded = this.queueData.queueBytesUploaded + fileBytesLoaded; var percentage = Math.round(fileBytesLoaded / fileTotalBytes * 100); // Calculate the average speed var suffix = 'KB/s'; var mbs = 0; var kbs = (lapsedBytes / 1024) / (lapsedTime / 1000); kbs = Math.floor(kbs * 10) / 10; if (this.queueData.averageSpeed > 0) { this.queueData.averageSpeed = Math.floor((this.queueData.averageSpeed + kbs) / 2); } else { this.queueData.averageSpeed = Math.floor(kbs); } if (kbs > 1000) { mbs = (kbs * .001); this.queueData.averageSpeed = Math.floor(mbs); suffix = 'MB/s'; } // Call the default event handler if ($.inArray('onUploadProgress', settings.overrideEvents) < 0) { if (settings.progressData == 'percentage') { $('#' + file.id).find('.data').html(' - ' + percentage + '%'); } else if (settings.progressData == 'speed' && lapsedTime > 500) { $('#' + file.id).find('.data').html(' - ' + this.queueData.averageSpeed + suffix); } $('#' + file.id).find('.uploadify-progress-bar').css('width', percentage + '%'); } // Call the user-defined event handler if (settings.onUploadProgress) settings.onUploadProgress.call(this, file, fileBytesLoaded, fileTotalBytes, queueBytesLoaded, this.queueData.uploadSize); }, // Triggered right before a file is uploaded onUploadStart : function(file) { // Load the swfupload settings var settings = this.settings; var timer = new Date(); this.timer = timer.getTime(); this.bytesLoaded = 0; if (this.queueData.uploadQueue.length == 0) { this.queueData.uploadSize = file.size; } if (settings.checkExisting) { $.ajax({ type : 'POST', async : false, url : settings.checkExisting, data : {filename: file.name}, success : function(data) { if (data == 1) { var overwrite = confirm('A file with the name "' + file.name + '" already exists on the server.\nWould you like to replace the existing file?'); if (!overwrite) { this.cancelUpload(file.id); $('#' + file.id).remove(); if (this.queueData.uploadQueue.length > 0 && this.queueData.queueLength > 0) { if (this.queueData.uploadQueue[0] == '*') { this.startUpload(); } else { this.startUpload(this.queueData.uploadQueue.shift()); } } } } } }); } // Call the user-defined event handler if (settings.onUploadStart) settings.onUploadStart.call(this, file); }, // Triggered when a file upload returns a successful code onUploadSuccess : function(file, data, response) { // Load the swfupload settings var settings = this.settings; var stats = this.getStats(); this.queueData.uploadsSuccessful = stats.successful_uploads; this.queueData.queueBytesUploaded += file.size; // Call the default event handler if ($.inArray('onUploadSuccess', settings.overrideEvents) < 0) { $('#' + file.id).find('.data').html(' - Complete'); } // Call the user-defined event handler if (settings.onUploadSuccess) settings.onUploadSuccess.call(this, file, data, response); } } $.fn.uploadify = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('The method ' + method + ' does not exist in $.uploadify'); } } })($);
JavaScript
/** * syncHeight - jQuery plugin to automagically Snyc the heights of columns * Made to seemlessly work with the CCS-Framework YAML (yaml.de) * @requires jQuery v1.0.3 * * http://blog.ginader.de/dev/syncheight/ * * Copyright (c) 2007-2009 * Dirk Ginader (ginader.de) * Dirk Jesse (yaml.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Version: 1.2 * * Usage: $(window).load(function(){ $('p').syncHeight(); }); */ (function($) { var getHeightProperty = function() { var browser_id = 0; var property = [ // To avoid content overflow in synchronised boxes on font scaling, we // use 'min-height' property for modern browsers ... ['min-height','0px'], // and 'height' property for Internet Explorer. ['height','1%'] ]; // check for IE6 ... if($.browser.msie && $.browser.version < 7){ browser_id = 1; } return { 'name': property[browser_id][0], 'autoheightVal': property[browser_id][1] }; }; $.getSyncedHeight = function(selector) { var max = 0; var heightProperty = getHeightProperty(); // get maximum element height ... $(selector).each(function() { // fallback to auto height before height check ... $(this).css(heightProperty.name, heightProperty.autoheightVal); var val = $(this).height(); if(val > max){ max = val; } }); return max; }; $.fn.syncHeight = function(config) { var defaults = { updateOnResize: false, // re-sync element heights after a browser resize event (useful in flexible layouts) height: false }; var options = $.extend(defaults, config); var e = this; var max = 0; var heightPropertyName = getHeightProperty().name; if(typeof(options.height) === "number") { max = options.height; } else { max = $.getSyncedHeight(this); } // set synchronized element height ... $(this).each(function() { $(this).css(heightPropertyName, max+'px'); }); // optional sync refresh on resize event ... if (options.updateOnResize === true) { $(window).resize(function(){ $(e).syncHeight(); }); } return this; }; })(jQuery);
JavaScript
/** * "Yet Another Multicolumn Layout" - YAML CSS Framework * * (en) Workaround for IE8 und Webkit browsers to fix focus problems when using skiplinks * (de) Workaround für IE8 und Webkit browser, um den Focus zu korrigieren, bei Verwendung von Skiplinks * * @note inspired by Paul Ratcliffe's article * http://www.communis.co.uk/blog/2009-06-02-skip-links-chrome-safari-and-added-wai-aria * Many thanks to Mathias Schäfer (http://molily.de/) for his code improvements * * @copyright Copyright 2005-2012, Dirk Jesse * @license CC-BY 2.0 (http://creativecommons.org/licenses/by/2.0/), * YAML-CDL (http://www.yaml.de/license.html) * @link http://www.yaml.de * @package yaml * @version 4.0+ * @revision $Revision: 617 $ * @lastmodified $Date: 2012-01-05 23:56:54 +0100 (Do, 05 Jan 2012) $ */ (function () { var YAML_focusFix = { skipClass : 'ym-skip', init : function () { var userAgent = navigator.userAgent.toLowerCase(); var is_webkit = userAgent.indexOf('webkit') > -1; var is_ie = userAgent.indexOf('msie') > -1; if (is_webkit || is_ie) { var body = document.body, handler = YAML_focusFix.click; if (body.addEventListener) { body.addEventListener('click', handler, false); } else if (body.attachEvent) { body.attachEvent('onclick', handler); } } }, trim : function (str) { return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); }, click : function (e) { e = e || window.event; var target = e.target || e.srcElement; var a = target.className.split(' '); for (var i=0; i < a.length; i++) { var cls = YAML_focusFix.trim(a[i]); if ( cls === YAML_focusFix.skipClass) { YAML_focusFix.focus(target); break; } } }, focus : function (link) { if (link.href) { var href = link.href, id = href.substr(href.indexOf('#') + 1), target = document.getElementById(id); if (target) { target.setAttribute("tabindex", "-1"); target.focus(); } } } }; YAML_focusFix.init(); })();
JavaScript
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highcharts JS v2.3.5 (2012-12-19) * * (c) 2009-2012 Torstein Hønsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console */ (function () { // encapsulated variables var UNDEFINED, doc = document, win = window, math = Math, mathRound = math.round, mathFloor = math.floor, mathCeil = math.ceil, mathMax = math.max, mathMin = math.min, mathAbs = math.abs, mathCos = math.cos, mathSin = math.sin, mathPI = math.PI, deg2rad = mathPI * 2 / 360, // some variables userAgent = navigator.userAgent, isOpera = win.opera, isIE = /msie/i.test(userAgent) && !isOpera, docMode8 = doc.documentMode === 8, isWebKit = /AppleWebKit/.test(userAgent), isFirefox = /Firefox/.test(userAgent), isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent), SVG_NS = 'http://www.w3.org/2000/svg', hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect, hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38 useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext, Renderer, hasTouch = doc.documentElement.ontouchstart !== UNDEFINED, symbolSizes = {}, idCounter = 0, garbageBin, defaultOptions, dateFormat, // function globalAnimation, pathAnim, timeUnits, noop = function () {}, charts = [], // some constants for frequently used strings DIV = 'div', ABSOLUTE = 'absolute', RELATIVE = 'relative', HIDDEN = 'hidden', PREFIX = 'highcharts-', VISIBLE = 'visible', PX = 'px', NONE = 'none', M = 'M', L = 'L', /* * Empirical lowest possible opacities for TRACKER_FILL * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * IE10: 0.0001 (exporting only) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')', // invisible but clickable //TRACKER_FILL = 'rgba(192,192,192,0.5)', NORMAL_STATE = '', HOVER_STATE = 'hover', SELECT_STATE = 'select', MILLISECOND = 'millisecond', SECOND = 'second', MINUTE = 'minute', HOUR = 'hour', DAY = 'day', WEEK = 'week', MONTH = 'month', YEAR = 'year', // constants for attributes FILL = 'fill', LINEAR_GRADIENT = 'linearGradient', STOPS = 'stops', STROKE = 'stroke', STROKE_WIDTH = 'stroke-width', // time methods, changed based on whether or not UTC is used makeTime, getMinutes, getHours, getDay, getDate, getMonth, getFullYear, setMinutes, setHours, setDate, setMonth, setFullYear, // lookup over the types and the associated classes seriesTypes = {}; // The Highcharts namespace win.Highcharts = {}; /** * Extend an object with the members of another * @param {Object} a The object to be extended * @param {Object} b The object to add to the first one */ function extend(a, b) { var n; if (!a) { a = {}; } for (n in b) { a[n] = b[n]; } return a; } /** * Take an array and turn into a hash with even number arguments as keys and odd numbers as * values. Allows creating constants for commonly used style properties, attributes etc. * Avoid it in performance critical situations like looping */ function hash() { var i = 0, args = arguments, length = args.length, obj = {}; for (; i < length; i++) { obj[args[i++]] = args[i]; } return obj; } /** * Shortcut for parseInt * @param {Object} s * @param {Number} mag Magnitude */ function pInt(s, mag) { return parseInt(s, mag || 10); } /** * Check for string * @param {Object} s */ function isString(s) { return typeof s === 'string'; } /** * Check for object * @param {Object} obj */ function isObject(obj) { return typeof obj === 'object'; } /** * Check for array * @param {Object} obj */ function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } /** * Check for number * @param {Object} n */ function isNumber(n) { return typeof n === 'number'; } function log2lin(num) { return math.log(num) / math.LN10; } function lin2log(num) { return math.pow(10, num); } /** * Remove last occurence of an item from an array * @param {Array} arr * @param {Mixed} item */ function erase(arr, item) { var i = arr.length; while (i--) { if (arr[i] === item) { arr.splice(i, 1); break; } } //return arr; } /** * Returns true if the object is not null or undefined. Like MooTools' $.defined. * @param {Object} obj */ function defined(obj) { return obj !== UNDEFINED && obj !== null; } /** * Set or get an attribute or an object of attributes. Can't use jQuery attr because * it attempts to set expando properties on the SVG element, which is not allowed. * * @param {Object} elem The DOM element to receive the attribute(s) * @param {String|Object} prop The property or an abject of key-value pairs * @param {String} value The value if a single property is set */ function attr(elem, prop, value) { var key, setAttribute = 'setAttribute', ret; // if the prop is a string if (isString(prop)) { // set the value if (defined(value)) { elem[setAttribute](prop, value); // get the value } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo... ret = elem.getAttribute(prop); } // else if prop is defined, it is a hash of key/value pairs } else if (defined(prop) && isObject(prop)) { for (key in prop) { elem[setAttribute](key, prop[key]); } } return ret; } /** * Check if an element is an array, and if not, make it into an array. Like * MooTools' $.splat. */ function splat(obj) { return isArray(obj) ? obj : [obj]; } /** * Return the first value that is defined. Like MooTools' $.pick. */ function pick() { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i++) { arg = args[i]; if (typeof arg !== 'undefined' && arg !== null) { return arg; } } } /** * Set CSS on a given element * @param {Object} el * @param {Object} styles Style object with camel case property names */ function css(el, styles) { if (isIE) { if (styles && styles.opacity !== UNDEFINED) { styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')'; } } extend(el.style, styles); } /** * Utility function to create element with attributes and styles * @param {Object} tag * @param {Object} attribs * @param {Object} styles * @param {Object} parent * @param {Object} nopad */ function createElement(tag, attribs, styles, parent, nopad) { var el = doc.createElement(tag); if (attribs) { extend(el, attribs); } if (nopad) { css(el, {padding: 0, border: NONE, margin: 0}); } if (styles) { css(el, styles); } if (parent) { parent.appendChild(el); } return el; } /** * Extend a prototyped class by new members * @param {Object} parent * @param {Object} members */ function extendClass(parent, members) { var object = function () {}; object.prototype = new parent(); extend(object.prototype, members); return object; } /** * How many decimals are there in a number */ function getDecimals(number) { number = (number || 0).toString(); return number.indexOf('.') > -1 ? number.split('.')[1].length : 0; } /** * Format a number and return a string based on input settings * @param {Number} number The input number to format * @param {Number} decimals The amount of decimals * @param {String} decPoint The decimal point, defaults to the one given in the lang options * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options */ function numberFormat(number, decimals, decPoint, thousandsSep) { var lang = defaultOptions.lang, // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/ n = number, c = decimals === -1 ? getDecimals(number) : (isNaN(decimals = mathAbs(decimals)) ? 2 : decimals), d = decPoint === undefined ? lang.decimalPoint : decPoint, t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep, s = n < 0 ? "-" : "", i = String(pInt(n = mathAbs(+n || 0).toFixed(c))), j = i.length > 3 ? i.length % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + mathAbs(n - i).toFixed(c).slice(2) : ""); } /** * Pad a string to a given length by adding 0 to the beginning * @param {Number} number * @param {Number} length */ function pad(number, length) { // Create an array of the remaining length +1 and join it with 0's return new Array((length || 2) + 1 - String(number).length).join(0) + number; } /** * Wrap a method with extended functionality, preserving the original function * @param {Object} obj The context object that the method belongs to * @param {String} method The name of the method to extend * @param {Function} func A wrapper function callback. This function is called with the same arguments * as the original function, except that the original function is unshifted and passed as the first * argument. */ function wrap(obj, method, func) { var proceed = obj[method]; obj[method] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(proceed); return func.apply(this, args); }; } /** * Based on http://www.php.net/manual/en/function.strftime.php * @param {String} format * @param {Number} timestamp * @param {Boolean} capitalize */ dateFormat = function (format, timestamp, capitalize) { if (!defined(timestamp) || isNaN(timestamp)) { return 'Invalid date'; } format = pick(format, '%Y-%m-%d %H:%M:%S'); var date = new Date(timestamp), key, // used in for constuct below // get the basic time values hours = date[getHours](), day = date[getDay](), dayOfMonth = date[getDate](), month = date[getMonth](), fullYear = date[getFullYear](), lang = defaultOptions.lang, langWeekdays = lang.weekdays, /* // uncomment this and the 'W' format key below to enable week numbers weekNumber = function () { var clone = new Date(date.valueOf()), day = clone[getDay]() == 0 ? 7 : clone[getDay](), dayNumber; clone.setDate(clone[getDate]() + 4 - day); dayNumber = mathFloor((clone.getTime() - new Date(clone[getFullYear](), 0, 1, -6)) / 86400000); return 1 + mathFloor(dayNumber / 7); }, */ // list all format keys replacements = { // Day 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon' 'A': langWeekdays[day], // Long weekday, like 'Monday' 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31 'e': dayOfMonth, // Day of the month, 1 through 31 // Week (none implemented) //'W': weekNumber(), // Month 'b': lang.shortMonths[month], // Short month, like 'Jan' 'B': lang.months[month], // Long month, like 'January' 'm': pad(month + 1), // Two digit month number, 01 through 12 // Year 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009 'Y': fullYear, // Four digits year, like 2009 // Time 'H': pad(hours), // Two digits hours in 24h format, 00 through 23 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby) }; // do the replaces for (key in replacements) { while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster format = format.replace('%' + key, replacements[key]); } } // Optionally capitalize the string and return return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format; }; /** * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5 * @param {Number} interval * @param {Array} multiples * @param {Number} magnitude * @param {Object} options */ function normalizeTickInterval(interval, multiples, magnitude, options) { var normalized, i; // round to a tenfold of 1, 2, 2.5 or 5 magnitude = pick(magnitude, 1); normalized = interval / magnitude; // multiples for a linear scale if (!multiples) { multiples = [1, 2, 2.5, 5, 10]; // the allowDecimals option if (options && options.allowDecimals === false) { if (magnitude === 1) { multiples = [1, 2, 5, 10]; } else if (magnitude <= 0.1) { multiples = [1 / magnitude]; } } } // normalize the interval to the nearest multiple for (i = 0; i < multiples.length; i++) { interval = multiples[i]; if (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2) { break; } } // multiply back to the correct magnitude interval *= magnitude; return interval; } /** * Get a normalized tick interval for dates. Returns a configuration object with * unit range (interval), count and name. Used to prepare data for getTimeTicks. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs * of segments in stock charts, the normalizing logic was extracted in order to * prevent it for running over again for each segment having the same interval. * #662, #697. */ function normalizeTimeTickInterval(tickInterval, unitsOption) { var units = unitsOption || [[ MILLISECOND, // unit name [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples ], [ SECOND, [1, 2, 5, 10, 15, 30] ], [ MINUTE, [1, 2, 5, 10, 15, 30] ], [ HOUR, [1, 2, 3, 4, 6, 8, 12] ], [ DAY, [1, 2] ], [ WEEK, [1, 2] ], [ MONTH, [1, 2, 3, 4, 6] ], [ YEAR, null ]], unit = units[units.length - 1], // default unit is years interval = timeUnits[unit[0]], multiples = unit[1], count, i; // loop through the units to find the one that best fits the tickInterval for (i = 0; i < units.length; i++) { unit = units[i]; interval = timeUnits[unit[0]]; multiples = unit[1]; if (units[i + 1]) { // lessThan is in the middle between the highest multiple and the next unit. var lessThan = (interval * multiples[multiples.length - 1] + timeUnits[units[i + 1][0]]) / 2; // break and keep the current unit if (tickInterval <= lessThan) { break; } } } // prevent 2.5 years intervals, though 25, 250 etc. are allowed if (interval === timeUnits[YEAR] && tickInterval < 5 * interval) { multiples = [1, 2, 5]; } // prevent 2.5 years intervals, though 25, 250 etc. are allowed if (interval === timeUnits[YEAR] && tickInterval < 5 * interval) { multiples = [1, 2, 5]; } // get the count count = normalizeTickInterval(tickInterval / interval, multiples); return { unitRange: interval, count: count, unitName: unit[0] }; } /** * Set the tick positions to a time unit that makes sense, for example * on the first of each month or on every Monday. Return an array * with the time positions. Used in datetime axes as well as for grouping * data on a datetime axis. * * @param {Object} normalizedInterval The interval in axis values (ms) and the count * @param {Number} min The minimum in axis values * @param {Number} max The maximum in axis values * @param {Number} startOfWeek */ function getTimeTicks(normalizedInterval, min, max, startOfWeek) { var tickPositions = [], i, higherRanks = {}, useUTC = defaultOptions.global.useUTC, minYear, // used in months and years as a basis for Date.UTC() minDate = new Date(min), interval = normalizedInterval.unitRange, count = normalizedInterval.count; if (defined(min)) { // #1300 if (interval >= timeUnits[SECOND]) { // second minDate.setMilliseconds(0); minDate.setSeconds(interval >= timeUnits[MINUTE] ? 0 : count * mathFloor(minDate.getSeconds() / count)); } if (interval >= timeUnits[MINUTE]) { // minute minDate[setMinutes](interval >= timeUnits[HOUR] ? 0 : count * mathFloor(minDate[getMinutes]() / count)); } if (interval >= timeUnits[HOUR]) { // hour minDate[setHours](interval >= timeUnits[DAY] ? 0 : count * mathFloor(minDate[getHours]() / count)); } if (interval >= timeUnits[DAY]) { // day minDate[setDate](interval >= timeUnits[MONTH] ? 1 : count * mathFloor(minDate[getDate]() / count)); } if (interval >= timeUnits[MONTH]) { // month minDate[setMonth](interval >= timeUnits[YEAR] ? 0 : count * mathFloor(minDate[getMonth]() / count)); minYear = minDate[getFullYear](); } if (interval >= timeUnits[YEAR]) { // year minYear -= minYear % count; minDate[setFullYear](minYear); } // week is a special case that runs outside the hierarchy if (interval === timeUnits[WEEK]) { // get start of current week, independent of count minDate[setDate](minDate[getDate]() - minDate[getDay]() + pick(startOfWeek, 1)); } // get tick positions i = 1; minYear = minDate[getFullYear](); var time = minDate.getTime(), minMonth = minDate[getMonth](), minDateDate = minDate[getDate](), timezoneOffset = useUTC ? 0 : (24 * 3600 * 1000 + minDate.getTimezoneOffset() * 60 * 1000) % (24 * 3600 * 1000); // #950 // iterate and add tick positions at appropriate values while (time < max) { tickPositions.push(time); // if the interval is years, use Date.UTC to increase years if (interval === timeUnits[YEAR]) { time = makeTime(minYear + i * count, 0); // if the interval is months, use Date.UTC to increase months } else if (interval === timeUnits[MONTH]) { time = makeTime(minYear, minMonth + i * count); // if we're using global time, the interval is not fixed as it jumps // one hour at the DST crossover } else if (!useUTC && (interval === timeUnits[DAY] || interval === timeUnits[WEEK])) { time = makeTime(minYear, minMonth, minDateDate + i * count * (interval === timeUnits[DAY] ? 1 : 7)); // else, the interval is fixed and we use simple addition } else { time += interval * count; // mark new days if the time is dividable by day if (interval <= timeUnits[HOUR] && time % timeUnits[DAY] === timezoneOffset) { higherRanks[time] = DAY; } } i++; } // push the last time tickPositions.push(time); } // record information on the chosen unit - for dynamic label formatter tickPositions.info = extend(normalizedInterval, { higherRanks: higherRanks, totalRange: interval * count }); return tickPositions; } /** * Helper class that contains variuos counters that are local to the chart. */ function ChartCounters() { this.color = 0; this.symbol = 0; } ChartCounters.prototype = { /** * Wraps the color counter if it reaches the specified length. */ wrapColor: function (length) { if (this.color >= length) { this.color = 0; } }, /** * Wraps the symbol counter if it reaches the specified length. */ wrapSymbol: function (length) { if (this.symbol >= length) { this.symbol = 0; } } }; /** * Utility method that sorts an object array and keeping the order of equal items. * ECMA script standard does not specify the behaviour when items are equal. */ function stableSort(arr, sortFunction) { var length = arr.length, sortValue, i; // Add index to each item for (i = 0; i < length; i++) { arr[i].ss_i = i; // stable sort index } arr.sort(function (a, b) { sortValue = sortFunction(a, b); return sortValue === 0 ? a.ss_i - b.ss_i : sortValue; }); // Remove index from items for (i = 0; i < length; i++) { delete arr[i].ss_i; // stable sort index } } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMin(data) { var i = data.length, min = data[0]; while (i--) { if (data[i] < min) { min = data[i]; } } return min; } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMax(data) { var i = data.length, max = data[0]; while (i--) { if (data[i] > max) { max = data[i]; } } return max; } /** * Utility method that destroys any SVGElement or VMLElement that are properties on the given object. * It loops all properties and invokes destroy if there is a destroy method. The property is * then delete'ed. * @param {Object} The object to destroy properties on * @param {Object} Exception, do not destroy this property, only delete it. */ function destroyObjectProperties(obj, except) { var n; for (n in obj) { // If the object is non-null and destroy is defined if (obj[n] && obj[n] !== except && obj[n].destroy) { // Invoke the destroy obj[n].destroy(); } // Delete the property from the object. delete obj[n]; } } /** * Discard an element by moving it to the bin and delete * @param {Object} The HTML node to discard */ function discardElement(element) { // create a garbage bin element, not part of the DOM if (!garbageBin) { garbageBin = createElement(DIV); } // move the node and empty bin if (element) { garbageBin.appendChild(element); } garbageBin.innerHTML = ''; } /** * Provide error messages for debugging, with links to online explanation */ function error(code, stop) { var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code; if (stop) { throw msg; } else if (win.console) { console.log(msg); } } /** * Fix JS round off float errors * @param {Number} num */ function correctFloat(num) { return parseFloat( num.toPrecision(14) ); } /** * Set the global animation to either a given value, or fall back to the * given chart's animation option * @param {Object} animation * @param {Object} chart */ function setAnimation(animation, chart) { globalAnimation = pick(animation, chart.animation); } /** * The time unit lookup */ /*jslint white: true*/ timeUnits = hash( MILLISECOND, 1, SECOND, 1000, MINUTE, 60000, HOUR, 3600000, DAY, 24 * 3600000, WEEK, 7 * 24 * 3600000, MONTH, 31 * 24 * 3600000, YEAR, 31556952000 ); /*jslint white: false*/ /** * Path interpolation algorithm used across adapters */ pathAnim = { /** * Prepare start and end values so that the path can be animated one to one */ init: function (elem, fromD, toD) { fromD = fromD || ''; var shift = elem.shift, bezier = fromD.indexOf('C') > -1, numParams = bezier ? 7 : 3, endLength, slice, i, start = fromD.split(' '), end = [].concat(toD), // copy startBaseLine, endBaseLine, sixify = function (arr) { // in splines make move points have six parameters like bezier curves i = arr.length; while (i--) { if (arr[i] === M) { arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]); } } }; if (bezier) { sixify(start); sixify(end); } // pull out the base lines before padding if (elem.isArea) { startBaseLine = start.splice(start.length - 6, 6); endBaseLine = end.splice(end.length - 6, 6); } // if shifting points, prepend a dummy point to the end path if (shift <= end.length / numParams) { while (shift--) { end = [].concat(end).splice(0, numParams).concat(end); } } elem.shift = 0; // reset for following animations // copy and append last point until the length matches the end length if (start.length) { endLength = end.length; while (start.length < endLength) { //bezier && sixify(start); slice = [].concat(start).splice(start.length - numParams, numParams); if (bezier) { // disable first control point slice[numParams - 6] = slice[numParams - 2]; slice[numParams - 5] = slice[numParams - 1]; } start = start.concat(slice); } } if (startBaseLine) { // append the base lines for areas start = start.concat(startBaseLine); end = end.concat(endBaseLine); } return [start, end]; }, /** * Interpolate each value of the path and return the array */ step: function (start, end, pos, complete) { var ret = [], i = start.length, startVal; if (pos === 1) { // land on the final path without adjustment points appended in the ends ret = complete; } else if (i === end.length && pos < 1) { while (i--) { startVal = parseFloat(start[i]); ret[i] = isNaN(startVal) ? // a letter instruction like M or L start[i] : pos * (parseFloat(end[i] - startVal)) + startVal; } } else { // if animation is finished or length not matching, land on right value ret = end; } return ret; } }; (function ($) { /** * The default HighchartsAdapter for jQuery */ win.HighchartsAdapter = win.HighchartsAdapter || ($ && { /** * Initialize the adapter by applying some extensions to jQuery */ init: function (pathAnim) { // extend the animate function to allow SVG animations var Fx = $.fx, Step = Fx.step, dSetter, Tween = $.Tween, propHooks = Tween && Tween.propHooks; /*jslint unparam: true*//* allow unused param x in this function */ $.extend($.easing, { easeOutQuad: function (x, t, b, c, d) { return -c * (t /= d) * (t - 2) + b; } }); /*jslint unparam: false*/ // extend some methods to check for elem.attr, which means it is a Highcharts SVG object $.each(['cur', '_default', 'width', 'height'], function (i, fn) { var obj = Step, base, elem; // Handle different parent objects if (fn === 'cur') { obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype } else if (fn === '_default' && Tween) { // jQuery 1.8 model obj = propHooks[fn]; fn = 'set'; } // Overwrite the method base = obj[fn]; if (base) { // step.width and step.height don't exist in jQuery < 1.7 // create the extended function replacement obj[fn] = function (fx) { // Fx.prototype.cur does not use fx argument fx = i ? fx : this; // shortcut elem = fx.elem; // Fx.prototype.cur returns the current value. The other ones are setters // and returning a value has no effect. return elem.attr ? // is SVG element wrapper elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method base.apply(this, arguments); // use jQuery's built-in method }; } }); // Define the setter function for d (path definitions) dSetter = function (fx) { var elem = fx.elem, ends; // Normally start and end should be set in state == 0, but sometimes, // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped // in these cases if (!fx.started) { ends = pathAnim.init(elem, elem.d, elem.toD); fx.start = ends[0]; fx.end = ends[1]; fx.started = true; } // interpolate each value of the path elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD)); }; // jQuery 1.8 style if (Tween) { propHooks.d = { set: dSetter }; // pre 1.8 } else { // animate paths Step.d = dSetter; } /** * Utility for iterating over an array. Parameters are reversed compared to jQuery. * @param {Array} arr * @param {Function} fn */ this.each = Array.prototype.forEach ? function (arr, fn) { // modern browsers return Array.prototype.forEach.call(arr, fn); } : function (arr, fn) { // legacy var i = 0, len = arr.length; for (; i < len; i++) { if (fn.call(arr[i], arr[i], i, arr) === false) { return i; } } }; // Register Highcharts as a jQuery plugin // TODO: MooTools and prototype as well? // TODO: StockChart /*$.fn.highcharts = function(options, callback) { options.chart = merge(options.chart, { renderTo: this[0] }); this.chart = new Chart(options, callback); return this; };*/ }, /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ getScript: $.getScript, /** * Return the index of an item in an array, or -1 if not found */ inArray: $.inArray, /** * A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method. * @param {Object} elem The HTML element * @param {String} method Which method to run on the wrapped element */ adapterRun: function (elem, method) { return $(elem)[method](); }, /** * Filter an array */ grep: $.grep, /** * Map an array * @param {Array} arr * @param {Function} fn */ map: function (arr, fn) { //return jQuery.map(arr, fn); var results = [], i = 0, len = arr.length; for (; i < len; i++) { results[i] = fn.call(arr[i], arr[i], i, arr); } return results; }, /** * Deep merge two objects and return a third object */ merge: function () { var args = arguments; return $.extend(true, null, args[0], args[1], args[2], args[3]); }, /** * Get the position of an element relative to the top left of the page */ offset: function (el) { return $(el).offset(); }, /** * Add an event listener * @param {Object} el A HTML element or custom object * @param {String} event The event type * @param {Function} fn The event handler */ addEvent: function (el, event, fn) { $(el).bind(event, fn); }, /** * Remove event added with addEvent * @param {Object} el The object * @param {String} eventType The event type. Leave blank to remove all events. * @param {Function} handler The function to remove */ removeEvent: function (el, eventType, handler) { // workaround for jQuery issue with unbinding custom events: // http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2 var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent'; if (doc[func] && !el[func]) { el[func] = function () {}; } $(el).unbind(eventType, handler); }, /** * Fire an event on a custom object * @param {Object} el * @param {String} type * @param {Object} eventArguments * @param {Function} defaultFunction */ fireEvent: function (el, type, eventArguments, defaultFunction) { var event = $.Event(type), detachedType = 'detached' + type, defaultPrevented; // Remove warnings in Chrome when accessing layerX and layerY. Although Highcharts // never uses these properties, Chrome includes them in the default click event and // raises the warning when they are copied over in the extend statement below. // // To avoid problems in IE (see #1010) where we cannot delete the properties and avoid // testing if they are there (warning in chrome) the only option is to test if running IE. if (!isIE && eventArguments) { delete eventArguments.layerX; delete eventArguments.layerY; } extend(event, eventArguments); // Prevent jQuery from triggering the object method that is named the // same as the event. For example, if the event is 'select', jQuery // attempts calling el.select and it goes into a loop. if (el[type]) { el[detachedType] = el[type]; el[type] = null; } // Wrap preventDefault and stopPropagation in try/catch blocks in // order to prevent JS errors when cancelling events on non-DOM // objects. #615. /*jslint unparam: true*/ $.each(['preventDefault', 'stopPropagation'], function (i, fn) { var base = event[fn]; event[fn] = function () { try { base.call(event); } catch (e) { if (fn === 'preventDefault') { defaultPrevented = true; } } }; }); /*jslint unparam: false*/ // trigger it $(el).trigger(event); // attach the method if (el[detachedType]) { el[type] = el[detachedType]; el[detachedType] = null; } if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) { defaultFunction(event); } }, /** * Extension method needed for MooTools */ washMouseEvent: function (e) { var ret = e.originalEvent || e; // computed by jQuery, needed by IE8 if (ret.pageX === UNDEFINED) { // #1236 ret.pageX = e.pageX; ret.pageY = e.pageY; } return ret; }, /** * Animate a HTML element or SVG element wrapper * @param {Object} el * @param {Object} params * @param {Object} options jQuery-like animation options: duration, easing, callback */ animate: function (el, params, options) { var $el = $(el); if (params.d) { el.toD = params.d; // keep the array form for paths, used in $.fx.step.d params.d = 1; // because in jQuery, animating to an array has a different meaning } $el.stop(); $el.animate(params, options); }, /** * Stop running animation */ stop: function (el) { $(el).stop(); } }); }(win.jQuery)); // check for a custom HighchartsAdapter defined prior to this file var globalAdapter = win.HighchartsAdapter, adapter = globalAdapter || {}; // Initialize the adapter if (globalAdapter) { globalAdapter.init.call(globalAdapter, pathAnim); } // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object // and all the utility functions will be null. In that case they are populated by the // default adapters below. var adapterRun = adapter.adapterRun, getScript = adapter.getScript, inArray = adapter.inArray, each = adapter.each, grep = adapter.grep, offset = adapter.offset, map = adapter.map, merge = adapter.merge, addEvent = adapter.addEvent, removeEvent = adapter.removeEvent, fireEvent = adapter.fireEvent, washMouseEvent = adapter.washMouseEvent, animate = adapter.animate, stop = adapter.stop; /* **************************************************************************** * Handle the options * *****************************************************************************/ var defaultLabelOptions = { enabled: true, // rotation: 0, align: 'center', x: 0, y: 15, /*formatter: function () { return this.value; },*/ style: { color: '#666', fontSize: '11px', lineHeight: '14px' } }; defaultOptions = { colors: ['#4572A7', '#AA4643', '#89A54E', '#80699B', '#3D96AE', '#DB843D', '#92A8CD', '#A47D7C', '#B5CA92'], symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'], lang: { loading: 'Loading...', months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], decimalPoint: '.', numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels resetZoom: 'Reset zoom', resetZoomTitle: 'Reset zoom level 1:1', thousandsSep: ',' }, global: { useUTC: true, canvasToolsURL: 'http://code.highcharts.com/2.3.5/modules/canvas-tools.js', VMLRadialGradientURL: 'http://code.highcharts.com/2.3.5/gfx/vml-radial-gradient.png' }, chart: { //animation: true, //alignTicks: false, //reflow: true, //className: null, //events: { load, selection }, //margin: [null], //marginTop: null, //marginRight: null, //marginBottom: null, //marginLeft: null, borderColor: '#4572A7', //borderWidth: 0, borderRadius: 5, defaultSeriesType: 'line', ignoreHiddenSeries: true, //inverted: false, //shadow: false, spacingTop: 10, spacingRight: 10, spacingBottom: 15, spacingLeft: 10, style: { fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font fontSize: '12px' }, backgroundColor: '#FFFFFF', //plotBackgroundColor: null, plotBorderColor: '#C0C0C0', //plotBorderWidth: 0, //plotShadow: false, //zoomType: '' resetZoomButton: { theme: { zIndex: 20 }, position: { align: 'right', x: -10, //verticalAlign: 'top', y: 10 } // relativeTo: 'plot' } }, title: { text: 'Chart title', align: 'center', // floating: false, // margin: 15, // x: 0, // verticalAlign: 'top', y: 15, style: { color: '#3E576F', fontSize: '16px' } }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', y: 30, style: { color: '#6D869F' } }, plotOptions: { line: { // base series options allowPointSelect: false, showCheckbox: false, animation: { duration: 1000 }, //connectNulls: false, //cursor: 'default', //clip: true, //dashStyle: null, //enableMouseTracking: true, events: {}, //legendIndex: 0, lineWidth: 2, shadow: true, // stacking: null, marker: { enabled: true, //symbol: null, lineWidth: 0, radius: 4, lineColor: '#FFFFFF', //fillColor: null, states: { // states for a single point hover: { enabled: true //radius: base + 2 }, select: { fillColor: '#FFFFFF', lineColor: '#000000', lineWidth: 2 } } }, point: { events: {} }, dataLabels: merge(defaultLabelOptions, { enabled: false, formatter: function () { return this.y; }, verticalAlign: 'bottom', // above singular point y: 0 // backgroundColor: undefined, // borderColor: undefined, // borderRadius: undefined, // borderWidth: undefined, // padding: 3, // shadow: false }), cropThreshold: 300, // draw points outside the plot area when the number of points is less than this pointRange: 0, //pointStart: 0, //pointInterval: 1, showInLegend: true, states: { // states for the entire series hover: { //enabled: false, //lineWidth: base + 1, marker: { // lineWidth: base + 1, // radius: base + 1 } }, select: { marker: {} } }, stickyTracking: true //tooltip: { //pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b>' //valueDecimals: null, //xDateFormat: '%A, %b %e, %Y', //valuePrefix: '', //ySuffix: '' //} // turboThreshold: 1000 // zIndex: null } }, labels: { //items: [], style: { //font: defaultFont, position: ABSOLUTE, color: '#3E576F' } }, legend: { enabled: true, align: 'center', //floating: false, layout: 'horizontal', labelFormatter: function () { return this.name; }, borderWidth: 1, borderColor: '#909090', borderRadius: 5, navigation: { // animation: true, activeColor: '#3E576F', // arrowSize: 12 inactiveColor: '#CCC' // style: {} // text styles }, // margin: 10, // reversed: false, shadow: false, // backgroundColor: null, /*style: { padding: '5px' },*/ itemStyle: { cursor: 'pointer', color: '#3E576F', fontSize: '12px' }, itemHoverStyle: { //cursor: 'pointer', removed as of #601 color: '#000' }, itemHiddenStyle: { color: '#CCC' }, itemCheckboxStyle: { position: ABSOLUTE, width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, symbolWidth: 16, symbolPadding: 5, verticalAlign: 'bottom', // width: undefined, x: 0, y: 0 }, loading: { // hideDuration: 100, labelStyle: { fontWeight: 'bold', position: RELATIVE, top: '1em' }, // showDuration: 0, style: { position: ABSOLUTE, backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } }, tooltip: { enabled: true, //crosshairs: null, backgroundColor: 'rgba(255, 255, 255, .85)', borderWidth: 2, borderRadius: 5, dateTimeLabelFormats: { millisecond: '%A, %b %e, %H:%M:%S.%L', second: '%A, %b %e, %H:%M:%S', minute: '%A, %b %e, %H:%M', hour: '%A, %b %e, %H:%M', day: '%A, %b %e, %Y', week: 'Week from %A, %b %e, %Y', month: '%B %Y', year: '%Y' }, //formatter: defaultFormatter, headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>', pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>', shadow: true, shared: useCanVG, snap: isTouchDevice ? 25 : 10, style: { color: '#333333', fontSize: '12px', padding: '5px', whiteSpace: 'nowrap' } //xDateFormat: '%A, %b %e, %Y', //valueDecimals: null, //valuePrefix: '', //valueSuffix: '' }, credits: { enabled: true, text: 'Highcharts.com', href: 'http://www.highcharts.com', position: { align: 'right', x: -10, verticalAlign: 'bottom', y: -5 }, style: { cursor: 'pointer', color: '#909090', fontSize: '10px' } } }; // Series defaults var defaultPlotOptions = defaultOptions.plotOptions, defaultSeriesOptions = defaultPlotOptions.line; // set the default time methods setTimeMethods(); /** * Set the time methods globally based on the useUTC option. Time method can be either * local time or UTC (default). */ function setTimeMethods() { var useUTC = defaultOptions.global.useUTC, GET = useUTC ? 'getUTC' : 'get', SET = useUTC ? 'setUTC' : 'set'; makeTime = useUTC ? Date.UTC : function (year, month, date, hours, minutes, seconds) { return new Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); }; getMinutes = GET + 'Minutes'; getHours = GET + 'Hours'; getDay = GET + 'Day'; getDate = GET + 'Date'; getMonth = GET + 'Month'; getFullYear = GET + 'FullYear'; setMinutes = SET + 'Minutes'; setHours = SET + 'Hours'; setDate = SET + 'Date'; setMonth = SET + 'Month'; setFullYear = SET + 'FullYear'; } /** * Merge the default options with custom options and return the new options structure * @param {Object} options The new custom options */ function setOptions(options) { // Pull out axis options and apply them to the respective default axis options /*defaultXAxisOptions = merge(defaultXAxisOptions, options.xAxis); defaultYAxisOptions = merge(defaultYAxisOptions, options.yAxis); options.xAxis = options.yAxis = UNDEFINED;*/ // Merge in the default options defaultOptions = merge(defaultOptions, options); // Apply UTC setTimeMethods(); return defaultOptions; } /** * Get the updated default options. Merely exposing defaultOptions for outside modules * isn't enough because the setOptions method creates a new object. */ function getOptions() { return defaultOptions; } /** * Handle color operations. The object methods are chainable. * @param {String} input The input color in either rbga or hex format */ var Color = function (input) { // declare variables var rgba = [], result; /** * Parse the input color to rgba array * @param {String} input */ function init(input) { // rgba result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)]; } else { // hex result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(input); if (result) { rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1]; } } } /** * Return the color a specified format * @param {String} format */ function get(format) { var ret; // it's NaN if gradient colors on a column chart if (rgba && !isNaN(rgba[0])) { if (format === 'rgb') { ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')'; } else if (format === 'a') { ret = rgba[3]; } else { ret = 'rgba(' + rgba.join(',') + ')'; } } else { ret = input; } return ret; } /** * Brighten the color * @param {Number} alpha */ function brighten(alpha) { if (isNumber(alpha) && alpha !== 0) { var i; for (i = 0; i < 3; i++) { rgba[i] += pInt(alpha * 255); if (rgba[i] < 0) { rgba[i] = 0; } if (rgba[i] > 255) { rgba[i] = 255; } } } return this; } /** * Set the color's opacity to a given alpha value * @param {Number} alpha */ function setOpacity(alpha) { rgba[3] = alpha; return this; } // initialize: parse the input init(input); // public methods return { get: get, brighten: brighten, setOpacity: setOpacity }; }; /** * A wrapper object for SVG elements */ function SVGElement() {} SVGElement.prototype = { /** * Initialize the SVG renderer * @param {Object} renderer * @param {String} nodeName */ init: function (renderer, nodeName) { var wrapper = this; wrapper.element = nodeName === 'span' ? createElement(nodeName) : doc.createElementNS(SVG_NS, nodeName); wrapper.renderer = renderer; /** * A collection of attribute setters. These methods, if defined, are called right before a certain * attribute is set on an element wrapper. Returning false prevents the default attribute * setter to run. Returning a value causes the default setter to set that value. Used in * Renderer.label. */ wrapper.attrSetters = {}; }, /** * Animate a given attribute * @param {Object} params * @param {Number} options The same options as in jQuery animation * @param {Function} complete Function to perform at the end of animation */ animate: function (params, options, complete) { var animOptions = pick(options, globalAnimation, true); stop(this); // stop regardless of animation actually running, or reverting to .attr (#607) if (animOptions) { animOptions = merge(animOptions); if (complete) { // allows using a callback with the global animation without overwriting it animOptions.complete = complete; } animate(this, params, animOptions); } else { this.attr(params); if (complete) { complete(); } } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function (hash, val) { var wrapper = this, key, value, result, i, child, element = wrapper.element, nodeName = element.nodeName.toLowerCase(), // Android2 requires lower for "text" renderer = wrapper.renderer, skipAttr, titleNode, attrSetters = wrapper.attrSetters, shadows = wrapper.shadows, hasSetSymbolSize, doTransform, ret = wrapper; // single key-value pair if (isString(hash) && defined(val)) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (isString(hash)) { key = hash; if (nodeName === 'circle') { key = { x: 'cx', y: 'cy' }[key] || key; } else if (key === 'strokeWidth') { key = 'stroke-width'; } ret = attr(element, key) || wrapper[key] || 0; if (key !== 'd' && key !== 'visibility') { // 'd' is string in animation step ret = parseFloat(ret); } // setter } else { for (key in hash) { skipAttr = false; // reset value = hash[key]; // check for a specific attribute setter result = attrSetters[key] && attrSetters[key].call(wrapper, value, key); if (result !== false) { if (result !== UNDEFINED) { value = result; // the attribute setter has returned a new value to set } // paths if (key === 'd') { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } //wrapper.d = value; // shortcut for animations // update child tspans x values } else if (key === 'x' && nodeName === 'text') { for (i = 0; i < element.childNodes.length; i++) { child = element.childNodes[i]; // if the x values are equal, the tspan represents a linebreak if (attr(child, 'x') === attr(element, 'x')) { //child.setAttribute('x', value); attr(child, 'x', value); } } if (wrapper.rotation) { attr(element, 'transform', 'rotate(' + wrapper.rotation + ' ' + value + ' ' + pInt(hash.y || attr(element, 'y')) + ')'); } // apply gradients } else if (key === 'fill') { value = renderer.color(value, element, key); // circle x and y } else if (nodeName === 'circle' && (key === 'x' || key === 'y')) { key = { x: 'cx', y: 'cy' }[key] || key; // rectangle border radius } else if (nodeName === 'rect' && key === 'r') { attr(element, { rx: value, ry: value }); skipAttr = true; // translation and text rotation } else if (key === 'translateX' || key === 'translateY' || key === 'rotation' || key === 'verticalAlign') { doTransform = true; skipAttr = true; // apply opacity as subnode (required by legacy WebKit and Batik) } else if (key === 'stroke') { value = renderer.color(value, element, key); // emulate VML's dashstyle implementation } else if (key === 'dashstyle') { key = 'stroke-dasharray'; value = value && value.toLowerCase(); if (value === 'solid') { value = NONE; } else if (value) { value = value .replace('shortdashdotdot', '3,1,1,1,1,1,') .replace('shortdashdot', '3,1,1,1') .replace('shortdot', '1,1,') .replace('shortdash', '3,1,') .replace('longdash', '8,3,') .replace(/dot/g, '1,3,') .replace('dash', '4,3,') .replace(/,$/, '') .split(','); // ending comma i = value.length; while (i--) { value[i] = pInt(value[i]) * hash['stroke-width']; } value = value.join(','); } // special } else if (key === 'isTracker') { wrapper[key] = value; // IE9/MooTools combo: MooTools returns objects instead of numbers and IE9 Beta 2 // is unable to cast them. Test again with final IE9. } else if (key === 'width') { value = pInt(value); // Text alignment } else if (key === 'align') { key = 'text-anchor'; value = { left: 'start', center: 'middle', right: 'end' }[value]; // Title requires a subnode, #431 } else if (key === 'title') { titleNode = element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(SVG_NS, 'title'); element.appendChild(titleNode); } titleNode.textContent = value; } // jQuery animate changes case if (key === 'strokeWidth') { key = 'stroke-width'; } // Chrome/Win < 6 bug (http://code.google.com/p/chromium/issues/detail?id=15461), #1369 if (key === 'stroke-width' && value === 0 && (isWebKit || renderer.forExport)) { value = 0.000001; } // symbols if (wrapper.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) { if (!hasSetSymbolSize) { wrapper.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } // let the shadow follow the main element if (shadows && /^(width|height|visibility|x|y|d|transform)$/.test(key)) { i = shadows.length; while (i--) { attr( shadows[i], key, key === 'height' ? mathMax(value - (shadows[i].cutHeight || 0), 0) : value ); } } // validate heights if ((key === 'width' || key === 'height') && nodeName === 'rect' && value < 0) { value = 0; } // Record for animation and quick access without polling the DOM wrapper[key] = value; // Update transform if (doTransform) { wrapper.updateTransform(); } if (key === 'text') { // Delete bBox memo when the text changes if (value !== wrapper.textStr) { delete wrapper.bBox; } wrapper.textStr = value; if (wrapper.added) { renderer.buildText(wrapper); } } else if (!skipAttr) { attr(element, key, value); } } } } return ret; }, /** * If one of the symbol size affecting parameters are changed, * check all the others only once for each call to an element's * .attr() method * @param {Object} hash */ symbolAttr: function (hash) { var wrapper = this; each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) { wrapper[key] = pick(hash[key], wrapper[key]); }); wrapper.attr({ d: wrapper.renderer.symbols[wrapper.symbolName](wrapper.x, wrapper.y, wrapper.width, wrapper.height, wrapper) }); }, /** * Apply a clipping path to this object * @param {String} id */ clip: function (clipRect) { return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE); }, /** * Calculate the coordinates needed for drawing a rectangle crisply and return the * calculated attributes * @param {Number} strokeWidth * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ crisp: function (strokeWidth, x, y, width, height) { var wrapper = this, key, attribs = {}, values = {}, normalizer; strokeWidth = strokeWidth || wrapper.strokeWidth || (wrapper.attr && wrapper.attr('stroke-width')) || 0; normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors // normalize for crisp edges values.x = mathFloor(x || wrapper.x || 0) + normalizer; values.y = mathFloor(y || wrapper.y || 0) + normalizer; values.width = mathFloor((width || wrapper.width || 0) - 2 * normalizer); values.height = mathFloor((height || wrapper.height || 0) - 2 * normalizer); values.strokeWidth = strokeWidth; for (key in values) { if (wrapper[key] !== values[key]) { // only set attribute if changed wrapper[key] = attribs[key] = values[key]; } } return attribs; }, /** * Set styles for the element * @param {Object} styles */ css: function (styles) { /*jslint unparam: true*//* allow unused param a in the regexp function below */ var elemWrapper = this, elem = elemWrapper.element, textWidth = styles && styles.width && elem.nodeName.toLowerCase() === 'text', n, serializedCss = '', hyphenate = function (a, b) { return '-' + b.toLowerCase(); }; /*jslint unparam: false*/ // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Merge the new styles with the old ones styles = extend( elemWrapper.styles, styles ); // store object elemWrapper.styles = styles; // Don't handle line wrap on canvas if (useCanVG && textWidth) { delete styles.width; } // serialize and set style attribute if (isIE && !hasSVG) { // legacy IE doesn't support setting style attribute if (textWidth) { delete styles.width; } css(elemWrapper.element, styles); } else { for (n in styles) { serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';'; } elemWrapper.attr({ style: serializedCss }); } // re-build text if (textWidth && elemWrapper.added) { elemWrapper.renderer.buildText(elemWrapper); } return elemWrapper; }, /** * Add an event listener * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { // touch if (hasTouch && eventType === 'click') { this.element.ontouchstart = function (e) { e.preventDefault(); handler(); }; } // simplest possible event model for internal use this.element['on' + eventType] = handler; return this; }, /** * Set the coordinates needed to draw a consistent radial gradient across * pie slices regardless of positioning inside the chart. The format is * [centerX, centerY, diameter] in pixels. */ setRadialReference: function (coordinates) { this.element.radialReference = coordinates; return this; }, /** * Move an object and its children by x and y values * @param {Number} x * @param {Number} y */ translate: function (x, y) { return this.attr({ translateX: x, translateY: y }); }, /** * Invert a group, rotate and flip */ invert: function () { var wrapper = this; wrapper.inverted = true; wrapper.updateTransform(); return wrapper; }, /** * Apply CSS to HTML elements. This is used in text within SVG rendering and * by the VML renderer */ htmlCss: function (styles) { var wrapper = this, element = wrapper.element, textWidth = styles && element.tagName === 'SPAN' && styles.width; if (textWidth) { delete styles.width; wrapper.textWidth = textWidth; wrapper.updateTransform(); } wrapper.styles = extend(wrapper.styles, styles); css(wrapper.element, styles); return wrapper; }, /** * VML and useHTML method for calculating the bounding box based on offsets * @param {Boolean} refresh Whether to force a fresh value from the DOM or to * use the cached value * * @return {Object} A hash containing values for x, y, width and height */ htmlGetBBox: function () { var wrapper = this, element = wrapper.element, bBox = wrapper.bBox; // faking getBBox in exported SVG in legacy IE if (!bBox) { // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?) if (element.nodeName === 'text') { element.style.position = ABSOLUTE; } bBox = wrapper.bBox = { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; } return bBox; }, /** * VML override private method to update elements based on internal * properties based on SVG transform */ htmlUpdateTransform: function () { // aligning non added elements is expensive if (!this.added) { this.alignOnAdd = true; return; } var wrapper = this, renderer = wrapper.renderer, elem = wrapper.element, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, x = wrapper.x || 0, y = wrapper.y || 0, align = wrapper.textAlign || 'left', alignCorrection = { left: 0, center: 0.5, right: 1 }[align], nonLeft = align && align !== 'left', shadows = wrapper.shadows; // apply translate if (translateX || translateY) { css(elem, { marginLeft: translateX, marginTop: translateY }); if (shadows) { // used in labels/tooltip each(shadows, function (shadow) { css(shadow, { marginLeft: translateX + 1, marginTop: translateY + 1 }); }); } } // apply inversion if (wrapper.inverted) { // wrapper is a group each(elem.childNodes, function (child) { renderer.invertChild(child, elem); }); } if (elem.tagName === 'SPAN') { var width, height, rotation = wrapper.rotation, baseline, radians = 0, costheta = 1, sintheta = 0, quad, textWidth = pInt(wrapper.textWidth), xCorr = wrapper.xCorr || 0, yCorr = wrapper.yCorr || 0, currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(','), rotationStyle = {}, cssTransformKey; if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed if (defined(rotation)) { if (renderer.isSVG) { // #916 cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : ''; rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)'; } else { radians = rotation * deg2rad; // deg to rad costheta = mathCos(radians); sintheta = mathSin(radians); // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+ // has support for CSS3 transform. The getBBox method also needs to be updated // to compensate for the rotation, like it currently does for SVG. // Test case: http://highcharts.com/tests/?file=text-rotation rotationStyle.filter = rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')'].join('') : NONE; } css(elem, rotationStyle); } width = pick(wrapper.elemWidth, elem.offsetWidth); height = pick(wrapper.elemHeight, elem.offsetHeight); // update textWidth if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254 css(elem, { width: textWidth + PX, display: 'block', whiteSpace: 'normal' }); width = textWidth; } // correct x and y baseline = renderer.fontMetrics(elem.style.fontSize).b; xCorr = costheta < 0 && -width; yCorr = sintheta < 0 && -height; // correct for baseline and corners spilling out after rotation quad = costheta * sintheta < 0; xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection); yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1); // correct for the length/height of the text if (nonLeft) { xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1); } css(elem, { textAlign: align }); } // record correction wrapper.xCorr = xCorr; wrapper.yCorr = yCorr; } // apply position with correction css(elem, { left: (x + xCorr) + PX, top: (y + yCorr) + PX }); // force reflow in webkit to apply the left and top on useHTML element (#1249) if (isWebKit) { height = elem.offsetHeight; // assigned to height for JSLint purpose } // record current text transform wrapper.cTT = currentTextTransform; } }, /** * Private method to update the transform attribute based on internal * properties */ updateTransform: function () { var wrapper = this, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, inverted = wrapper.inverted, rotation = wrapper.rotation, transform = []; // flipping affects translate as adjustment for flipping around the group's axis if (inverted) { translateX += wrapper.attr('width'); translateY += wrapper.attr('height'); } // apply translate if (translateX || translateY) { transform.push('translate(' + translateX + ',' + translateY + ')'); } // apply rotation if (inverted) { transform.push('rotate(90) scale(-1,1)'); } else if (rotation) { // text rotation transform.push('rotate(' + rotation + ' ' + (wrapper.x || 0) + ' ' + (wrapper.y || 0) + ')'); } if (transform.length) { attr(wrapper.element, 'transform', transform.join(' ')); } }, /** * Bring the element to the front */ toFront: function () { var element = this.element; element.parentNode.appendChild(element); return this; }, /** * Break down alignment options like align, verticalAlign, x and y * to x and y relative to the chart. * * @param {Object} alignOptions * @param {Boolean} alignByTranslate * @param {Object} box The box to align to, needs a width and height * */ align: function (alignOptions, alignByTranslate, box) { var elemWrapper = this; if (!alignOptions) { // called on resize alignOptions = elemWrapper.alignOptions; alignByTranslate = elemWrapper.alignByTranslate; } else { // first call on instanciate elemWrapper.alignOptions = alignOptions; elemWrapper.alignByTranslate = alignByTranslate; if (!box) { // boxes other than renderer handle this internally elemWrapper.renderer.alignedObjects.push(elemWrapper); } } box = pick(box, elemWrapper.renderer); var align = alignOptions.align, vAlign = alignOptions.verticalAlign, x = (box.x || 0) + (alignOptions.x || 0), // default: left align y = (box.y || 0) + (alignOptions.y || 0), // default: top align attribs = {}; // align if (align === 'right' || align === 'center') { x += (box.width - (alignOptions.width || 0)) / { right: 1, center: 2 }[align]; } attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x); // vertical align if (vAlign === 'bottom' || vAlign === 'middle') { y += (box.height - (alignOptions.height || 0)) / ({ bottom: 1, middle: 2 }[vAlign] || 1); } attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y); // animate only if already placed elemWrapper[elemWrapper.placed ? 'animate' : 'attr'](attribs); elemWrapper.placed = true; elemWrapper.alignAttr = attribs; return elemWrapper; }, /** * Get the bounding box (width, height, x and y) for the element */ getBBox: function () { var wrapper = this, bBox = wrapper.bBox, renderer = wrapper.renderer, width, height, rotation = wrapper.rotation, element = wrapper.element, styles = wrapper.styles, rad = rotation * deg2rad; if (!bBox) { // SVG elements if (element.namespaceURI === SVG_NS || renderer.forExport) { try { // Fails in Firefox if the container has display: none. bBox = element.getBBox ? // SVG: use extend because IE9 is not allowed to change width and height in case // of rotation (below) extend({}, element.getBBox()) : // Canvas renderer and legacy IE in export mode { width: element.offsetWidth, height: element.offsetHeight }; } catch (e) {} // If the bBox is not set, the try-catch block above failed. The other condition // is for Opera that returns a width of -Infinity on hidden elements. if (!bBox || bBox.width < 0) { bBox = { width: 0, height: 0 }; } // VML Renderer or useHTML within SVG } else { bBox = wrapper.htmlGetBBox(); } // True SVG elements as well as HTML elements in modern browsers using the .useHTML option // need to compensated for rotation if (renderer.isSVG) { width = bBox.width; height = bBox.height; // Workaround for wrong bounding box in IE9 and IE10 (#1101) if (isIE && styles && styles.fontSize === '11px' && height === 22.700000762939453) { bBox.height = height = 14; } // Adjust for rotated text if (rotation) { bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad)); bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad)); } } wrapper.bBox = bBox; } return bBox; }, /** * Show the element */ show: function () { return this.attr({ visibility: VISIBLE }); }, /** * Hide the element */ hide: function () { return this.attr({ visibility: HIDDEN }); }, /** * Add the element * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined * to append the element to the renderer.box. */ add: function (parent) { var renderer = this.renderer, parentWrapper = parent || renderer, parentNode = parentWrapper.element || renderer.box, childNodes = parentNode.childNodes, element = this.element, zIndex = attr(element, 'zIndex'), otherElement, otherZIndex, i, inserted; if (parent) { this.parentGroup = parent; } // mark as inverted this.parentInverted = parent && parent.inverted; // build formatted text if (this.textStr !== undefined) { renderer.buildText(this); } // mark the container as having z indexed children if (zIndex) { parentWrapper.handleZ = true; zIndex = pInt(zIndex); } // insert according to this and other elements' zIndex if (parentWrapper.handleZ) { // this element or any of its siblings has a z index for (i = 0; i < childNodes.length; i++) { otherElement = childNodes[i]; otherZIndex = attr(otherElement, 'zIndex'); if (otherElement !== element && ( // insert before the first element with a higher zIndex pInt(otherZIndex) > zIndex || // if no zIndex given, insert before the first element with a zIndex (!defined(zIndex) && defined(otherZIndex)) )) { parentNode.insertBefore(element, otherElement); inserted = true; break; } } } // default: append at the end if (!inserted) { parentNode.appendChild(element); } // mark as added this.added = true; // fire an event for internal hooks fireEvent(this, 'add'); return this; }, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { var parentNode = element.parentNode; if (parentNode) { parentNode.removeChild(element); } }, /** * Destroy the element and element wrapper */ destroy: function () { var wrapper = this, element = wrapper.element || {}, shadows = wrapper.shadows, key, i; // remove events element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = null; stop(wrapper); // stop running animations if (wrapper.clipPath) { wrapper.clipPath = wrapper.clipPath.destroy(); } // Destroy stops in case this is a gradient object if (wrapper.stops) { for (i = 0; i < wrapper.stops.length; i++) { wrapper.stops[i] = wrapper.stops[i].destroy(); } wrapper.stops = null; } // remove element wrapper.safeRemoveChild(element); // destroy shadows if (shadows) { each(shadows, function (shadow) { wrapper.safeRemoveChild(shadow); }); } // remove from alignObjects erase(wrapper.renderer.alignedObjects, wrapper); for (key in wrapper) { delete wrapper[key]; } return null; }, /** * Empty a group element */ empty: function () { var element = this.element, childNodes = element.childNodes, i = childNodes.length; while (i--) { element.removeChild(childNodes[i]); } }, /** * Add a shadow to the element. Must be done after the element is added to the DOM * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, shadow, element = this.element, strokeWidth, shadowWidth, shadowElementOpacity, // compensate for inverted plot area transform; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; transform = this.parentInverted ? '(-1,-1)' : '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')'; for (i = 1; i <= shadowWidth; i++) { shadow = element.cloneNode(0); strokeWidth = (shadowWidth * 2) + 1 - (2 * i); attr(shadow, { 'isShadow': 'true', 'stroke': shadowOptions.color || 'black', 'stroke-opacity': shadowElementOpacity * i, 'stroke-width': strokeWidth, 'transform': 'translate' + transform, 'fill': NONE }); if (cutOff) { attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0)); shadow.cutHeight = strokeWidth; } if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } shadows.push(shadow); } this.shadows = shadows; } return this; } }; /** * The default SVG renderer */ var SVGRenderer = function () { this.init.apply(this, arguments); }; SVGRenderer.prototype = { Element: SVGElement, /** * Initialize the SVGRenderer * @param {Object} container * @param {Number} width * @param {Number} height * @param {Boolean} forExport */ init: function (container, width, height, forExport) { var renderer = this, loc = location, boxWrapper; boxWrapper = renderer.createElement('svg') .attr({ xmlns: SVG_NS, version: '1.1' }); container.appendChild(boxWrapper.element); // object properties renderer.isSVG = true; renderer.box = boxWrapper.element; renderer.boxWrapper = boxWrapper; renderer.alignedObjects = []; // Page url used for internal references. #24, #672, #1070 renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ? loc.href .replace(/#.*?$/, '') // remove the hash .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes .replace(/ /g, '%20') : // replace spaces (needed for Safari only) ''; renderer.defs = this.createElement('defs').add(); renderer.forExport = forExport; renderer.gradients = {}; // Object where gradient SvgElements are stored renderer.setSize(width, height, false); // Issue 110 workaround: // In Firefox, if a div is positioned by percentage, its pixel position may land // between pixels. The container itself doesn't display this, but an SVG element // inside this container will be drawn at subpixel precision. In order to draw // sharp lines, this must be compensated for. This doesn't seem to work inside // iframes though (like in jsFiddle). var subPixelFix, rect; if (isFirefox && container.getBoundingClientRect) { renderer.subPixelFix = subPixelFix = function () { css(container, { left: 0, top: 0 }); rect = container.getBoundingClientRect(); css(container, { left: (mathCeil(rect.left) - rect.left) + PX, top: (mathCeil(rect.top) - rect.top) + PX }); }; // run the fix now subPixelFix(); // run it on resize addEvent(win, 'resize', subPixelFix); } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none. #608. */ isHidden: function () { return !this.boxWrapper.getBBox().width; }, /** * Destroys the renderer and its allocated members. */ destroy: function () { var renderer = this, rendererDefs = renderer.defs; renderer.box = null; renderer.boxWrapper = renderer.boxWrapper.destroy(); // Call destroy on all gradient elements destroyObjectProperties(renderer.gradients || {}); renderer.gradients = null; // Defs are null in VMLRenderer // Otherwise, destroy them here. if (rendererDefs) { renderer.defs = rendererDefs.destroy(); } // Remove sub pixel fix handler // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed // See issue #982 if (renderer.subPixelFix) { removeEvent(win, 'resize', renderer.subPixelFix); } renderer.alignedObjects = null; return null; }, /** * Create a wrapper for an SVG element * @param {Object} nodeName */ createElement: function (nodeName) { var wrapper = new this.Element(); wrapper.init(this, nodeName); return wrapper; }, /** * Dummy function for use in canvas renderer */ draw: function () {}, /** * Parse a simple HTML string into SVG tspans * * @param {Object} textNode The parent text SVG node */ buildText: function (wrapper) { var textNode = wrapper.element, lines = pick(wrapper.textStr, '').toString() .replace(/<(b|strong)>/g, '<span style="font-weight:bold">') .replace(/<(i|em)>/g, '<span style="font-style:italic">') .replace(/<a/g, '<span') .replace(/<\/(b|strong|i|em|a)>/g, '</span>') .split(/<br.*?>/g), childNodes = textNode.childNodes, styleRegex = /style="([^"]+)"/, hrefRegex = /href="([^"]+)"/, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = textStyles && textStyles.width && pInt(textStyles.width), textLineHeight = textStyles && textStyles.lineHeight, lastLine, GET_COMPUTED_STYLE = 'getComputedStyle', i = childNodes.length, linePositions = []; // Needed in IE9 because it doesn't report tspan's offsetHeight (#893) function getLineHeightByBBox(lineNo) { linePositions[lineNo] = textNode.getBBox ? textNode.getBBox().height : wrapper.renderer.fontMetrics(textNode.style.fontSize).h; // #990 return mathRound(linePositions[lineNo] - (linePositions[lineNo - 1] || 0)); } // remove old text while (i--) { textNode.removeChild(childNodes[i]); } if (width && !wrapper.added) { this.box.appendChild(textNode); // attach it to the DOM to read offset width } // remove empty line at end if (lines[lines.length - 1] === '') { lines.pop(); } // build the lines each(lines, function (line, lineNo) { var spans, spanNo = 0, lineHeight; line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||'); spans = line.split('|||'); each(spans, function (span) { if (span !== '' || spans.length === 1) { var attributes = {}, tspan = doc.createElementNS(SVG_NS, 'tspan'), spanStyle; // #390 if (styleRegex.test(span)) { spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2'); attr(tspan, 'style', spanStyle); } if (hrefRegex.test(span)) { attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"'); css(tspan, { cursor: 'pointer' }); } span = (span.replace(/<(.|\n)*?>/g, '') || ' ') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>'); // issue #38 workaround. /*if (reverse) { arr = []; i = span.length; while (i--) { arr.push(span.charAt(i)); } span = arr.join(''); }*/ // add the text node tspan.appendChild(doc.createTextNode(span)); if (!spanNo) { // first span in a line, align it to the left attributes.x = parentX; } else { // Firefox ignores spaces at the front or end of the tspan attributes.dx = 3; // space } // first span on subsequent line, add the line height if (!spanNo) { if (lineNo) { // allow getting the right offset height in exporting in IE if (!hasSVG && wrapper.renderer.forExport) { css(tspan, { display: 'block' }); } // Webkit and opera sometimes return 'normal' as the line height. In that // case, webkit uses offsetHeight, while Opera falls back to 18 lineHeight = win[GET_COMPUTED_STYLE] && pInt(win[GET_COMPUTED_STYLE](lastLine, null).getPropertyValue('line-height')); if (!lineHeight || isNaN(lineHeight)) { lineHeight = textLineHeight || lastLine.offsetHeight || getLineHeightByBBox(lineNo) || 18; } attr(tspan, 'dy', lineHeight); } lastLine = tspan; // record for use in next line } // add attributes attr(tspan, attributes); // append it textNode.appendChild(tspan); spanNo++; // check width and apply soft breaks if (width) { var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273 tooLong, actualWidth, rest = []; while (words.length || rest.length) { delete wrapper.bBox; // delete cache actualWidth = wrapper.getBBox().width; tooLong = actualWidth > width; if (!tooLong || words.length === 1) { // new line needed words = rest; rest = []; if (words.length) { tspan = doc.createElementNS(SVG_NS, 'tspan'); attr(tspan, { dy: textLineHeight || 16, x: parentX }); if (spanStyle) { // #390 attr(tspan, 'style', spanStyle); } textNode.appendChild(tspan); if (actualWidth > width) { // a single word is pressing it out width = actualWidth; } } } else { // append to existing line tspan tspan.removeChild(tspan.firstChild); rest.unshift(words.pop()); } if (words.length) { tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-'))); } } } } }); }); }, /** * Create a button with preset states * @param {String} text * @param {Number} x * @param {Number} y * @param {Function} callback * @param {Object} normalState * @param {Object} hoverState * @param {Object} pressedState */ button: function (text, x, y, callback, normalState, hoverState, pressedState) { var label = this.label(text, x, y), curState = 0, stateOptions, stateStyle, normalStyle, hoverStyle, pressedStyle, STYLE = 'style', verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 }; // prepare the attributes /*jslint white: true*/ normalState = merge(hash( STROKE_WIDTH, 1, STROKE, '#999', FILL, hash( LINEAR_GRADIENT, verticalGradient, STOPS, [ [0, '#FFF'], [1, '#DDD'] ] ), 'r', 3, 'padding', 3, STYLE, hash( 'color', 'black' ) ), normalState); /*jslint white: false*/ normalStyle = normalState[STYLE]; delete normalState[STYLE]; /*jslint white: true*/ hoverState = merge(normalState, hash( STROKE, '#68A', FILL, hash( LINEAR_GRADIENT, verticalGradient, STOPS, [ [0, '#FFF'], [1, '#ACF'] ] ) ), hoverState); /*jslint white: false*/ hoverStyle = hoverState[STYLE]; delete hoverState[STYLE]; /*jslint white: true*/ pressedState = merge(normalState, hash( STROKE, '#68A', FILL, hash( LINEAR_GRADIENT, verticalGradient, STOPS, [ [0, '#9BD'], [1, '#CDF'] ] ) ), pressedState); /*jslint white: false*/ pressedStyle = pressedState[STYLE]; delete pressedState[STYLE]; // add the events addEvent(label.element, 'mouseenter', function () { label.attr(hoverState) .css(hoverStyle); }); addEvent(label.element, 'mouseleave', function () { stateOptions = [normalState, hoverState, pressedState][curState]; stateStyle = [normalStyle, hoverStyle, pressedStyle][curState]; label.attr(stateOptions) .css(stateStyle); }); label.setState = function (state) { curState = state; if (!state) { label.attr(normalState) .css(normalStyle); } else if (state === 2) { label.attr(pressedState) .css(pressedStyle); } }; return label .on('click', function () { callback.call(label); }) .attr(normalState) .css(extend({ cursor: 'default' }, normalStyle)); }, /** * Make a straight line crisper by not spilling out to neighbour pixels * @param {Array} points * @param {Number} width */ crispLine: function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line if (points[1] === points[4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2); } if (points[2] === points[5]) { points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2); } return points; }, /** * Draw a path * @param {Array} path An SVG path in array form */ path: function (path) { var attr = { fill: NONE }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } return this.createElement('path').attr(attr); }, /** * Draw and return an SVG circle * @param {Number} x The x position * @param {Number} y The y position * @param {Number} r The radius */ circle: function (x, y, r) { var attr = isObject(x) ? x : { x: x, y: y, r: r }; return this.createElement('circle').attr(attr); }, /** * Draw and return an arc * @param {Number} x X position * @param {Number} y Y position * @param {Number} r Radius * @param {Number} innerR Inner radius like used in donut charts * @param {Number} start Starting angle * @param {Number} end Ending angle */ arc: function (x, y, r, innerR, start, end) { // arcs are defined as symbols for the ability to set // attributes in attr and animate if (isObject(x)) { y = x.y; r = x.r; innerR = x.innerR; start = x.start; end = x.end; x = x.x; } return this.symbol('arc', x || 0, y || 0, r || 0, r || 0, { innerR: innerR || 0, start: start || 0, end: end || 0 }); }, /** * Draw and return a rectangle * @param {Number} x Left position * @param {Number} y Top position * @param {Number} width * @param {Number} height * @param {Number} r Border corner radius * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing */ rect: function (x, y, width, height, r, strokeWidth) { r = isObject(x) ? x.r : r; var wrapper = this.createElement('rect').attr({ rx: r, ry: r, fill: NONE }); return wrapper.attr( isObject(x) ? x : // do not crispify when an object is passed in (as in column charts) wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0)) ); }, /** * Resize the box and re-align all aligned elements * @param {Object} width * @param {Object} height * @param {Boolean} animate * */ setSize: function (width, height, animate) { var renderer = this, alignedObjects = renderer.alignedObjects, i = alignedObjects.length; renderer.width = width; renderer.height = height; renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({ width: width, height: height }); while (i--) { alignedObjects[i].align(); } }, /** * Create a group * @param {String} name The group will be given a class name of 'highcharts-{name}'. * This can be used for styling and scripting. */ g: function (name) { var elem = this.createElement('g'); return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem; }, /** * Display an image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var attribs = { preserveAspectRatio: NONE }, elemWrapper; // optional properties if (arguments.length > 1) { extend(attribs, { x: x, y: y, width: width, height: height }); } elemWrapper = this.createElement('image').attr(attribs); // set the href in the xlink namespace if (elemWrapper.element.setAttributeNS) { elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink', 'href', src); } else { // could be exporting in IE // using href throws "not supported" in ie7 and under, requries regex shim to fix later elemWrapper.element.setAttribute('hc-svg-href', src); } return elemWrapper; }, /** * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object. * * @param {Object} symbol * @param {Object} x * @param {Object} y * @param {Object} radius * @param {Object} options */ symbol: function (symbol, x, y, width, height, options) { var obj, // get the symbol definition function symbolFn = this.symbols[symbol], // check if there's a path defined for this symbol path = symbolFn && symbolFn( mathRound(x), mathRound(y), width, height, options ), imageElement, imageRegex = /^url\((.*?)\)$/, imageSrc, imageSize, centerImage; if (path) { obj = this.path(path); // expando properties for use in animate and attr extend(obj, { symbolName: symbol, x: x, y: y, width: width, height: height }); if (options) { extend(obj, options); } // image symbols } else if (imageRegex.test(symbol)) { // On image load, set the size and position centerImage = function (img, size) { if (img.element) { // it may be destroyed in the meantime (#1390) img.attr({ width: size[0], height: size[1] }); if (!img.alignByTranslate) { // #185 img.translate( mathRound((width - size[0]) / 2), // #1378 mathRound((height - size[1]) / 2) ); } } }; imageSrc = symbol.match(imageRegex)[1]; imageSize = symbolSizes[imageSrc]; // Ireate the image synchronously, add attribs async obj = this.image(imageSrc) .attr({ x: x, y: y }); if (imageSize) { centerImage(obj, imageSize); } else { // Initialize image to be 0 size so export will still function if there's no cached sizes. // obj.attr({ width: 0, height: 0 }); // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8, // the created element must be assigned to a variable in order to load (#292). imageElement = createElement('img', { onload: function () { centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]); }, src: imageSrc }); } } return obj; }, /** * An extendable collection of functions for defining symbol paths. */ symbols: { 'circle': function (x, y, w, h) { var cpw = 0.166 * w; return [ M, x + w / 2, y, 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h, 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y, 'Z' ]; }, 'square': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle-down': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w / 2, y + h, 'Z' ]; }, 'diamond': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h / 2, x + w / 2, y + h, x, y + h / 2, 'Z' ]; }, 'arc': function (x, y, w, h, options) { var start = options.start, radius = options.r || w || h, end = options.end - 0.000001, // to prevent cos and sin of start and end from becoming equal on 360 arcs innerRadius = options.innerR, open = options.open, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), longArc = options.end - start < mathPI ? 0 : 1; return [ M, x + radius * cosStart, y + radius * sinStart, 'A', // arcTo radius, // x radius radius, // y radius 0, // slanting longArc, // long or short arc 1, // clockwise x + radius * cosEnd, y + radius * sinEnd, open ? M : L, x + innerRadius * cosEnd, y + innerRadius * sinEnd, 'A', // arcTo innerRadius, // x radius innerRadius, // y radius 0, // slanting longArc, // long or short arc 0, // clockwise x + innerRadius * cosStart, y + innerRadius * sinStart, open ? '' : 'Z' // close ]; } }, /** * Define a clipping rectangle * @param {String} id * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { var wrapper, id = PREFIX + idCounter++, clipPath = this.createElement('clipPath').attr({ id: id }).add(this.defs); wrapper = this.rect(x, y, width, height, 0).add(clipPath); wrapper.id = id; wrapper.clipPath = clipPath; return wrapper; }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object. Prior to Highstock, an array was used to define * a linear gradient with pixel positions relative to the SVG. In newer versions * we change the coordinates to apply relative to the shape, using coordinates * 0-1 within the shape. To preserve backwards compatibility, linearGradient * in this definition is an object of x1, y1, x2 and y2. * * @param {Object} color The color or config object */ color: function (color, elem, prop) { var renderer = this, colorObject, regexRgba = /^rgba/, gradName, gradAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, n, id, key = []; // Apply linear or radial gradients if (color && color.linearGradient) { gradName = 'linearGradient'; } else if (color && color.radialGradient) { gradName = 'radialGradient'; } if (gradName) { gradAttr = color[gradName]; gradients = renderer.gradients; stops = color.stops; radialReference = elem.radialReference; // Keep < 2.2 kompatibility if (isArray(gradAttr)) { color[gradName] = gradAttr = { x1: gradAttr[0], y1: gradAttr[1], x2: gradAttr[2], y2: gradAttr[3], gradientUnits: 'userSpaceOnUse' }; } // Correct the radial gradient for the radial reference system if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) { extend(gradAttr, { cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2], cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2], r: gradAttr.r * radialReference[2], gradientUnits: 'userSpaceOnUse' }); } // Build the unique key to detect whether we need to create a new element (#1282) for (n in gradAttr) { if (n !== 'id') { key.push(n, gradAttr[n]); } } for (n in stops) { key.push(stops[n]); } key = key.join(','); // Check if a gradient object with the same config object is created within this renderer if (gradients[key]) { id = gradients[key].id; } else { // Set the id and create the element gradAttr.id = id = PREFIX + idCounter++; gradients[key] = gradientObject = renderer.createElement(gradName) .attr(gradAttr) .add(renderer.defs); // The gradient needs to keep a list of stops to be able to destroy them gradientObject.stops = []; each(stops, function (stop) { var stopObject; if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } stopObject = renderer.createElement('stop').attr({ offset: stop[0], 'stop-color': stopColor, 'stop-opacity': stopOpacity }).add(gradientObject); // Add the stop element to the gradient gradientObject.stops.push(stopObject); }); } // Return the reference to the gradient object return 'url(' + renderer.url + '#' + id + ')'; // Webkit and Batik can't show rgba. } else if (regexRgba.test(color)) { colorObject = Color(color); attr(elem, prop + '-opacity', colorObject.get('a')); return colorObject.get('rgb'); } else { // Remove the opacity attribute added above. Does not throw if the attribute is not there. elem.removeAttribute(prop + '-opacity'); return color; } }, /** * Add text to the SVG object * @param {String} str * @param {Number} x Left position * @param {Number} y Top position * @param {Boolean} useHTML Use HTML to render the text */ text: function (str, x, y, useHTML) { // declare variables var renderer = this, defaultChartStyle = defaultOptions.chart.style, fakeSVG = useCanVG || (!hasSVG && renderer.forExport), wrapper; if (useHTML && !renderer.forExport) { return renderer.html(str, x, y); } x = mathRound(pick(x, 0)); y = mathRound(pick(y, 0)); wrapper = renderer.createElement('text') .attr({ x: x, y: y, text: str }) .css({ fontFamily: defaultChartStyle.fontFamily, fontSize: defaultChartStyle.fontSize }); // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063) if (fakeSVG) { wrapper.css({ position: ABSOLUTE }); } wrapper.x = x; wrapper.y = y; return wrapper; }, /** * Create HTML text node. This is used by the VML renderer as well as the SVG * renderer through the useHTML option. * * @param {String} str * @param {Number} x * @param {Number} y */ html: function (str, x, y) { var defaultChartStyle = defaultOptions.chart.style, wrapper = this.createElement('span'), attrSetters = wrapper.attrSetters, element = wrapper.element, renderer = wrapper.renderer; // Text setter attrSetters.text = function (value) { if (value !== element.innerHTML) { delete this.bBox; } element.innerHTML = value; return false; }; // Various setters which rely on update transform attrSetters.x = attrSetters.y = attrSetters.align = function (value, key) { if (key === 'align') { key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML. } wrapper[key] = value; wrapper.htmlUpdateTransform(); return false; }; // Set the default attributes wrapper.attr({ text: str, x: mathRound(x), y: mathRound(y) }) .css({ position: ABSOLUTE, whiteSpace: 'nowrap', fontFamily: defaultChartStyle.fontFamily, fontSize: defaultChartStyle.fontSize }); // Use the HTML specific .css method wrapper.css = wrapper.htmlCss; // This is specific for HTML within SVG if (renderer.isSVG) { wrapper.add = function (svgGroupWrapper) { var htmlGroup, container = renderer.box.parentNode, parentGroup, parents = []; // Create a mock group to hold the HTML elements if (svgGroupWrapper) { htmlGroup = svgGroupWrapper.div; if (!htmlGroup) { // Read the parent chain into an array and read from top down parentGroup = svgGroupWrapper; while (parentGroup) { parents.push(parentGroup); // Move up to the next parent group parentGroup = parentGroup.parentGroup; } // Ensure dynamically updating position when any parent is translated each(parents.reverse(), function (parentGroup) { var htmlGroupStyle; // Create a HTML div and append it to the parent div to emulate // the SVG group structure htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, { className: attr(parentGroup.element, 'class') }, { position: ABSOLUTE, left: (parentGroup.translateX || 0) + PX, top: (parentGroup.translateY || 0) + PX }, htmlGroup || container); // the top group is appended to container // Shortcut htmlGroupStyle = htmlGroup.style; // Set listeners to update the HTML div's position whenever the SVG group // position is changed extend(parentGroup.attrSetters, { translateX: function (value) { htmlGroupStyle.left = value + PX; }, translateY: function (value) { htmlGroupStyle.top = value + PX; }, visibility: function (value, key) { htmlGroupStyle[key] = value; } }); }); } } else { htmlGroup = container; } htmlGroup.appendChild(element); // Shared with VML: wrapper.added = true; if (wrapper.alignOnAdd) { wrapper.htmlUpdateTransform(); } return wrapper; }; } return wrapper; }, /** * Utility to return the baseline offset and total line height from the font size */ fontMetrics: function (fontSize) { fontSize = pInt(fontSize || 11); // Empirical values found by comparing font size and bounding box height. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/ var lineHeight = fontSize < 24 ? fontSize + 4 : mathRound(fontSize * 1.2), baseline = mathRound(lineHeight * 0.8); return { h: lineHeight, b: baseline }; }, /** * Add a label, a text item that can hold a colored or gradient background * as well as a border and shadow. * @param {string} str * @param {Number} x * @param {Number} y * @param {String} shape * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the * coordinates it should be pinned to * @param {Number} anchorY * @param {Boolean} baseline Whether to position the label relative to the text baseline, * like renderer.text, or to the upper border of the rectangle. * @param {String} className Class name for the group */ label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) { var renderer = this, wrapper = renderer.g(className), text = renderer.text('', 0, 0, useHTML) .attr({ zIndex: 1 }), //.add(wrapper), box, bBox, alignFactor = 0, padding = 3, width, height, wrapperX, wrapperY, crispAdjust = 0, deferredAttr = {}, baselineOffset, attrSetters = wrapper.attrSetters, needsBox; /** * This function runs after the label is added to the DOM (when the bounding box is * available), and after the text of the label is updated to detect the new bounding * box and reflect it in the border box. */ function updateBoxSize() { var boxY, style = text.element.style; bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && text.getBBox(); wrapper.width = (width || bBox.width || 0) + 2 * padding; wrapper.height = (height || bBox.height || 0) + 2 * padding; // update the label-scoped y offset baselineOffset = padding + renderer.fontMetrics(style && style.fontSize).b; if (needsBox) { // create the border box if it is not already present if (!box) { boxY = baseline ? -baselineOffset : 0; wrapper.box = box = shape ? renderer.symbol(shape, -alignFactor * padding, boxY, wrapper.width, wrapper.height) : renderer.rect(-alignFactor * padding, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]); box.add(wrapper); } // apply the box attributes box.attr(merge({ width: wrapper.width, height: wrapper.height }, deferredAttr)); deferredAttr = null; } } /** * This function runs after setting text or padding, but only if padding is changed */ function updateTextPadding() { var styles = wrapper.styles, textAlign = styles && styles.textAlign, x = padding * (1 - alignFactor), y; // determin y based on the baseline y = baseline ? 0 : baselineOffset; // compensate for alignment if (defined(width) && (textAlign === 'center' || textAlign === 'right')) { x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width); } // update if anything changed if (x !== text.x || y !== text.y) { text.attr({ x: x, y: y }); } // record current values text.x = x; text.y = y; } /** * Set a box attribute, or defer it if the box is not yet created * @param {Object} key * @param {Object} value */ function boxAttr(key, value) { if (box) { box.attr(key, value); } else { deferredAttr[key] = value; } } function getSizeAfterAdd() { text.add(wrapper); wrapper.attr({ text: str, // alignment is available now x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } } /** * After the text element is added, get the desired size of the border box * and add it before the text in the DOM. */ addEvent(wrapper, 'add', getSizeAfterAdd); /* * Add specific attribute setters. */ // only change local variables attrSetters.width = function (value) { width = value; return false; }; attrSetters.height = function (value) { height = value; return false; }; attrSetters.padding = function (value) { if (defined(value) && value !== padding) { padding = value; updateTextPadding(); } return false; }; // change local variable and set attribue as well attrSetters.align = function (value) { alignFactor = { left: 0, center: 0.5, right: 1 }[value]; return false; // prevent setting text-anchor on the group }; // apply these to the box and the text alike attrSetters.text = function (value, key) { text.attr(key, value); updateBoxSize(); updateTextPadding(); return false; }; // apply these to the box but not to the text attrSetters[STROKE_WIDTH] = function (value, key) { needsBox = true; crispAdjust = value % 2 / 2; boxAttr(key, value); return false; }; attrSetters.stroke = attrSetters.fill = attrSetters.r = function (value, key) { if (key === 'fill') { needsBox = true; } boxAttr(key, value); return false; }; attrSetters.anchorX = function (value, key) { anchorX = value; boxAttr(key, value + crispAdjust - wrapperX); return false; }; attrSetters.anchorY = function (value, key) { anchorY = value; boxAttr(key, value - wrapperY); return false; }; // rename attributes attrSetters.x = function (value) { wrapper.x = value; // for animation getter value -= alignFactor * ((width || bBox.width) + padding); wrapperX = mathRound(value); wrapper.attr('translateX', wrapperX); return false; }; attrSetters.y = function (value) { wrapperY = wrapper.y = mathRound(value); wrapper.attr('translateY', value); return false; }; // Redirect certain methods to either the box or the text var baseCss = wrapper.css; return extend(wrapper, { /** * Pick up some properties and apply them to the text instead of the wrapper */ css: function (styles) { if (styles) { var textStyles = {}; styles = merge({}, styles); // create a copy to avoid altering the original object (#537) each(['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width'], function (prop) { if (styles[prop] !== UNDEFINED) { textStyles[prop] = styles[prop]; delete styles[prop]; } }); text.css(textStyles); } return baseCss.call(wrapper, styles); }, /** * Return the bounding box of the box, not the group */ getBBox: function () { return { width: bBox.width + 2 * padding, height: bBox.height + 2 * padding, x: bBox.x - padding, y: bBox.y - padding }; }, /** * Apply the shadow to the box */ shadow: function (b) { if (box) { box.shadow(b); } return wrapper; }, /** * Destroy and release memory. */ destroy: function () { removeEvent(wrapper, 'add', getSizeAfterAdd); // Added by button implementation removeEvent(wrapper.element, 'mouseenter'); removeEvent(wrapper.element, 'mouseleave'); if (text) { text = text.destroy(); } if (box) { box = box.destroy(); } // Call base implementation to destroy the rest SVGElement.prototype.destroy.call(wrapper); // Release local pointers (#1298) wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = getSizeAfterAdd = null; } }); } }; // end SVGRenderer // general renderer Renderer = SVGRenderer; /* **************************************************************************** * * * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * * For applications and websites that don't need IE support, like platform * * targeted mobile apps and web apps, this code can be removed. * * * *****************************************************************************/ /** * @constructor */ var VMLRenderer; if (!hasSVG && !useCanVG) { /** * The VML element wrapper. */ var VMLElement = { /** * Initialize a new VML element wrapper. It builds the markup as a string * to minimize DOM traffic. * @param {Object} renderer * @param {Object} nodeName */ init: function (renderer, nodeName) { var wrapper = this, markup = ['<', nodeName, ' filled="f" stroked="f"'], style = ['position: ', ABSOLUTE, ';']; // divs and shapes need size if (nodeName === 'shape' || nodeName === DIV) { style.push('left:0;top:0;width:1px;height:1px;'); } if (docMode8) { style.push('visibility: ', nodeName === DIV ? HIDDEN : VISIBLE); } markup.push(' style="', style.join(''), '"/>'); // create element with default attributes and style if (nodeName) { markup = nodeName === DIV || nodeName === 'span' || nodeName === 'img' ? markup.join('') : renderer.prepVML(markup); wrapper.element = createElement(markup); } wrapper.renderer = renderer; wrapper.attrSetters = {}; }, /** * Add the node to the given parent * @param {Object} parent */ add: function (parent) { var wrapper = this, renderer = wrapper.renderer, element = wrapper.element, box = renderer.box, inverted = parent && parent.inverted, // get the parent node parentNode = parent ? parent.element || parent : box; // if the parent group is inverted, apply inversion on all children if (inverted) { // only on groups renderer.invertChild(element, parentNode); } // append it parentNode.appendChild(element); // align text after adding to be able to read offset wrapper.added = true; if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) { wrapper.updateTransform(); } // fire an event for internal hooks fireEvent(wrapper, 'add'); return wrapper; }, /** * VML always uses htmlUpdateTransform */ updateTransform: SVGElement.prototype.htmlUpdateTransform, /** * Get or set attributes */ attr: function (hash, val) { var wrapper = this, key, value, i, result, element = wrapper.element || {}, elemStyle = element.style, nodeName = element.nodeName, renderer = wrapper.renderer, symbolName = wrapper.symbolName, hasSetSymbolSize, shadows = wrapper.shadows, skipAttr, attrSetters = wrapper.attrSetters, ret = wrapper; // single key-value pair if (isString(hash) && defined(val)) { key = hash; hash = {}; hash[key] = val; } // used as a getter, val is undefined if (isString(hash)) { key = hash; if (key === 'strokeWidth' || key === 'stroke-width') { ret = wrapper.strokeweight; } else { ret = wrapper[key]; } // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; // check for a specific attribute setter result = attrSetters[key] && attrSetters[key].call(wrapper, value, key); if (result !== false && value !== null) { // #620 if (result !== UNDEFINED) { value = result; // the attribute setter has returned a new value to set } // prepare paths // symbols if (symbolName && /^(x|y|r|start|end|width|height|innerR|anchorX|anchorY)/.test(key)) { // if one of the symbol size affecting parameters are changed, // check all the others only once for each call to an element's // .attr() method if (!hasSetSymbolSize) { wrapper.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } else if (key === 'd') { value = value || []; wrapper.d = value.join(' '); // used in getter for animation // convert paths i = value.length; var convertedPath = []; while (i--) { // Multiply by 10 to allow subpixel precision. // Substracting half a pixel seems to make the coordinates // align with SVG, but this hasn't been tested thoroughly if (isNumber(value[i])) { convertedPath[i] = mathRound(value[i] * 10) - 5; } else if (value[i] === 'Z') { // close the path convertedPath[i] = 'x'; } else { convertedPath[i] = value[i]; } } value = convertedPath.join(' ') || 'x'; element.path = value; // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value; } } skipAttr = true; // handle visibility } else if (key === 'visibility') { // let the shadow follow the main element if (shadows) { i = shadows.length; while (i--) { shadows[i].style[key] = value; } } // Instead of toggling the visibility CSS property, move the div out of the viewport. // This works around #61 and #586 if (nodeName === 'DIV') { value = value === HIDDEN ? '-999em' : 0; key = 'top'; } elemStyle[key] = value; skipAttr = true; // directly mapped to css } else if (key === 'zIndex') { if (value) { elemStyle[key] = value; } skipAttr = true; // width and height } else if (key === 'width' || key === 'height') { value = mathMax(0, value); // don't set width or height below zero (#311) this[key] = value; // used in getter // clipping rectangle special if (wrapper.updateClipping) { wrapper[key] = value; wrapper.updateClipping(); } else { // normal elemStyle[key] = value; } skipAttr = true; // x and y } else if (key === 'x' || key === 'y') { wrapper[key] = value; // used in getter elemStyle[{ x: 'left', y: 'top' }[key]] = value; // class name } else if (key === 'class') { // IE8 Standards mode has problems retrieving the className element.className = value; // stroke } else if (key === 'stroke') { value = renderer.color(value, element, key); key = 'strokecolor'; // stroke width } else if (key === 'stroke-width' || key === 'strokeWidth') { element.stroked = value ? true : false; key = 'strokeweight'; wrapper[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += PX; } // dashStyle } else if (key === 'dashstyle') { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; wrapper.dashstyle = value; /* because changing stroke-width will change the dash length and cause an epileptic effect */ skipAttr = true; // fill } else if (key === 'fill') { if (nodeName === 'SPAN') { // text color elemStyle.color = value; } else if (nodeName !== 'IMG') { // #1336 element.filled = value !== NONE ? true : false; value = renderer.color(value, element, key, wrapper); key = 'fillcolor'; } // rotation on VML elements } else if (nodeName === 'shape' && key === 'rotation') { wrapper[key] = value; // Correction for the 1x1 size of the shape container. Used in gauge needles. element.style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX; element.style.top = mathRound(mathCos(value * deg2rad)) + PX; // translation for animation } else if (key === 'translateX' || key === 'translateY' || key === 'rotation') { wrapper[key] = value; wrapper.updateTransform(); skipAttr = true; // text for rotated and non-rotated elements } else if (key === 'text') { this.bBox = null; element.innerHTML = value; skipAttr = true; } if (!skipAttr) { if (docMode8) { // IE8 setAttribute bug element[key] = value; } else { attr(element, key, value); } } } } } return ret; }, /** * Set the element's clipping to a predefined rectangle * * @param {String} id The id of the clip rectangle */ clip: function (clipRect) { var wrapper = this, clipMembers, element = wrapper.element, parentNode = element.parentNode, cssRet; if (clipRect) { clipMembers = clipRect.members; erase(clipMembers, wrapper); // Ensure unique list of elements (#1258) clipMembers.push(wrapper); wrapper.destroyClip = function () { erase(clipMembers, wrapper); }; // Issue #863 workaround - related to #140, #61, #74 if (parentNode && parentNode.className === 'highcharts-tracker' && !docMode8) { css(element, { visibility: HIDDEN }); } cssRet = clipRect.getCSS(wrapper); } else { if (wrapper.destroyClip) { wrapper.destroyClip(); } cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214 } return wrapper.css(cssRet); }, /** * Set styles for the element * @param {Object} styles */ css: SVGElement.prototype.htmlCss, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { // discardElement will detach the node from its parent before attaching it // to the garbage bin. Therefore it is important that the node is attached and have parent. if (element.parentNode) { discardElement(element); } }, /** * Extend element.destroy by removing it from the clip members array */ destroy: function () { if (this.destroyClip) { this.destroyClip(); } return SVGElement.prototype.destroy.apply(this); }, /** * Remove all child nodes of a group, except the v:group element */ empty: function () { var element = this.element, childNodes = element.childNodes, i = childNodes.length, node; while (i--) { node = childNodes[i]; node.parentNode.removeChild(node); } }, /** * Add an event listener. VML override for normalizing event parameters. * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { // simplest possible event model for internal use this.element['on' + eventType] = function () { var evt = win.event; evt.target = evt.srcElement; handler(evt); }; return this; }, /** * In stacked columns, cut off the shadows so that they don't overlap */ cutOffPath: function (path, length) { var len; path = path.split(/[ ,]/); len = path.length; if (len === 9 || len === 11) { path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length; } return path.join(' '); }, /** * Apply a drop shadow by copying elements and giving them different strokes * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, element = this.element, renderer = this.renderer, shadow, elemStyle = element.style, markup, path = element.path, strokeWidth, modifiedPath, shadowWidth, shadowElementOpacity; // some times empty paths are not strings if (path && typeof path.value !== 'string') { path = 'x'; } modifiedPath = path; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; for (i = 1; i <= 3; i++) { strokeWidth = (shadowWidth * 2) + 1 - (2 * i); // Cut off shadows for stacked column items if (cutOff) { modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5); } markup = ['<shape isShadow="true" strokeweight="', strokeWidth, '" filled="false" path="', modifiedPath, '" coordsize="10 10" style="', element.style.cssText, '" />']; shadow = createElement(renderer.prepVML(markup), null, { left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1), top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1) } ); if (cutOff) { shadow.cutOff = strokeWidth + 1; } // apply the opacity markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>']; createElement(renderer.prepVML(markup), null, null, shadow); // insert it if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } // record it shadows.push(shadow); } this.shadows = shadows; } return this; } }; VMLElement = extendClass(SVGElement, VMLElement); /** * The VML renderer */ var VMLRendererExtension = { // inherit SVGRenderer Element: VMLElement, isIE8: userAgent.indexOf('MSIE 8.0') > -1, /** * Initialize the VMLRenderer * @param {Object} container * @param {Number} width * @param {Number} height */ init: function (container, width, height) { var renderer = this, boxWrapper, box; renderer.alignedObjects = []; boxWrapper = renderer.createElement(DIV); box = boxWrapper.element; box.style.position = RELATIVE; // for freeform drawing using renderer directly container.appendChild(boxWrapper.element); // generate the containing box renderer.box = box; renderer.boxWrapper = boxWrapper; renderer.setSize(width, height, false); // The only way to make IE6 and IE7 print is to use a global namespace. However, // with IE8 the only way to make the dynamic shapes visible in screen and print mode // seems to be to add the xmlns attribute and the behaviour style inline. if (!doc.namespaces.hcv) { doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml'); // setup default css doc.createStyleSheet().cssText = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' + '{ behavior:url(#default#VML); display: inline-block; } '; } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none */ isHidden: function () { return !this.box.offsetWidth; }, /** * Define a clipping rectangle. In VML it is accomplished by storing the values * for setting the CSS style to all associated members. * * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { // create a dummy element var clipRect = this.createElement(), isObj = isObject(x); // mimic a rectangle with its style object for automatic updating in attr return extend(clipRect, { members: [], left: isObj ? x.x : x, top: isObj ? x.y : y, width: isObj ? x.width : width, height: isObj ? x.height : height, getCSS: function (wrapper) { var inverted = wrapper.inverted, rect = this, top = rect.top, left = rect.left, right = left + rect.width, bottom = top + rect.height, ret = { clip: 'rect(' + mathRound(inverted ? left : top) + 'px,' + mathRound(inverted ? bottom : right) + 'px,' + mathRound(inverted ? right : bottom) + 'px,' + mathRound(inverted ? top : left) + 'px)' }; // issue 74 workaround if (!inverted && docMode8 && wrapper.element.nodeName !== 'IMG') { extend(ret, { width: right + PX, height: bottom + PX }); } return ret; }, // used in attr and animation to update the clipping of all members updateClipping: function () { each(clipRect.members, function (member) { member.css(clipRect.getCSS(member)); }); } }); }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object, and apply opacity. * * @param {Object} color The color or config object */ color: function (color, elem, prop, wrapper) { var renderer = this, colorObject, regexRgba = /^rgba/, markup, fillType, ret = NONE; // Check for linear or radial gradient if (color && color.linearGradient) { fillType = 'gradient'; } else if (color && color.radialGradient) { fillType = 'pattern'; } if (fillType) { var stopColor, stopOpacity, gradient = color.linearGradient || color.radialGradient, x1, y1, x2, y2, opacity1, opacity2, color1, color2, fillAttr = '', stops = color.stops, firstStop, lastStop, colors = [], addFillNode = function () { // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1, '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />']; createElement(renderer.prepVML(markup), null, null, elem); }; // Extend from 0 to 1 firstStop = stops[0]; lastStop = stops[stops.length - 1]; if (firstStop[0] > 0) { stops.unshift([ 0, firstStop[1] ]); } if (lastStop[0] < 1) { stops.push([ 1, lastStop[1] ]); } // Compute the stops each(stops, function (stop, i) { if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } // Build the color attribute colors.push((stop[0] * 100) + '% ' + stopColor); // Only start and end opacities are allowed, so we use the first and the last if (!i) { opacity1 = stopOpacity; color2 = stopColor; } else { opacity2 = stopOpacity; color1 = stopColor; } }); // Apply the gradient to fills only. if (prop === 'fill') { // Handle linear gradient angle if (fillType === 'gradient') { x1 = gradient.x1 || gradient[0] || 0; y1 = gradient.y1 || gradient[1] || 0; x2 = gradient.x2 || gradient[2] || 0; y2 = gradient.y2 || gradient[3] || 0; fillAttr = 'angle="' + (90 - math.atan( (y2 - y1) / // y vector (x2 - x1) // x vector ) * 180 / mathPI) + '"'; addFillNode(); // Radial (circular) gradient } else { var r = gradient.r, sizex = r * 2, sizey = r * 2, cx = gradient.cx, cy = gradient.cy, radialReference = elem.radialReference, bBox, applyRadialGradient = function () { if (radialReference) { bBox = wrapper.getBBox(); cx += (radialReference[0] - bBox.x) / bBox.width - 0.5; cy += (radialReference[1] - bBox.y) / bBox.height - 0.5; sizex *= radialReference[2] / bBox.width; sizey *= radialReference[2] / bBox.height; } fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' + 'size="' + sizex + ',' + sizey + '" ' + 'origin="0.5,0.5" ' + 'position="' + cx + ',' + cy + '" ' + 'color2="' + color2 + '" '; addFillNode(); }; // Apply radial gradient if (wrapper.added) { applyRadialGradient(); } else { // We need to know the bounding box to get the size and position right addEvent(wrapper, 'add', applyRadialGradient); } // The fill element's color attribute is broken in IE8 standards mode, so we // need to set the parent shape's fillcolor attribute instead. ret = color1; } // Gradients are not supported for VML stroke, return the first color. #722. } else { ret = stopColor; } // if the color is an rgba color, split it and add a fill node // to hold the opacity component } else if (regexRgba.test(color) && elem.tagName !== 'IMG') { colorObject = Color(color); markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>']; createElement(this.prepVML(markup), null, null, elem); ret = colorObject.get('rgb'); } else { var strokeNodes = elem.getElementsByTagName(prop); if (strokeNodes.length) { strokeNodes[0].opacity = 1; } ret = color; } return ret; }, /** * Take a VML string and prepare it for either IE8 or IE6/IE7. * @param {Array} markup A string array of the VML markup to prepare */ prepVML: function (markup) { var vmlStyle = 'display:inline-block;behavior:url(#default#VML);', isIE8 = this.isIE8; markup = markup.join(''); if (isIE8) { // add xmlns and style inline markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />'); if (markup.indexOf('style="') === -1) { markup = markup.replace('/>', ' style="' + vmlStyle + '" />'); } else { markup = markup.replace('style="', 'style="' + vmlStyle); } } else { // add namespace markup = markup.replace('<', '<hcv:'); } return markup; }, /** * Create rotated and aligned text * @param {String} str * @param {Number} x * @param {Number} y */ text: SVGRenderer.prototype.html, /** * Create and return a path element * @param {Array} path */ path: function (path) { var attr = { // subpixel precision down to 0.1 (width and height = 1px) coordsize: '10 10' }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } // create the shape return this.createElement('shape').attr(attr); }, /** * Create and return a circle element. In VML circles are implemented as * shapes, which is faster than v:oval * @param {Number} x * @param {Number} y * @param {Number} r */ circle: function (x, y, r) { return this.symbol('circle').attr({ x: x - r, y: y - r, width: 2 * r, height: 2 * r }); }, /** * Create a group using an outer div and an inner v:group to allow rotating * and flipping. A simple v:group would have problems with positioning * child HTML elements and CSS clip. * * @param {String} name The name of the group */ g: function (name) { var wrapper, attribs; // set the class name if (name) { attribs = { 'className': PREFIX + name, 'class': PREFIX + name }; } // the div to hold HTML and clipping wrapper = this.createElement(DIV).attr(attribs); return wrapper; }, /** * VML override to create a regular HTML image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var obj = this.createElement('img') .attr({ src: src }); if (arguments.length > 1) { obj.attr({ x: x, y: y, width: width, height: height }); } return obj; }, /** * VML uses a shape for rect to overcome bugs and rotation problems */ rect: function (x, y, width, height, r, strokeWidth) { if (isObject(x)) { y = x.y; width = x.width; height = x.height; strokeWidth = x.strokeWidth; x = x.x; } var wrapper = this.symbol('rect'); wrapper.r = r; return wrapper.attr(wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0))); }, /** * In the VML renderer, each child of an inverted div (group) is inverted * @param {Object} element * @param {Object} parentNode */ invertChild: function (element, parentNode) { var parentStyle = parentNode.style; css(element, { flip: 'x', left: pInt(parentStyle.width) - 1, top: pInt(parentStyle.height) - 1, rotation: -90 }); }, /** * Symbol definitions that override the parent SVG renderer's symbols * */ symbols: { // VML specific arc function arc: function (x, y, w, h, options) { var start = options.start, end = options.end, radius = options.r || w || h, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), innerRadius = options.innerR, circleCorrection = 0.08 / radius, // #760 innerCorrection = (innerRadius && 0.1 / innerRadius) || 0, ret; if (end - start === 0) { // no angle, don't show it. return ['x']; } else if (2 * mathPI - end + start < circleCorrection) { // full circle // empirical correction found by trying out the limits for different radii cosEnd = -circleCorrection; } else if (end - start < innerCorrection) { // issue #186, another mysterious VML arc problem cosEnd = mathCos(start + innerCorrection); } ret = [ 'wa', // clockwise arc to x - radius, // left y - radius, // top x + radius, // right y + radius, // bottom x + radius * cosStart, // start x y + radius * sinStart, // start y x + radius * cosEnd, // end x y + radius * sinEnd // end y ]; if (options.open && !innerRadius) { ret.push( 'e', M, x,// - innerRadius, y// - innerRadius ); } ret.push( 'at', // anti clockwise arc to x - innerRadius, // left y - innerRadius, // top x + innerRadius, // right y + innerRadius, // bottom x + innerRadius * cosEnd, // start x y + innerRadius * sinEnd, // start y x + innerRadius * cosStart, // end x y + innerRadius * sinStart, // end y 'x', // finish path 'e' // close ); return ret; }, // Add circle symbol path. This performs significantly faster than v:oval. circle: function (x, y, w, h) { return [ 'wa', // clockwisearcto x, // left y, // top x + w, // right y + h, // bottom x + w, // start x y + h / 2, // start y x + w, // end x y + h / 2, // end y //'x', // finish path 'e' // close ]; }, /** * Add rectangle symbol path which eases rotation and omits arcsize problems * compared to the built-in VML roundrect shape * * @param {Number} left Left position * @param {Number} top Top position * @param {Number} r Border radius * @param {Object} options Width and height */ rect: function (left, top, width, height, options) { var right = left + width, bottom = top + height, ret, r; // No radius, return the more lightweight square if (!defined(options) || !options.r) { ret = SVGRenderer.prototype.symbols.square.apply(0, arguments); // Has radius add arcs for the corners } else { r = mathMin(options.r, width, height); ret = [ M, left + r, top, L, right - r, top, 'wa', right - 2 * r, top, right, top + 2 * r, right - r, top, right, top + r, L, right, bottom - r, 'wa', right - 2 * r, bottom - 2 * r, right, bottom, right, bottom - r, right - r, bottom, L, left + r, bottom, 'wa', left, bottom - 2 * r, left + 2 * r, bottom, left + r, bottom, left, bottom - r, L, left, top + r, 'wa', left, top, left + 2 * r, top + 2 * r, left, top + r, left + r, top, 'x', 'e' ]; } return ret; } } }; VMLRenderer = function () { this.init.apply(this, arguments); }; VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension); // general renderer Renderer = VMLRenderer; } /* **************************************************************************** * * * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * *****************************************************************************/ /* **************************************************************************** * * * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT * * TARGETING THAT SYSTEM. * * * *****************************************************************************/ var CanVGRenderer, CanVGController; if (useCanVG) { /** * The CanVGRenderer is empty from start to keep the source footprint small. * When requested, the CanVGController downloads the rest of the source packaged * together with the canvg library. */ CanVGRenderer = function () { // Override the global SVG namespace to fake SVG/HTML that accepts CSS SVG_NS = 'http://www.w3.org/1999/xhtml'; }; /** * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but * the implementation from SvgRenderer will not be merged in until first render. */ CanVGRenderer.prototype.symbols = {}; /** * Handles on demand download of canvg rendering support. */ CanVGController = (function () { // List of renderering calls var deferredRenderCalls = []; /** * When downloaded, we are ready to draw deferred charts. */ function drawDeferred() { var callLength = deferredRenderCalls.length, callIndex; // Draw all pending render calls for (callIndex = 0; callIndex < callLength; callIndex++) { deferredRenderCalls[callIndex](); } // Clear the list deferredRenderCalls = []; } return { push: function (func, scriptLocation) { // Only get the script once if (deferredRenderCalls.length === 0) { getScript(scriptLocation, drawDeferred); } // Register render call deferredRenderCalls.push(func); } }; }()); } // end CanVGRenderer /* **************************************************************************** * * * END OF ANDROID < 3 SPECIFIC CODE * * * *****************************************************************************/ /** * General renderer */ Renderer = VMLRenderer || CanVGRenderer || SVGRenderer; /** * The Tick class */ function Tick(axis, pos, type) { this.axis = axis; this.pos = pos; this.type = type || ''; this.isNew = true; if (!type) { this.addLabel(); } } Tick.prototype = { /** * Write the tick label */ addLabel: function () { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, horiz = axis.horiz, categories = axis.categories, pos = tick.pos, labelOptions = options.labels, str, tickPositions = axis.tickPositions, width = (categories && horiz && categories.length && !labelOptions.step && !labelOptions.staggerLines && !labelOptions.rotation && chart.plotWidth / tickPositions.length) || (!horiz && chart.plotWidth / 2), isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], css, attr, value = categories && defined(categories[pos]) ? categories[pos] : pos, label = tick.label, tickPositionInfo = tickPositions.info, dateTimeLabelFormat; // Set the datetime label format. If a higher rank is set for this position, use that. If not, // use the general format. if (axis.isDatetimeAxis && tickPositionInfo) { dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName]; } // set properties for access in render method tick.isFirst = isFirst; tick.isLast = isLast; // get the string str = axis.labelFormatter.call({ axis: axis, chart: chart, isFirst: isFirst, isLast: isLast, dateTimeLabelFormat: dateTimeLabelFormat, value: axis.isLog ? correctFloat(lin2log(value)) : value }); // prepare CSS css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX }; css = extend(css, labelOptions.style); // first call if (!defined(label)) { attr = { align: labelOptions.align }; if (isNumber(labelOptions.rotation)) { attr.rotation = labelOptions.rotation; } tick.label = defined(str) && labelOptions.enabled ? chart.renderer.text( str, 0, 0, labelOptions.useHTML ) .attr(attr) // without position absolute, IE export sometimes is wrong .css(css) .add(axis.labelGroup) : null; // update } else if (label) { label.attr({ text: str }) .css(css); } }, /** * Get the offset height or width of the label */ getLabelSize: function () { var label = this.label, axis = this.axis; return label ? ((this.labelBBox = label.getBBox()))[axis.horiz ? 'height' : 'width'] : 0; }, /** * Find how far the labels extend to the right and left of the tick's x position. Used for anti-collision * detection with overflow logic. */ getLabelSides: function () { var bBox = this.labelBBox, // assume getLabelSize has run at this point axis = this.axis, options = axis.options, labelOptions = options.labels, width = bBox.width, leftSide = width * { left: 0, center: 0.5, right: 1 }[labelOptions.align] - labelOptions.x; return [-leftSide, width - leftSide]; }, /** * Handle the label overflow by adjusting the labels to the left and right edge, or * hide them if they collide into the neighbour label. */ handleOverflow: function (index, xy) { var show = true, axis = this.axis, chart = axis.chart, isFirst = this.isFirst, isLast = this.isLast, x = xy.x, reversed = axis.reversed, tickPositions = axis.tickPositions; if (isFirst || isLast) { var sides = this.getLabelSides(), leftSide = sides[0], rightSide = sides[1], plotLeft = chart.plotLeft, plotRight = plotLeft + axis.len, neighbour = axis.ticks[tickPositions[index + (isFirst ? 1 : -1)]], neighbourEdge = neighbour && neighbour.label.xy && neighbour.label.xy.x + neighbour.getLabelSides()[isFirst ? 0 : 1]; if ((isFirst && !reversed) || (isLast && reversed)) { // Is the label spilling out to the left of the plot area? if (x + leftSide < plotLeft) { // Align it to plot left x = plotLeft - leftSide; // Hide it if it now overlaps the neighbour label if (neighbour && x + rightSide > neighbourEdge) { show = false; } } } else { // Is the label spilling out to the right of the plot area? if (x + rightSide > plotRight) { // Align it to plot right x = plotRight - rightSide; // Hide it if it now overlaps the neighbour label if (neighbour && x + leftSide < neighbourEdge) { show = false; } } } // Set the modified x position of the label xy.x = x; } return show; }, /** * Get the x and y position for ticks and labels */ getPosition: function (horiz, pos, tickmarkOffset, old) { var axis = this.axis, chart = axis.chart, cHeight = (old && chart.oldChartHeight) || chart.chartHeight; return { x: horiz ? axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0), y: horiz ? cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB }; }, /** * Get the x, y position of the tick label */ getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, transA = axis.transA, reversed = axis.reversed, staggerLines = axis.staggerLines; x = x + labelOptions.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + labelOptions.y - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Vertically centered if (!defined(labelOptions.y)) { y += pInt(label.styles.lineHeight) * 0.9 - label.getBBox().height / 2; } // Correct for staggered labels if (staggerLines) { y += (index / (step || 1) % staggerLines) * 16; } return { x: x, y: y }; }, /** * Extendible method to return the path of the marker */ getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) { return renderer.crispLine([ M, x, y, L, x + (horiz ? 0 : -tickLength), y + (horiz ? tickLength : 0) ], tickWidth); }, /** * Put everything in place * * @param index {Number} * @param old {Boolean} Use old coordinates to prepare an animation into new position */ render: function (index, old) { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, renderer = chart.renderer, horiz = axis.horiz, type = tick.type, label = tick.label, pos = tick.pos, labelOptions = options.labels, gridLine = tick.gridLine, gridPrefix = type ? type + 'Grid' : 'grid', tickPrefix = type ? type + 'Tick' : 'tick', gridLineWidth = options[gridPrefix + 'LineWidth'], gridLineColor = options[gridPrefix + 'LineColor'], dashStyle = options[gridPrefix + 'LineDashStyle'], tickLength = options[tickPrefix + 'Length'], tickWidth = options[tickPrefix + 'Width'] || 0, tickColor = options[tickPrefix + 'Color'], tickPosition = options[tickPrefix + 'Position'], gridLinePath, mark = tick.mark, markPath, step = labelOptions.step, attribs, show = true, tickmarkOffset = axis.tickmarkOffset, xy = tick.getPosition(horiz, pos, tickmarkOffset, old), x = xy.x, y = xy.y, staggerLines = axis.staggerLines; // create the grid line if (gridLineWidth) { gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth, old); if (gridLine === UNDEFINED) { attribs = { stroke: gridLineColor, 'stroke-width': gridLineWidth }; if (dashStyle) { attribs.dashstyle = dashStyle; } if (!type) { attribs.zIndex = 1; } tick.gridLine = gridLine = gridLineWidth ? renderer.path(gridLinePath) .attr(attribs).add(axis.gridGroup) : null; } // If the parameter 'old' is set, the current call will be followed // by another call, therefore do not do any animations this time if (!old && gridLine && gridLinePath) { gridLine[tick.isNew ? 'attr' : 'animate']({ d: gridLinePath }); } } // create the tick mark if (tickWidth && tickLength) { // negate the length if (tickPosition === 'inside') { tickLength = -tickLength; } if (axis.opposite) { tickLength = -tickLength; } markPath = tick.getMarkPath(x, y, tickLength, tickWidth, horiz, renderer); if (mark) { // updating mark.animate({ d: markPath }); } else { // first time tick.mark = renderer.path( markPath ).attr({ stroke: tickColor, 'stroke-width': tickWidth }).add(axis.axisGroup); } } // the label is created on init - now move it into place if (label && !isNaN(x)) { label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step); // apply show first and show last if ((tick.isFirst && !pick(options.showFirstLabel, 1)) || (tick.isLast && !pick(options.showLastLabel, 1))) { show = false; // Handle label overflow and show or hide accordingly } else if (!staggerLines && horiz && labelOptions.overflow === 'justify' && !tick.handleOverflow(index, xy)) { show = false; } // apply step if (step && index % step) { // show those indices dividable by step show = false; } // Set the new position, and show or hide if (show) { label[tick.isNew ? 'attr' : 'animate'](xy); tick.isNew = false; } else { label.attr('y', -9999); // #1338 } } }, /** * Destructor for the tick prototype */ destroy: function () { destroyObjectProperties(this, this.axis); } }; /** * The object wrapper for plot lines and plot bands * @param {Object} options */ function PlotLineOrBand(axis, options) { this.axis = axis; if (options) { this.options = options; this.id = options.id; } //plotLine.render() return this; } PlotLineOrBand.prototype = { /** * Render the plot line or plot band. If it is already existing, * move it. */ render: function () { var plotLine = this, axis = plotLine.axis, horiz = axis.horiz, halfPointRange = (axis.pointRange || 0) / 2, options = plotLine.options, optionsLabel = options.label, label = plotLine.label, width = options.width, to = options.to, from = options.from, isBand = defined(from) && defined(to), value = options.value, dashStyle = options.dashStyle, svgElem = plotLine.svgElem, path = [], addEvent, eventType, xs, ys, x, y, color = options.color, zIndex = options.zIndex, events = options.events, attribs, renderer = axis.chart.renderer; // logarithmic conversion if (axis.isLog) { from = log2lin(from); to = log2lin(to); value = log2lin(value); } // plot line if (width) { path = axis.getPlotLinePath(value, width); attribs = { stroke: color, 'stroke-width': width }; if (dashStyle) { attribs.dashstyle = dashStyle; } } else if (isBand) { // plot band // keep within plot area from = mathMax(from, axis.min - halfPointRange); to = mathMin(to, axis.max + halfPointRange); path = axis.getPlotBandPath(from, to, options); attribs = { fill: color }; if (options.borderWidth) { attribs.stroke = options.borderColor; attribs['stroke-width'] = options.borderWidth; } } else { return; } // zIndex if (defined(zIndex)) { attribs.zIndex = zIndex; } // common for lines and bands if (svgElem) { if (path) { svgElem.animate({ d: path }, null, svgElem.onGetPath); } else { svgElem.hide(); svgElem.onGetPath = function () { svgElem.show(); }; } } else if (path && path.length) { plotLine.svgElem = svgElem = renderer.path(path) .attr(attribs).add(); // events if (events) { addEvent = function (eventType) { svgElem.on(eventType, function (e) { events[eventType].apply(plotLine, [e]); }); }; for (eventType in events) { addEvent(eventType); } } } // the plot band/line label if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) { // apply defaults optionsLabel = merge({ align: horiz && isBand && 'center', x: horiz ? !isBand && 4 : 10, verticalAlign : !horiz && isBand && 'middle', y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4, rotation: horiz && !isBand && 90 }, optionsLabel); // add the SVG element if (!label) { plotLine.label = label = renderer.text( optionsLabel.text, 0, 0 ) .attr({ align: optionsLabel.textAlign || optionsLabel.align, rotation: optionsLabel.rotation, zIndex: zIndex }) .css(optionsLabel.style) .add(); } // get the bounding box and align the label xs = [path[1], path[4], pick(path[6], path[1])]; ys = [path[2], path[5], pick(path[7], path[2])]; x = arrayMin(xs); y = arrayMin(ys); label.align(optionsLabel, false, { x: x, y: y, width: arrayMax(xs) - x, height: arrayMax(ys) - y }); label.show(); } else if (label) { // move out of sight label.hide(); } // chainable return plotLine; }, /** * Remove the plot line or band */ destroy: function () { var plotLine = this, axis = plotLine.axis; // remove it from the lookup erase(axis.plotLinesAndBands, plotLine); destroyObjectProperties(plotLine, this.axis); } }; /** * The class for stack items */ function StackItem(axis, options, isNegative, x, stackOption, stacking) { var inverted = axis.chart.inverted; this.axis = axis; // Tells if the stack is negative this.isNegative = isNegative; // Save the options to be able to style the label this.options = options; // Save the x value to be able to position the label later this.x = x; // Save the stack option on the series configuration object, and whether to treat it as percent this.stack = stackOption; this.percent = stacking === 'percent'; // The align options and text align varies on whether the stack is negative and // if the chart is inverted or not. // First test the user supplied value, then use the dynamic. this.alignOptions = { align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'), verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')), y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)), x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0) }; this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center'); } StackItem.prototype = { destroy: function () { destroyObjectProperties(this, this.axis); }, /** * Sets the total of this stack. Should be called when a serie is hidden or shown * since that will affect the total of other stacks. */ setTotal: function (total) { this.total = total; this.cum = total; }, /** * Renders the stack total label and adds it to the stack label group. */ render: function (group) { var str = this.options.formatter.call(this); // format the text in the label // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden if (this.label) { this.label.attr({text: str, visibility: HIDDEN}); // Create new label } else { this.label = this.axis.chart.renderer.text(str, 0, 0) // dummy positions, actual position updated with setOffset method in columnseries .css(this.options.style) // apply style .attr({ align: this.textAlign, // fix the text-anchor rotation: this.options.rotation, // rotation visibility: HIDDEN // hidden until setOffset is called }) .add(group); // add to the labels-group } }, /** * Sets the offset that the stack has from the x value and repositions the label. */ setOffset: function (xOffset, xWidth) { var stackItem = this, axis = stackItem.axis, chart = axis.chart, inverted = chart.inverted, neg = this.isNegative, // special treatment is needed for negative stacks y = axis.translate(this.percent ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates yZero = axis.translate(0), // stack origin h = mathAbs(y - yZero), // stack height x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position plotHeight = chart.plotHeight, stackBox = { // this is the box for the complete stack x: inverted ? (neg ? y : y - h) : x, y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y), width: inverted ? h : xWidth, height: inverted ? xWidth : h }, label = this.label, alignAttr; if (label) { label.align(this.alignOptions, null, stackBox); // align the label to the box // Set visibility (#678) alignAttr = label.alignAttr; label.attr({ visibility: this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? (hasSVG ? 'inherit' : VISIBLE) : HIDDEN }); } } }; /** * Create a new axis object * @param {Object} chart * @param {Object} options */ function Axis() { this.init.apply(this, arguments); } Axis.prototype = { /** * Default options for the X axis - the Y axis has extended defaults */ defaultOptions: { // allowDecimals: null, // alternateGridColor: null, // categories: [], dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y' }, endOnTick: false, gridLineColor: '#C0C0C0', // gridLineDashStyle: 'solid', // gridLineWidth: 0, // reversed: false, labels: defaultLabelOptions, // { step: null }, lineColor: '#C0D0E0', lineWidth: 1, //linkedTo: null, //max: undefined, //min: undefined, minPadding: 0.01, maxPadding: 0.01, //minRange: null, minorGridLineColor: '#E0E0E0', // minorGridLineDashStyle: null, minorGridLineWidth: 1, minorTickColor: '#A0A0A0', //minorTickInterval: null, minorTickLength: 2, minorTickPosition: 'outside', // inside or outside //minorTickWidth: 0, //opposite: false, //offset: 0, //plotBands: [{ // events: {}, // zIndex: 1, // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //plotLines: [{ // events: {} // dashStyle: {} // zIndex: // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //reversed: false, // showFirstLabel: true, // showLastLabel: true, startOfWeek: 1, startOnTick: false, tickColor: '#C0D0E0', //tickInterval: null, tickLength: 5, tickmarkPlacement: 'between', // on or between tickPixelInterval: 100, tickPosition: 'outside', tickWidth: 1, title: { //text: null, align: 'middle', // low, middle or high //margin: 0 for horizontal, 10 for vertical axes, //rotation: 0, //side: 'outside', style: { color: '#6D869F', //font: defaultFont.replace('normal', 'bold') fontWeight: 'bold' } //x: 0, //y: 0 }, type: 'linear' // linear, logarithmic or datetime }, /** * This options set extends the defaultOptions for Y axes */ defaultYAxisOptions: { endOnTick: true, gridLineWidth: 1, tickPixelInterval: 72, showLastLabel: true, labels: { align: 'right', x: -8, y: 3 }, lineWidth: 0, maxPadding: 0.05, minPadding: 0.05, startOnTick: true, tickWidth: 0, title: { rotation: 270, text: 'Y-values' }, stackLabels: { enabled: false, //align: dynamic, //y: dynamic, //x: dynamic, //verticalAlign: dynamic, //textAlign: dynamic, //rotation: 0, formatter: function () { return this.total; }, style: defaultLabelOptions.style } }, /** * These options extend the defaultOptions for left axes */ defaultLeftAxisOptions: { labels: { align: 'right', x: -8, y: null }, title: { rotation: 270 } }, /** * These options extend the defaultOptions for right axes */ defaultRightAxisOptions: { labels: { align: 'left', x: 8, y: null }, title: { rotation: 90 } }, /** * These options extend the defaultOptions for bottom axes */ defaultBottomAxisOptions: { labels: { align: 'center', x: 0, y: 14 // overflow: undefined, // staggerLines: null }, title: { rotation: 0 } }, /** * These options extend the defaultOptions for left axes */ defaultTopAxisOptions: { labels: { align: 'center', x: 0, y: -5 // overflow: undefined // staggerLines: null }, title: { rotation: 0 } }, /** * Initialize the axis */ init: function (chart, userOptions) { var isXAxis = userOptions.isX, axis = this; // Flag, is the axis horizontal axis.horiz = chart.inverted ? !isXAxis : isXAxis; // Flag, isXAxis axis.isXAxis = isXAxis; axis.xOrY = isXAxis ? 'x' : 'y'; axis.opposite = userOptions.opposite; // needed in setOptions axis.side = axis.horiz ? (axis.opposite ? 0 : 2) : // top : bottom (axis.opposite ? 1 : 3); // right : left axis.setOptions(userOptions); var options = this.options, type = options.type, isDatetimeAxis = type === 'datetime'; axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format // Flag, stagger lines or not axis.staggerLines = axis.horiz && options.labels.staggerLines; axis.userOptions = userOptions; //axis.axisTitleMargin = UNDEFINED,// = options.title.margin, axis.minPixelPadding = 0; //axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series //axis.ignoreMaxPadding = UNDEFINED; axis.chart = chart; axis.reversed = options.reversed; // Initial categories axis.categories = options.categories; // Elements //axis.axisGroup = UNDEFINED; //axis.gridGroup = UNDEFINED; //axis.axisTitle = UNDEFINED; //axis.axisLine = UNDEFINED; // Flag if type === logarithmic axis.isLog = type === 'logarithmic'; // Flag, if axis is linked to another axis axis.isLinked = defined(options.linkedTo); // Linked axis. //axis.linkedParent = UNDEFINED; // Flag if type === datetime axis.isDatetimeAxis = isDatetimeAxis; // Flag if percentage mode //axis.usePercentage = UNDEFINED; // Tick positions //axis.tickPositions = UNDEFINED; // array containing predefined positions // Tick intervals //axis.tickInterval = UNDEFINED; //axis.minorTickInterval = UNDEFINED; axis.tickmarkOffset = (options.categories && options.tickmarkPlacement === 'between') ? 0.5 : 0; // Major ticks axis.ticks = {}; // Minor ticks axis.minorTicks = {}; //axis.tickAmount = UNDEFINED; // List of plotLines/Bands axis.plotLinesAndBands = []; // Alternate bands axis.alternateBands = {}; // Axis metrics //axis.left = UNDEFINED; //axis.top = UNDEFINED; //axis.width = UNDEFINED; //axis.height = UNDEFINED; //axis.bottom = UNDEFINED; //axis.right = UNDEFINED; //axis.transA = UNDEFINED; //axis.transB = UNDEFINED; //axis.oldTransA = UNDEFINED; axis.len = 0; //axis.oldMin = UNDEFINED; //axis.oldMax = UNDEFINED; //axis.oldUserMin = UNDEFINED; //axis.oldUserMax = UNDEFINED; //axis.oldAxisLength = UNDEFINED; axis.minRange = axis.userMinRange = options.minRange || options.maxZoom; axis.range = options.range; axis.offset = options.offset || 0; // Dictionary for stacks axis.stacks = {}; // Min and max in the data //axis.dataMin = UNDEFINED, //axis.dataMax = UNDEFINED, // The axis range axis.max = null; axis.min = null; // User set min and max //axis.userMin = UNDEFINED, //axis.userMax = UNDEFINED, // Run Axis var eventType, events = axis.options.events; // Register chart.axes.push(axis); chart[isXAxis ? 'xAxis' : 'yAxis'].push(axis); axis.series = []; // populated by Series // inverted charts have reversed xAxes as default if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) { axis.reversed = true; } axis.removePlotBand = axis.removePlotBandOrLine; axis.removePlotLine = axis.removePlotBandOrLine; axis.addPlotBand = axis.addPlotBandOrLine; axis.addPlotLine = axis.addPlotBandOrLine; // register event listeners for (eventType in events) { addEvent(axis, eventType, events[eventType]); } // extend logarithmic axis if (axis.isLog) { axis.val2lin = log2lin; axis.lin2val = lin2log; } }, /** * Merge and set options */ setOptions: function (userOptions) { this.options = merge( this.defaultOptions, this.isXAxis ? {} : this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions, this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side], merge( defaultOptions[this.isXAxis ? 'xAxis' : 'yAxis'], // if set in setOptions (#1053) userOptions ) ); }, /** * The default label formatter. The context is a special config object for the label. */ defaultLabelFormatter: function () { var axis = this.axis, value = this.value, categories = axis.categories, dateTimeLabelFormat = this.dateTimeLabelFormat, numericSymbols = defaultOptions.lang.numericSymbols, i = numericSymbols && numericSymbols.length, multi, ret, // make sure the same symbol is added for all labels on a linear axis numericSymbolDetector = axis.isLog ? value : axis.tickInterval; if (categories) { ret = value; } else if (dateTimeLabelFormat) { // datetime axis ret = dateFormat(dateTimeLabelFormat, value); } else if (i && numericSymbolDetector >= 1000) { // Decide whether we should add a numeric symbol like k (thousands) or M (millions). // If we are to enable this in tooltip or other places as well, we can move this // logic to the numberFormatter and enable it by a parameter. while (i-- && ret === UNDEFINED) { multi = Math.pow(1000, i + 1); if (numericSymbolDetector >= multi && numericSymbols[i] !== null) { ret = numberFormat(value / multi, -1) + numericSymbols[i]; } } } if (ret === UNDEFINED) { if (value >= 1000) { // add thousands separators ret = numberFormat(value, 0); } else { // small numbers ret = numberFormat(value, -1); } } return ret; }, /** * Get the minimum and maximum for the series of each axis */ getSeriesExtremes: function () { var axis = this, chart = axis.chart, stacks = axis.stacks, posStack = [], negStack = [], i; axis.hasVisibleSeries = false; // reset dataMin and dataMax in case we're redrawing axis.dataMin = axis.dataMax = null; // loop through this axis' series each(axis.series, function (series) { if (series.visible || !chart.options.chart.ignoreHiddenSeries) { var seriesOptions = series.options, stacking, posPointStack, negPointStack, stackKey, stackOption, negKey, xData, yData, x, y, threshold = seriesOptions.threshold, yDataLength, activeYData = [], activeCounter = 0; axis.hasVisibleSeries = true; // Validate threshold in logarithmic axes if (axis.isLog && threshold <= 0) { threshold = seriesOptions.threshold = null; } // Get dataMin and dataMax for X axes if (axis.isXAxis) { xData = series.xData; if (xData.length) { axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData)); axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData)); } // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data } else { var isNegative, pointStack, key, cropped = series.cropped, xExtremes = series.xAxis.getExtremes(), //findPointRange, //pointRange, j, hasModifyValue = !!series.modifyValue; // Handle stacking stacking = seriesOptions.stacking; axis.usePercentage = stacking === 'percent'; // create a stack for this particular series type if (stacking) { stackOption = seriesOptions.stack; stackKey = series.type + pick(stackOption, ''); negKey = '-' + stackKey; series.stackKey = stackKey; // used in translate posPointStack = posStack[stackKey] || []; // contains the total values for each x posStack[stackKey] = posPointStack; negPointStack = negStack[negKey] || []; negStack[negKey] = negPointStack; } if (axis.usePercentage) { axis.dataMin = 0; axis.dataMax = 99; } // processData can alter series.pointRange, so this goes after //findPointRange = series.pointRange === null; xData = series.processedXData; yData = series.processedYData; yDataLength = yData.length; // loop over the non-null y values and read them into a local array for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; // Read stacked values into a stack based on the x value, // the sign of y and the stack key. Stacking is also handled for null values (#739) if (stacking) { isNegative = y < threshold; pointStack = isNegative ? negPointStack : posPointStack; key = isNegative ? negKey : stackKey; // Set the stack value and y for extremes if (defined(pointStack[x])) { // we're adding to the stack pointStack[x] = correctFloat(pointStack[x] + y); y = [y, pointStack[x]]; // consider both the actual value and the stack (#1376) } else { // it's the first point in the stack pointStack[x] = y; } // add the series if (!stacks[key]) { stacks[key] = {}; } // If the StackItem is there, just update the values, // if not, create one first if (!stacks[key][x]) { stacks[key][x] = new StackItem(axis, axis.options.stackLabels, isNegative, x, stackOption, stacking); } stacks[key][x].setTotal(pointStack[x]); } // Handle non null values if (y !== null && y !== UNDEFINED) { // general hook, used for Highstock compare values feature if (hasModifyValue) { y = series.modifyValue(y); } // for points within the visible range, including the first point outside the // visible range, consider y extremes if (cropped || ((xData[i + 1] || x) >= xExtremes.min && (xData[i - 1] || x) <= xExtremes.max)) { j = y.length; if (j) { // array, like ohlc or range data while (j--) { if (y[j] !== null) { activeYData[activeCounter++] = y[j]; } } } else { activeYData[activeCounter++] = y; } } } } // Get the dataMin and dataMax so far. If percentage is used, the min and max are // always 0 and 100. If the length of activeYData is 0, continue with null values. if (!axis.usePercentage && activeYData.length) { axis.dataMin = mathMin(pick(axis.dataMin, activeYData[0]), arrayMin(activeYData)); axis.dataMax = mathMax(pick(axis.dataMax, activeYData[0]), arrayMax(activeYData)); } // Adjust to threshold if (defined(threshold)) { if (axis.dataMin >= threshold) { axis.dataMin = threshold; axis.ignoreMinPadding = true; } else if (axis.dataMax < threshold) { axis.dataMax = threshold; axis.ignoreMaxPadding = true; } } } } }); }, /** * Translate from axis value to pixel position on the chart, or back * */ translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacementBetween) { var axis = this, axisLength = axis.len, sign = 1, cvsOffset = 0, localA = old ? axis.oldTransA : axis.transA, localMin = old ? axis.oldMin : axis.min, returnValue, postTranslate = axis.options.ordinal || (axis.isLog && handleLog); if (!localA) { localA = axis.transA; } if (cvsCoord) { sign *= -1; // canvas coordinates inverts the value cvsOffset = axisLength; } if (axis.reversed) { // reversed axis sign *= -1; cvsOffset -= sign * axisLength; } if (backwards) { // reverse translation if (axis.reversed) { val = axisLength - val; } returnValue = val / localA + localMin; // from chart pixel to value if (postTranslate) { // log and ordinal axes returnValue = axis.lin2val(returnValue); } } else { // normal translation, from axis value to pixel, relative to plot if (postTranslate) { // log and ordinal axes val = axis.val2lin(val); } returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * axis.minPixelPadding) + (pointPlacementBetween ? localA * axis.pointRange / 2 : 0); } return returnValue; }, /** * Create the path for a plot line that goes from the given value on * this axis, across the plot to the opposite side * @param {Number} value * @param {Number} lineWidth Used for calculation crisp line * @param {Number] old Use old coordinates (for resizing and rescaling) */ getPlotLinePath: function (value, lineWidth, old) { var axis = this, chart = axis.chart, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, translatedValue = axis.translate(value, null, null, old), cHeight = (old && chart.oldChartHeight) || chart.chartHeight, cWidth = (old && chart.oldChartWidth) || chart.chartWidth, skip, transB = axis.transB; x1 = x2 = mathRound(translatedValue + transB); y1 = y2 = mathRound(cHeight - translatedValue - transB); if (isNaN(translatedValue)) { // no min or max skip = true; } else if (axis.horiz) { y1 = axisTop; y2 = cHeight - axis.bottom; if (x1 < axisLeft || x1 > axisLeft + axis.width) { skip = true; } } else { x1 = axisLeft; x2 = cWidth - axis.right; if (y1 < axisTop || y1 > axisTop + axis.height) { skip = true; } } return skip ? null : chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 0); }, /** * Create the path for a plot band */ getPlotBandPath: function (from, to) { var toPath = this.getPlotLinePath(to), path = this.getPlotLinePath(from); if (path && toPath) { path.push( toPath[4], toPath[5], toPath[1], toPath[2] ); } else { // outside the axis area path = null; } return path; }, /** * Set the tick positions of a linear axis to round values like whole tens or every five. */ getLinearTickPositions: function (tickInterval, min, max) { var pos, lastPos, roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval), roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval), tickPositions = []; // Populate the intermediate values pos = roundedMin; while (pos <= roundedMax) { // Place the tick on the rounded value tickPositions.push(pos); // Always add the raw tickInterval, not the corrected one. pos = correctFloat(pos + tickInterval); // If the interval is not big enough in the current min - max range to actually increase // the loop variable, we need to break out to prevent endless loop. Issue #619 if (pos === lastPos) { break; } // Record the last value lastPos = pos; } return tickPositions; }, /** * Set the tick positions of a logarithmic axis */ getLogTickPositions: function (interval, min, max, minor) { var axis = this, options = axis.options, axisLength = axis.len; // Since we use this method for both major and minor ticks, // use a local variable and return the result var positions = []; // Reset if (!minor) { axis._minorAutoInterval = null; } // First case: All ticks fall on whole logarithms: 1, 10, 100 etc. if (interval >= 0.5) { interval = mathRound(interval); positions = axis.getLinearTickPositions(interval, min, max); // Second case: We need intermediary ticks. For example // 1, 2, 4, 6, 8, 10, 20, 40 etc. } else if (interval >= 0.08) { var roundedMin = mathFloor(min), intermediate, i, j, len, pos, lastPos, break2; if (interval > 0.3) { intermediate = [1, 2, 4]; } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc intermediate = [1, 2, 4, 6, 8]; } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9]; } for (i = roundedMin; i < max + 1 && !break2; i++) { len = intermediate.length; for (j = 0; j < len && !break2; j++) { pos = log2lin(lin2log(i) * intermediate[j]); if (pos > min) { positions.push(lastPos); } if (lastPos > max) { break2 = true; } lastPos = pos; } } // Third case: We are so deep in between whole logarithmic values that // we might as well handle the tick positions like a linear axis. For // example 1.01, 1.02, 1.03, 1.04. } else { var realMin = lin2log(min), realMax = lin2log(max), tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'], filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption, tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1), totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength; interval = pick( filteredTickIntervalOption, axis._minorAutoInterval, (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1) ); interval = normalizeTickInterval( interval, null, math.pow(10, mathFloor(math.log(interval) / math.LN10)) ); positions = map(axis.getLinearTickPositions( interval, realMin, realMax ), log2lin); if (!minor) { axis._minorAutoInterval = interval / 5; } } // Set the axis-level tickInterval variable if (!minor) { axis.tickInterval = interval; } return positions; }, /** * Return the minor tick positions. For logarithmic axes, reuse the same logic * as for major ticks. */ getMinorTickPositions: function () { var axis = this, options = axis.options, tickPositions = axis.tickPositions, minorTickInterval = axis.minorTickInterval; var minorTickPositions = [], pos, i, len; if (axis.isLog) { len = tickPositions.length; for (i = 1; i < len; i++) { minorTickPositions = minorTickPositions.concat( axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true) ); } } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314 minorTickPositions = minorTickPositions.concat( getTimeTicks( normalizeTimeTickInterval(minorTickInterval), axis.min, axis.max, options.startOfWeek ) ); } else { for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) { minorTickPositions.push(pos); } } return minorTickPositions; }, /** * Adjust the min and max for the minimum range. Keep in mind that the series data is * not yet processed, so we don't have information on data cropping and grouping, or * updated axis.pointRange or series.pointRange. The data can't be processed until * we have finally established min and max. */ adjustForMinRange: function () { var axis = this, options = axis.options, min = axis.min, max = axis.max, zoomOffset, spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange, closestDataRange, i, distance, xData, loopLength, minArgs, maxArgs; // Set the automatic minimum range based on the closest point distance if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) { if (defined(options.min) || defined(options.max)) { axis.minRange = null; // don't do this again } else { // Find the closest distance between raw data points, as opposed to // closestPointRange that applies to processed points (cropped and grouped) each(axis.series, function (series) { xData = series.xData; loopLength = series.xIncrement ? 1 : xData.length - 1; for (i = loopLength; i > 0; i--) { distance = xData[i] - xData[i - 1]; if (closestDataRange === UNDEFINED || distance < closestDataRange) { closestDataRange = distance; } } }); axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin); } } // if minRange is exceeded, adjust if (max - min < axis.minRange) { var minRange = axis.minRange; zoomOffset = (minRange - max + min) / 2; // if min and max options have been set, don't go beyond it minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)]; if (spaceAvailable) { // if space is available, stay within the data range minArgs[2] = axis.dataMin; } min = arrayMax(minArgs); maxArgs = [min + minRange, pick(options.max, min + minRange)]; if (spaceAvailable) { // if space is availabe, stay within the data range maxArgs[2] = axis.dataMax; } max = arrayMin(maxArgs); // now if the max is adjusted, adjust the min back if (max - min < minRange) { minArgs[0] = max - minRange; minArgs[1] = pick(options.min, max - minRange); min = arrayMax(minArgs); } } // Record modified extremes axis.min = min; axis.max = max; }, /** * Update translation information */ setAxisTranslation: function () { var axis = this, range = axis.max - axis.min, pointRange = 0, closestPointRange, minPointOffset = 0, pointRangePadding = 0, linkedParent = axis.linkedParent, transA = axis.transA; // adjust translation for padding if (axis.isXAxis) { if (linkedParent) { minPointOffset = linkedParent.minPointOffset; pointRangePadding = linkedParent.pointRangePadding; } else { each(axis.series, function (series) { var seriesPointRange = series.pointRange, pointPlacement = series.options.pointPlacement, seriesClosestPointRange = series.closestPointRange; pointRange = mathMax(pointRange, seriesPointRange); // minPointOffset is the value padding to the left of the axis in order to make // room for points with a pointRange, typically columns. When the pointPlacement option // is 'between' or 'on', this padding does not apply. minPointOffset = mathMax( minPointOffset, pointPlacement ? 0 : seriesPointRange / 2 ); // Determine the total padding needed to the length of the axis to make room for the // pointRange. If the series' pointPlacement is 'on', no padding is added. pointRangePadding = mathMax( pointRangePadding, pointPlacement === 'on' ? 0 : seriesPointRange ); // Set the closestPointRange if (!series.noSharedTooltip && defined(seriesClosestPointRange)) { closestPointRange = defined(closestPointRange) ? mathMin(closestPointRange, seriesClosestPointRange) : seriesClosestPointRange; } }); } // Record minPointOffset and pointRangePadding axis.minPointOffset = minPointOffset; axis.pointRangePadding = pointRangePadding; // pointRange means the width reserved for each point, like in a column chart axis.pointRange = pointRange; // closestPointRange means the closest distance between points. In columns // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange // is some other value axis.closestPointRange = closestPointRange; } // secondary values axis.oldTransA = transA; //axis.translationSlope = axis.transA = transA = axis.len / ((range + (2 * minPointOffset)) || 1); axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1); axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend axis.minPixelPadding = transA * minPointOffset; }, /** * Set the tick positions to round values and optionally extend the extremes * to the nearest tick */ setTickPositions: function (secondPass) { var axis = this, chart = axis.chart, options = axis.options, isLog = axis.isLog, isDatetimeAxis = axis.isDatetimeAxis, isXAxis = axis.isXAxis, isLinked = axis.isLinked, tickPositioner = axis.options.tickPositioner, magnitude, maxPadding = options.maxPadding, minPadding = options.minPadding, length, linkedParentExtremes, tickIntervalOption = options.tickInterval, minTickIntervalOption = options.minTickInterval, tickPixelIntervalOption = options.tickPixelInterval, tickPositions, categories = axis.categories; // linked axis gets the extremes from the parent axis if (isLinked) { axis.linkedParent = chart[isXAxis ? 'xAxis' : 'yAxis'][options.linkedTo]; linkedParentExtremes = axis.linkedParent.getExtremes(); axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin); axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax); if (options.type !== axis.linkedParent.options.type) { error(11, 1); // Can't link axes of different type } } else { // initial min and max from the extreme data values axis.min = pick(axis.userMin, options.min, axis.dataMin); axis.max = pick(axis.userMax, options.max, axis.dataMax); } if (isLog) { if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978 error(10, 1); // Can't plot negative values on log axis } axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934 axis.max = correctFloat(log2lin(axis.max)); } // handle zoomed range if (axis.range) { axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618 axis.userMax = axis.max; if (secondPass) { axis.range = null; // don't use it when running setExtremes } } // adjust min and max for the minimum range axis.adjustForMinRange(); // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding // into account, we do this after computing tick interval (#1337). if (!categories && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) { length = axis.max - axis.min; if (length) { if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) { axis.min -= length * minPadding; } if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) { axis.max += length * maxPadding; } } } // get tickInterval if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) { axis.tickInterval = 1; } else if (isLinked && !tickIntervalOption && tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) { axis.tickInterval = axis.linkedParent.tickInterval; } else { axis.tickInterval = pick( tickIntervalOption, categories ? // for categoried axis, 1 is default, for linear axis use tickPix 1 : (axis.max - axis.min) * tickPixelIntervalOption / (axis.len || 1) ); } // Now we're finished detecting min and max, crop and group series data. This // is in turn needed in order to find tick positions in ordinal axes. if (isXAxis && !secondPass) { each(axis.series, function (series) { series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax); }); } // set the translation factor used in translate function axis.setAxisTranslation(secondPass); // hook for ordinal axes and radial axes if (axis.beforeSetTickPositions) { axis.beforeSetTickPositions(); } // hook for extensions, used in Highstock ordinal axes if (axis.postProcessTickInterval) { axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval); } // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined. if (!tickIntervalOption && axis.tickInterval < minTickIntervalOption) { axis.tickInterval = minTickIntervalOption; } // for linear axes, get magnitude and normalize the interval if (!isDatetimeAxis && !isLog) { // linear magnitude = math.pow(10, mathFloor(math.log(axis.tickInterval) / math.LN10)); if (!tickIntervalOption) { axis.tickInterval = normalizeTickInterval(axis.tickInterval, null, magnitude, options); } } // get minorTickInterval axis.minorTickInterval = options.minorTickInterval === 'auto' && axis.tickInterval ? axis.tickInterval / 5 : options.minorTickInterval; // find the tick positions axis.tickPositions = tickPositions = options.tickPositions || (tickPositioner && tickPositioner.apply(axis, [axis.min, axis.max])); if (!tickPositions) { if (isDatetimeAxis) { tickPositions = (axis.getNonLinearTimeTicks || getTimeTicks)( normalizeTimeTickInterval(axis.tickInterval, options.units), axis.min, axis.max, options.startOfWeek, axis.ordinalPositions, axis.closestPointRange, true ); } else if (isLog) { tickPositions = axis.getLogTickPositions(axis.tickInterval, axis.min, axis.max); } else { tickPositions = axis.getLinearTickPositions(axis.tickInterval, axis.min, axis.max); } axis.tickPositions = tickPositions; } if (!isLinked) { // reset min/max or remove extremes based on start/end on tick var roundedMin = tickPositions[0], roundedMax = tickPositions[tickPositions.length - 1], minPointOffset = axis.minPointOffset || 0, singlePad; if (options.startOnTick) { axis.min = roundedMin; } else if (axis.min - minPointOffset > roundedMin) { tickPositions.shift(); } if (options.endOnTick) { axis.max = roundedMax; } else if (axis.max + minPointOffset < roundedMax) { tickPositions.pop(); } // When there is only one point, or all points have the same value on this axis, then min // and max are equal and tickPositions.length is 1. In this case, add some padding // in order to center the point, but leave it with one tick. #1337. if (tickPositions.length === 1) { singlePad = 1e-9; // The lowest possible number to avoid extra padding on columns axis.min -= singlePad; axis.max += singlePad; } } }, /** * Set the max ticks of either the x and y axis collection */ setMaxTicks: function () { var chart = this.chart, maxTicks = chart.maxTicks, tickPositions = this.tickPositions, xOrY = this.xOrY; if (!maxTicks) { // first call, or maxTicks have been reset after a zoom operation maxTicks = { x: 0, y: 0 }; } if (!this.isLinked && !this.isDatetimeAxis && tickPositions.length > maxTicks[xOrY] && this.options.alignTicks !== false) { maxTicks[xOrY] = tickPositions.length; } chart.maxTicks = maxTicks; }, /** * When using multiple axes, adjust the number of ticks to match the highest * number of ticks in that group */ adjustTickAmount: function () { var axis = this, chart = axis.chart, xOrY = axis.xOrY, tickPositions = axis.tickPositions, maxTicks = chart.maxTicks; if (maxTicks && maxTicks[xOrY] && !axis.isDatetimeAxis && !axis.categories && !axis.isLinked && axis.options.alignTicks !== false) { // only apply to linear scale var oldTickAmount = axis.tickAmount, calculatedTickAmount = tickPositions.length, tickAmount; // set the axis-level tickAmount to use below axis.tickAmount = tickAmount = maxTicks[xOrY]; if (calculatedTickAmount < tickAmount) { while (tickPositions.length < tickAmount) { tickPositions.push(correctFloat( tickPositions[tickPositions.length - 1] + axis.tickInterval )); } axis.transA *= (calculatedTickAmount - 1) / (tickAmount - 1); axis.max = tickPositions[tickPositions.length - 1]; } if (defined(oldTickAmount) && tickAmount !== oldTickAmount) { axis.isDirty = true; } } }, /** * Set the scale based on data min and max, user set min and max or options * */ setScale: function () { var axis = this, stacks = axis.stacks, type, i, isDirtyData, isDirtyAxisLength; axis.oldMin = axis.min; axis.oldMax = axis.max; axis.oldAxisLength = axis.len; // set the new axisLength axis.setAxisSize(); //axisLength = horiz ? axisWidth : axisHeight; isDirtyAxisLength = axis.len !== axis.oldAxisLength; // is there new data? each(axis.series, function (series) { if (series.isDirtyData || series.isDirty || series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well isDirtyData = true; } }); // do we really need to go through all this? if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) { // get data extremes if needed axis.getSeriesExtremes(); // get fixed positions based on tickInterval axis.setTickPositions(); // record old values to decide whether a rescale is necessary later on (#540) axis.oldUserMin = axis.userMin; axis.oldUserMax = axis.userMax; // Mark as dirty if it is not already set to dirty and extremes have changed. #595. if (!axis.isDirty) { axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax; } } // reset stacks if (!axis.isXAxis) { for (type in stacks) { for (i in stacks[type]) { stacks[type][i].cum = stacks[type][i].total; } } } // Set the maximum tick amount axis.setMaxTicks(); }, /** * Set the extremes and optionally redraw * @param {Number} newMin * @param {Number} newMax * @param {Boolean} redraw * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * @param {Object} eventArguments * */ setExtremes: function (newMin, newMax, redraw, animation, eventArguments) { var axis = this, chart = axis.chart; redraw = pick(redraw, true); // defaults to true // Extend the arguments with min and max eventArguments = extend(eventArguments, { min: newMin, max: newMax }); // Fire the event fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler axis.userMin = newMin; axis.userMax = newMax; // Mark for running afterSetExtremes axis.isDirtyExtremes = true; // redraw if (redraw) { chart.redraw(animation); } }); }, /** * Overridable method for zooming chart. Pulled out in a separate method to allow overriding * in stock charts. */ zoom: function (newMin, newMax) { this.setExtremes(newMin, newMax, false, UNDEFINED, { trigger: 'zoom' }); return true; }, /** * Update the axis metrics */ setAxisSize: function () { var axis = this, chart = axis.chart, options = axis.options; var offsetLeft = options.offsetLeft || 0, offsetRight = options.offsetRight || 0; // basic values // expose to use in Series object and navigator axis.left = pick(options.left, chart.plotLeft + offsetLeft); axis.top = pick(options.top, chart.plotTop); axis.width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight); axis.height = pick(options.height, chart.plotHeight); axis.bottom = chart.chartHeight - axis.height - axis.top; axis.right = chart.chartWidth - axis.width - axis.left; axis.len = mathMax(axis.horiz ? axis.width : axis.height, 0); // mathMax fixes #905 }, /** * Get the actual axis extremes */ getExtremes: function () { var axis = this, isLog = axis.isLog; return { min: isLog ? correctFloat(lin2log(axis.min)) : axis.min, max: isLog ? correctFloat(lin2log(axis.max)) : axis.max, dataMin: axis.dataMin, dataMax: axis.dataMax, userMin: axis.userMin, userMax: axis.userMax }; }, /** * Get the zero plane either based on zero or on the min or max value. * Used in bar and area plots */ getThreshold: function (threshold) { var axis = this, isLog = axis.isLog; var realMin = isLog ? lin2log(axis.min) : axis.min, realMax = isLog ? lin2log(axis.max) : axis.max; if (realMin > threshold || threshold === null) { threshold = realMin; } else if (realMax < threshold) { threshold = realMax; } return axis.translate(threshold, 0, 1, 0, 1); }, /** * Add a plot band or plot line after render time * * @param options {Object} The plotBand or plotLine configuration object */ addPlotBandOrLine: function (options) { var obj = new PlotLineOrBand(this, options).render(); this.plotLinesAndBands.push(obj); return obj; }, /** * Render the tick labels to a preliminary position to get their sizes */ getOffset: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, tickPositions = axis.tickPositions, ticks = axis.ticks, horiz = axis.horiz, side = axis.side, hasData, showAxis, titleOffset = 0, titleOffsetOption, titleMargin = 0, axisTitleOptions = options.title, labelOptions = options.labels, labelOffset = 0, // reset axisOffset = chart.axisOffset, directionFactor = [-1, 1, 1, -1][side], n; // For reuse in Axis.render axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions)); axis.showAxis = showAxis = hasData || pick(options.showEmpty, true); // Create the axisGroup and gridGroup elements on first iteration if (!axis.axisGroup) { axis.gridGroup = renderer.g('grid') .attr({ zIndex: options.gridZIndex || 1 }) .add(); axis.axisGroup = renderer.g('axis') .attr({ zIndex: options.zIndex || 2 }) .add(); axis.labelGroup = renderer.g('axis-labels') .attr({ zIndex: labelOptions.zIndex || 7 }) .add(); } if (hasData || axis.isLinked) { each(tickPositions, function (pos) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } else { ticks[pos].addLabel(); // update labels depending on tick interval } }); each(tickPositions, function (pos) { // left side must be align: right and right side must have align: left for labels if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === labelOptions.align) { // get the highest offset labelOffset = mathMax( ticks[pos].getLabelSize(), labelOffset ); } }); if (axis.staggerLines) { labelOffset += (axis.staggerLines - 1) * 16; } } else { // doesn't have data for (n in ticks) { ticks[n].destroy(); delete ticks[n]; } } if (axisTitleOptions && axisTitleOptions.text) { if (!axis.axisTitle) { axis.axisTitle = renderer.text( axisTitleOptions.text, 0, 0, axisTitleOptions.useHTML ) .attr({ zIndex: 7, rotation: axisTitleOptions.rotation || 0, align: axisTitleOptions.textAlign || { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align] }) .css(axisTitleOptions.style) .add(axis.axisGroup); axis.axisTitle.isNew = true; } if (showAxis) { titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleMargin = pick(axisTitleOptions.margin, horiz ? 5 : 10); titleOffsetOption = axisTitleOptions.offset; } // hide or show the title depending on whether showEmpty is set axis.axisTitle[showAxis ? 'show' : 'hide'](); } // handle automatic or user set offset axis.offset = directionFactor * pick(options.offset, axisOffset[side]); axis.axisTitleMargin = pick(titleOffsetOption, labelOffset + titleMargin + (side !== 2 && labelOffset && directionFactor * options.labels[horiz ? 'y' : 'x']) ); axisOffset[side] = mathMax( axisOffset[side], axis.axisTitleMargin + titleOffset + directionFactor * axis.offset ); }, /** * Get the path for the axis line */ getLinePath: function (lineWidth) { var chart = this.chart, opposite = this.opposite, offset = this.offset, horiz = this.horiz, lineLeft = this.left + (opposite ? this.width : 0) + offset, lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset; this.lineTop = lineTop; // used by flag series return chart.renderer.crispLine([ M, horiz ? this.left : lineLeft, horiz ? lineTop : this.top, L, horiz ? chart.chartWidth - this.right : lineLeft, horiz ? lineTop : chart.chartHeight - this.bottom ], lineWidth); }, /** * Position the title */ getTitlePosition: function () { // compute anchor points for each of the title align options var horiz = this.horiz, axisLeft = this.left, axisTop = this.top, axisLength = this.len, axisTitleOptions = this.options.title, margin = horiz ? axisLeft : axisTop, opposite = this.opposite, offset = this.offset, fontSize = pInt(axisTitleOptions.style.fontSize || 12), // the position in the length direction of the axis alongAxis = { low: margin + (horiz ? 0 : axisLength), middle: margin + axisLength / 2, high: margin + (horiz ? axisLength : 0) }[axisTitleOptions.align], // the position in the perpendicular direction of the axis offAxis = (horiz ? axisTop + this.height : axisLeft) + (horiz ? 1 : -1) * // horizontal axis reverses the margin (opposite ? -1 : 1) * // so does opposite axes this.axisTitleMargin + (this.side === 2 ? fontSize : 0); return { x: horiz ? alongAxis : offAxis + (opposite ? this.width : 0) + offset + (axisTitleOptions.x || 0), // x y: horiz ? offAxis - (opposite ? this.height : 0) + offset : alongAxis + (axisTitleOptions.y || 0) // y }; }, /** * Render the axis */ render: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, isLog = axis.isLog, isLinked = axis.isLinked, tickPositions = axis.tickPositions, axisTitle = axis.axisTitle, stacks = axis.stacks, ticks = axis.ticks, minorTicks = axis.minorTicks, alternateBands = axis.alternateBands, stackLabelOptions = options.stackLabels, alternateGridColor = options.alternateGridColor, tickmarkOffset = axis.tickmarkOffset, lineWidth = options.lineWidth, linePath, hasRendered = chart.hasRendered, slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin), hasData = axis.hasData, showAxis = axis.showAxis, from, to; // If the series has data draw the ticks. Else only the line and title if (hasData || isLinked) { // minor ticks if (axis.minorTickInterval && !axis.categories) { each(axis.getMinorTickPositions(), function (pos) { if (!minorTicks[pos]) { minorTicks[pos] = new Tick(axis, pos, 'minor'); } // render new ticks in old position if (slideInTicks && minorTicks[pos].isNew) { minorTicks[pos].render(null, true); } minorTicks[pos].isActive = true; minorTicks[pos].render(); }); } // Major ticks. Pull out the first item and render it last so that // we can get the position of the neighbour label. #808. if (tickPositions.length) { // #1300 each(tickPositions.slice(1).concat([tickPositions[0]]), function (pos, i) { // Reorganize the indices i = (i === tickPositions.length - 1) ? 0 : i + 1; // linked axes need an extra check to find out if if (!isLinked || (pos >= axis.min && pos <= axis.max)) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } // render new ticks in old position if (slideInTicks && ticks[pos].isNew) { ticks[pos].render(i, true); } ticks[pos].isActive = true; ticks[pos].render(i); } }); } // alternate grid color if (alternateGridColor) { each(tickPositions, function (pos, i) { if (i % 2 === 0 && pos < axis.max) { if (!alternateBands[pos]) { alternateBands[pos] = new PlotLineOrBand(axis); } from = pos + tickmarkOffset; // #949 to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max; alternateBands[pos].options = { from: isLog ? lin2log(from) : from, to: isLog ? lin2log(to) : to, color: alternateGridColor }; alternateBands[pos].render(); alternateBands[pos].isActive = true; } }); } // custom plot lines and bands if (!axis._addedPlotLB) { // only first time each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) { //plotLinesAndBands.push(new PlotLineOrBand(plotLineOptions).render()); axis.addPlotBandOrLine(plotLineOptions); }); axis._addedPlotLB = true; } } // end if hasData // remove inactive ticks each([ticks, minorTicks, alternateBands], function (coll) { var pos; for (pos in coll) { if (!coll[pos].isActive) { coll[pos].destroy(); delete coll[pos]; } else { coll[pos].isActive = false; // reset } } }); // Static items. As the axis group is cleared on subsequent calls // to render, these items are added outside the group. // axis line if (lineWidth) { linePath = axis.getLinePath(lineWidth); if (!axis.axisLine) { axis.axisLine = renderer.path(linePath) .attr({ stroke: options.lineColor, 'stroke-width': lineWidth, zIndex: 7 }) .add(axis.axisGroup); } else { axis.axisLine.animate({ d: linePath }); } // show or hide the line depending on options.showEmpty axis.axisLine[showAxis ? 'show' : 'hide'](); } if (axisTitle && showAxis) { axisTitle[axisTitle.isNew ? 'attr' : 'animate']( axis.getTitlePosition() ); axisTitle.isNew = false; } // Stacked totals: if (stackLabelOptions && stackLabelOptions.enabled) { var stackKey, oneStack, stackCategory, stackTotalGroup = axis.stackTotalGroup; // Create a separate group for the stack total labels if (!stackTotalGroup) { axis.stackTotalGroup = stackTotalGroup = renderer.g('stack-labels') .attr({ visibility: VISIBLE, zIndex: 6 }) .add(); } // plotLeft/Top will change when y axis gets wider so we need to translate the // stackTotalGroup at every render call. See bug #506 and #516 stackTotalGroup.translate(chart.plotLeft, chart.plotTop); // Render each stack total for (stackKey in stacks) { oneStack = stacks[stackKey]; for (stackCategory in oneStack) { oneStack[stackCategory].render(stackTotalGroup); } } } // End stacked totals axis.isDirty = false; }, /** * Remove a plot band or plot line from the chart by id * @param {Object} id */ removePlotBandOrLine: function (id) { var plotLinesAndBands = this.plotLinesAndBands, i = plotLinesAndBands.length; while (i--) { if (plotLinesAndBands[i].id === id) { plotLinesAndBands[i].destroy(); } } }, /** * Update the axis title by options */ setTitle: function (newTitleOptions, redraw) { var chart = this.chart, options = this.options, axisTitle = this.axisTitle; options.title = merge(options.title, newTitleOptions); this.axisTitle = axisTitle && axisTitle.destroy(); // #922 this.isDirty = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Redraw the axis to reflect changes in the data or axis extremes */ redraw: function () { var axis = this, chart = axis.chart; // hide tooltip and hover states if (chart.tracker.resetTracker) { chart.tracker.resetTracker(true); } // render the axis axis.render(); // move plot lines and bands each(axis.plotLinesAndBands, function (plotLine) { plotLine.render(); }); // mark associated series as dirty and ready for redraw each(axis.series, function (series) { series.isDirty = true; }); }, /** * Set new axis categories and optionally redraw * @param {Array} newCategories * @param {Boolean} doRedraw */ setCategories: function (newCategories, doRedraw) { var axis = this, chart = axis.chart; // set the categories axis.categories = axis.userOptions.categories = newCategories; // force reindexing tooltips each(axis.series, function (series) { series.translate(); series.setTooltipPoints(true); }); // optionally redraw axis.isDirty = true; if (pick(doRedraw, true)) { chart.redraw(); } }, /** * Destroys an Axis instance. */ destroy: function () { var axis = this, stacks = axis.stacks, stackKey; // Remove the events removeEvent(axis); // Destroy each stack total for (stackKey in stacks) { destroyObjectProperties(stacks[stackKey]); stacks[stackKey] = null; } // Destroy collections each([axis.ticks, axis.minorTicks, axis.alternateBands, axis.plotLinesAndBands], function (coll) { destroyObjectProperties(coll); }); // Destroy local variables each(['stackTotalGroup', 'axisLine', 'axisGroup', 'gridGroup', 'labelGroup', 'axisTitle'], function (prop) { if (axis[prop]) { axis[prop] = axis[prop].destroy(); } }); } }; // end Axis /** * The tooltip object * @param {Object} chart The chart instance * @param {Object} options Tooltip options */ function Tooltip(chart, options) { var borderWidth = options.borderWidth, style = options.style, padding = pInt(style.padding); // Save the chart and options this.chart = chart; this.options = options; // Keep track of the current series //this.currentSeries = UNDEFINED; // List of crosshairs this.crosshairs = []; // Current values of x and y when animating this.now = { x: 0, y: 0 }; // The tooltip is initially hidden this.isHidden = true; // create the label this.label = chart.renderer.label('', 0, 0, options.shape, null, null, options.useHTML, null, 'tooltip') .attr({ padding: padding, fill: options.backgroundColor, 'stroke-width': borderWidth, r: options.borderRadius, zIndex: 8 }) .css(style) .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117) .hide() .add(); // When using canVG the shadow shows up as a gray circle // even if the tooltip is hidden. if (!useCanVG) { this.label.shadow(options.shadow); } // Public property for getting the shared state. this.shared = options.shared; } Tooltip.prototype = { /** * Destroy the tooltip and its elements. */ destroy: function () { each(this.crosshairs, function (crosshair) { if (crosshair) { crosshair.destroy(); } }); // Destroy and clear local variables if (this.label) { this.label = this.label.destroy(); } }, /** * Provide a soft movement for the tooltip * * @param {Number} x * @param {Number} y * @private */ move: function (x, y, anchorX, anchorY) { var tooltip = this, now = tooltip.now, animate = tooltip.options.animation !== false && !tooltip.isHidden; // get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: animate ? (now.anchorY + anchorY) / 2 : anchorY }); // move to the intermediate value tooltip.label.attr(now); // run on next tick of the mouse tracker if (animate && (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1)) { // never allow two timeouts clearTimeout(this.tooltipTimeout); // set the fixed interval ticking for the smooth tooltip this.tooltipTimeout = setTimeout(function () { // The interval function may still be running during destroy, so check that the chart is really there before calling. if (tooltip) { tooltip.move(x, y, anchorX, anchorY); } }, 32); } }, /** * Hide the tooltip */ hide: function () { if (!this.isHidden) { var hoverPoints = this.chart.hoverPoints; this.label.hide(); // hide previous hoverPoints and set new if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } this.chart.hoverPoints = null; this.isHidden = true; } }, /** * Hide the crosshairs */ hideCrosshairs: function () { each(this.crosshairs, function (crosshair) { if (crosshair) { crosshair.hide(); } }); }, /** * Extendable method to get the anchor position of the tooltip * from a point or set of points */ getAnchor: function (points, mouseEvent) { var ret, chart = this.chart, inverted = chart.inverted, plotX = 0, plotY = 0, yAxis; points = splat(points); // Pie uses a special tooltipPos ret = points[0].tooltipPos; // When shared, use the average position if (!ret) { each(points, function (point) { yAxis = point.series.yAxis; plotX += point.plotX; plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) + (!inverted && yAxis ? yAxis.top - chart.plotTop : 0); // #1151 }); plotX /= points.length; plotY /= points.length; ret = [ inverted ? chart.plotWidth - plotY : plotX, this.shared && !inverted && points.length > 1 && mouseEvent ? mouseEvent.chartY - chart.plotTop : // place shared tooltip next to the mouse (#424) inverted ? chart.plotHeight - plotX : plotY ]; } return map(ret, mathRound); }, /** * Place the tooltip in a chart without spilling over * and not covering the point it self. */ getPosition: function (boxWidth, boxHeight, point) { // Set up the variables var chart = this.chart, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, distance = pick(this.options.distance, 12), pointX = point.plotX, pointY = point.plotY, x = pointX + plotLeft + (chart.inverted ? distance : -boxWidth - distance), y = pointY - boxHeight + plotTop + 15, // 15 means the point is 15 pixels up from the bottom of the tooltip alignedRight; // It is too far to the left, adjust it if (x < 7) { x = plotLeft + mathMax(pointX, 0) + distance; } // Test to see if the tooltip is too far to the right, // if it is, move it back to be inside and then up to not cover the point. if ((x + boxWidth) > (plotLeft + plotWidth)) { x -= (x + boxWidth) - (plotLeft + plotWidth); y = pointY - boxHeight + plotTop - distance; alignedRight = true; } // If it is now above the plot area, align it to the top of the plot area if (y < plotTop + 5) { y = plotTop + 5; // If the tooltip is still covering the point, move it below instead if (alignedRight && pointY >= y && pointY <= (y + boxHeight)) { y = pointY + plotTop + distance; // below } } // Now if the tooltip is below the chart, move it up. It's better to cover the // point than to disappear outside the chart. #834. if (y + boxHeight > plotTop + plotHeight) { y = mathMax(plotTop, plotTop + plotHeight - boxHeight - distance); // below } return {x: x, y: y}; }, /** * Refresh the tooltip's text and position. * @param {Object} point */ refresh: function (point, mouseEvent) { var tooltip = this, chart = tooltip.chart, label = tooltip.label, options = tooltip.options; /** * In case no user defined formatter is given, this will be used */ function defaultFormatter() { var pThis = this, items = pThis.points || splat(pThis), series = items[0].series, s; // build the header s = [series.tooltipHeaderFormatter(items[0].key)]; // build the values each(items, function (item) { series = item.series; s.push((series.tooltipFormatter && series.tooltipFormatter(item)) || item.point.tooltipFormatter(series.tooltipOptions.pointFormat)); }); // footer s.push(options.footerFormat || ''); return s.join(''); } var x, y, show, anchor, textConfig = {}, text, pointConfig = [], formatter = options.formatter || defaultFormatter, hoverPoints = chart.hoverPoints, placedTooltipPoint, borderColor, crosshairsOptions = options.crosshairs, shared = tooltip.shared, currentSeries; // get the reference point coordinates (pie charts use tooltipPos) anchor = tooltip.getAnchor(point, mouseEvent); x = anchor[0]; y = anchor[1]; // shared tooltip, array is sent over if (shared && !(point.series && point.series.noSharedTooltip)) { // hide previous hoverPoints and set new chart.hoverPoints = point; if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(point, function (item) { item.setState(HOVER_STATE); pointConfig.push(item.getLabelConfig()); }); textConfig = { x: point[0].category, y: point[0].y }; textConfig.points = pointConfig; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } text = formatter.call(textConfig); // register the current series currentSeries = point.series; // For line type series, hide tooltip if the point falls outside the plot show = shared || !currentSeries.isCartesian || currentSeries.tooltipOutsidePlot || chart.isInsidePlot(x, y); // update the inner HTML if (text === false || !show) { this.hide(); } else { // show it if (tooltip.isHidden) { label.show(); } // update text label.attr({ text: text }); // set the stroke color of the box borderColor = options.borderColor || point.color || currentSeries.color || '#606060'; label.attr({ stroke: borderColor }); placedTooltipPoint = (options.positioner || tooltip.getPosition).call( tooltip, label.width, label.height, { plotX: x, plotY: y } ); // do the move tooltip.move( mathRound(placedTooltipPoint.x), mathRound(placedTooltipPoint.y), x + chart.plotLeft, y + chart.plotTop ); tooltip.isHidden = false; } // crosshairs if (crosshairsOptions) { crosshairsOptions = splat(crosshairsOptions); // [x, y] var path, i = crosshairsOptions.length, attribs, axis; while (i--) { axis = point.series[i ? 'yAxis' : 'xAxis']; if (crosshairsOptions[i] && axis) { path = axis.getPlotLinePath( i ? pick(point.stackY, point.y) : point.x, // #814 1 ); if (tooltip.crosshairs[i]) { tooltip.crosshairs[i].attr({ d: path, visibility: VISIBLE }); } else { attribs = { 'stroke-width': crosshairsOptions[i].width || 1, stroke: crosshairsOptions[i].color || '#C0C0C0', zIndex: crosshairsOptions[i].zIndex || 2 }; if (crosshairsOptions[i].dashStyle) { attribs.dashstyle = crosshairsOptions[i].dashStyle; } tooltip.crosshairs[i] = chart.renderer.path(path) .attr(attribs) .add(); } } } } fireEvent(chart, 'tooltipRefresh', { text: text, x: x + chart.plotLeft, y: y + chart.plotTop, borderColor: borderColor }); } }; /** * The mouse tracker object * @param {Object} chart The Chart instance * @param {Object} options The root options object */ function MouseTracker(chart, options) { var zoomType = useCanVG ? '' : options.chart.zoomType; // Zoom status this.zoomX = /x/.test(zoomType); this.zoomY = /y/.test(zoomType); // Store reference to options this.options = options; // Reference to the chart this.chart = chart; // The interval id //this.tooltipTimeout = UNDEFINED; // The cached x hover position //this.hoverX = UNDEFINED; // The chart position //this.chartPosition = UNDEFINED; // The selection marker element //this.selectionMarker = UNDEFINED; // False or a value > 0 if a dragging operation //this.mouseDownX = UNDEFINED; //this.mouseDownY = UNDEFINED; this.init(chart, options.tooltip); } MouseTracker.prototype = { /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ normalizeMouseEvent: function (e) { var chartPosition, chartX, chartY, ePos; // common IE normalizing e = e || win.event; if (!e.target) { e.target = e.srcElement; } // Framework specific normalizing (#1165) e = washMouseEvent(e); // iOS ePos = e.touches ? e.touches.item(0) : e; // get mouse position this.chartPosition = chartPosition = offset(this.chart.container); // chartX and chartY if (ePos.pageX === UNDEFINED) { // IE < 9. #886. chartX = e.x; chartY = e.y; } else { chartX = ePos.pageX - chartPosition.left; chartY = ePos.pageY - chartPosition.top; } return extend(e, { chartX: mathRound(chartX), chartY: mathRound(chartY) }); }, /** * Get the click position in terms of axis values. * * @param {Object} e A mouse event */ getMouseCoordinates: function (e) { var coordinates = { xAxis: [], yAxis: [] }, chart = this.chart; each(chart.axes, function (axis) { var isXAxis = axis.isXAxis, isHorizontal = chart.inverted ? !isXAxis : isXAxis; coordinates[isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.translate( (isHorizontal ? e.chartX - chart.plotLeft : axis.top + axis.len - e.chartY) - axis.minPixelPadding, // #1051 true ) }); }); return coordinates; }, /** * Return the index in the tooltipPoints array, corresponding to pixel position in * the plot area. */ getIndex: function (e) { var chart = this.chart; return chart.inverted ? chart.plotHeight + chart.plotTop - e.chartY : e.chartX - chart.plotLeft; }, /** * With line type charts with a single tracker, get the point closest to the mouse */ onmousemove: function (e) { var mouseTracker = this, chart = mouseTracker.chart, series = chart.series, tooltip = chart.tooltip, point, points, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, j, distance = chart.chartWidth, index = mouseTracker.getIndex(e); // shared tooltip if (tooltip && mouseTracker.options.tooltip.shared && !(hoverSeries && hoverSeries.noSharedTooltip)) { points = []; // loop over all series and find the ones with points closest to the mouse i = series.length; for (j = 0; j < i; j++) { if (series[j].visible && series[j].options.enableMouseTracking !== false && !series[j].noSharedTooltip && series[j].tooltipPoints && series[j].tooltipPoints.length) { point = series[j].tooltipPoints[index]; point._dist = mathAbs(index - point[series[j].xAxis.tooltipPosName || 'plotX']); distance = mathMin(distance, point._dist); points.push(point); } } // remove furthest points i = points.length; while (i--) { if (points[i]._dist > distance) { points.splice(i, 1); } } // refresh the tooltip if necessary if (points.length && (points[0].plotX !== mouseTracker.hoverX)) { tooltip.refresh(points, e); mouseTracker.hoverX = points[0].plotX; } } // separate tooltip and general mouse events if (hoverSeries && hoverSeries.tracker) { // only use for line-type series with common tracker // get the point point = hoverSeries.tooltipPoints[index]; // a new point is hovered, refresh the tooltip if (point && point !== hoverPoint) { // trigger the events point.onMouseOver(); } } }, /** * Reset the tracking by hiding the tooltip, the hover series state and the hover point * * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible */ resetTracker: function (allowMove) { var mouseTracker = this, chart = mouseTracker.chart, hoverSeries = chart.hoverSeries, hoverPoint = chart.hoverPoint, tooltip = chart.tooltip, tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint; // Narrow in allowMove allowMove = allowMove && tooltip && tooltipPoints; // Check if the points have moved outside the plot area, #1003 if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) { allowMove = false; } // Just move the tooltip, #349 if (allowMove) { tooltip.refresh(tooltipPoints); // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(); tooltip.hideCrosshairs(); } mouseTracker.hoverX = null; } }, /** * Set the JS events on the container element */ setDOMEvents: function () { var lastWasOutsidePlot = true, mouseTracker = this, chart = mouseTracker.chart, container = chart.container, hasDragged, zoomHor = (mouseTracker.zoomX && !chart.inverted) || (mouseTracker.zoomY && chart.inverted), zoomVert = (mouseTracker.zoomY && !chart.inverted) || (mouseTracker.zoomX && chart.inverted); /** * Mouse up or outside the plot area */ function drop() { if (mouseTracker.selectionMarker) { var selectionData = { xAxis: [], yAxis: [] }, selectionBox = mouseTracker.selectionMarker.getBBox(), selectionLeft = selectionBox.x - chart.plotLeft, selectionTop = selectionBox.y - chart.plotTop, runZoom; // a selection has been made if (hasDragged) { // record each axis' min and max each(chart.axes, function (axis) { if (axis.options.zoomEnabled !== false) { var isXAxis = axis.isXAxis, isHorizontal = chart.inverted ? !isXAxis : isXAxis, selectionMin = axis.translate( isHorizontal ? selectionLeft : chart.plotHeight - selectionTop - selectionBox.height, true, 0, 0, 1 ), selectionMax = axis.translate( (isHorizontal ? selectionLeft + selectionBox.width : chart.plotHeight - selectionTop) - 2 * axis.minPixelPadding, // #875 true, 0, 0, 1 ); if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859 selectionData[isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, min: mathMin(selectionMin, selectionMax), // for reversed axes, max: mathMax(selectionMin, selectionMax) }); runZoom = true; } } }); if (runZoom) { fireEvent(chart, 'selection', selectionData, function (args) { chart.zoom(args); }); } } mouseTracker.selectionMarker = mouseTracker.selectionMarker.destroy(); } if (chart) { // it may be destroyed on mouse up - #877 css(container, { cursor: 'auto' }); chart.cancelClick = hasDragged; // #370 chart.mouseIsDown = hasDragged = false; } removeEvent(doc, 'mouseup', drop); if (hasTouch) { removeEvent(doc, 'touchend', drop); } } /** * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea. */ mouseTracker.hideTooltipOnMouseMove = function (e) { // Get e.pageX and e.pageY back in MooTools e = washMouseEvent(e); // If we're outside, hide the tooltip if (mouseTracker.chartPosition && chart.hoverSeries && chart.hoverSeries.isCartesian && !chart.isInsidePlot(e.pageX - mouseTracker.chartPosition.left - chart.plotLeft, e.pageY - mouseTracker.chartPosition.top - chart.plotTop)) { mouseTracker.resetTracker(); } }; /** * When mouse leaves the container, hide the tooltip. */ mouseTracker.hideTooltipOnMouseLeave = function () { mouseTracker.resetTracker(); mouseTracker.chartPosition = null; // also reset the chart position, used in #149 fix }; /* * Record the starting position of a dragoperation */ container.onmousedown = function (e) { e = mouseTracker.normalizeMouseEvent(e); // issue #295, dragging not always working in Firefox if (e.type.indexOf('touch') === -1 && e.preventDefault) { e.preventDefault(); } // record the start position chart.mouseIsDown = true; chart.cancelClick = false; chart.mouseDownX = mouseTracker.mouseDownX = e.chartX; mouseTracker.mouseDownY = e.chartY; addEvent(doc, 'mouseup', drop); if (hasTouch) { addEvent(doc, 'touchend', drop); } }; // The mousemove, touchmove and touchstart event handler var mouseMove = function (e) { // let the system handle multitouch operations like two finger scroll // and pinching if (e && e.touches && e.touches.length > 1) { return; } // normalize e = mouseTracker.normalizeMouseEvent(e); var type = e.type, chartX = e.chartX, chartY = e.chartY, isOutsidePlot = !chart.isInsidePlot(chartX - chart.plotLeft, chartY - chart.plotTop); if (type.indexOf('touch') === -1) { // not for touch actions e.returnValue = false; } // on touch devices, only trigger click if a handler is defined if (type === 'touchstart') { if (attr(e.target, 'isTracker')) { if (!chart.runTrackerClick) { e.preventDefault(); } } else if (!chart.runChartClick && !isOutsidePlot) { e.preventDefault(); } } // cancel on mouse outside if (isOutsidePlot) { /*if (!lastWasOutsidePlot) { // reset the tracker resetTracker(); }*/ // drop the selection if any and reset mouseIsDown and hasDragged //drop(); if (chartX < chart.plotLeft) { chartX = chart.plotLeft; } else if (chartX > chart.plotLeft + chart.plotWidth) { chartX = chart.plotLeft + chart.plotWidth; } if (chartY < chart.plotTop) { chartY = chart.plotTop; } else if (chartY > chart.plotTop + chart.plotHeight) { chartY = chart.plotTop + chart.plotHeight; } } if (chart.mouseIsDown && type !== 'touchstart') { // make selection // determine if the mouse has moved more than 10px hasDragged = Math.sqrt( Math.pow(mouseTracker.mouseDownX - chartX, 2) + Math.pow(mouseTracker.mouseDownY - chartY, 2) ); if (hasDragged > 10) { var clickedInside = chart.isInsidePlot(mouseTracker.mouseDownX - chart.plotLeft, mouseTracker.mouseDownY - chart.plotTop); // make a selection if (chart.hasCartesianSeries && (mouseTracker.zoomX || mouseTracker.zoomY) && clickedInside) { if (!mouseTracker.selectionMarker) { mouseTracker.selectionMarker = chart.renderer.rect( chart.plotLeft, chart.plotTop, zoomHor ? 1 : chart.plotWidth, zoomVert ? 1 : chart.plotHeight, 0 ) .attr({ fill: mouseTracker.options.chart.selectionMarkerFill || 'rgba(69,114,167,0.25)', zIndex: 7 }) .add(); } } // adjust the width of the selection marker if (mouseTracker.selectionMarker && zoomHor) { var xSize = chartX - mouseTracker.mouseDownX; mouseTracker.selectionMarker.attr({ width: mathAbs(xSize), x: (xSize > 0 ? 0 : xSize) + mouseTracker.mouseDownX }); } // adjust the height of the selection marker if (mouseTracker.selectionMarker && zoomVert) { var ySize = chartY - mouseTracker.mouseDownY; mouseTracker.selectionMarker.attr({ height: mathAbs(ySize), y: (ySize > 0 ? 0 : ySize) + mouseTracker.mouseDownY }); } // panning if (clickedInside && !mouseTracker.selectionMarker && mouseTracker.options.chart.panning) { chart.pan(chartX); } } } // Show the tooltip and run mouse over events (#977) if (!isOutsidePlot) { mouseTracker.onmousemove(e); } lastWasOutsidePlot = isOutsidePlot; // when outside plot, allow touch-drag by returning true return isOutsidePlot || !chart.hasCartesianSeries; }; // When the mouse enters the container, run mouseMove if (!/Android 4\.0/.test(userAgent)) { // This hurts. Best effort for #1385. container.onmousemove = mouseMove; } /* * When the mouse leaves the container, hide the tracking (tooltip). */ addEvent(container, 'mouseleave', mouseTracker.hideTooltipOnMouseLeave); // issue #149 workaround // The mouseleave event above does not always fire. Whenever the mouse is moving // outside the plotarea, hide the tooltip if (!hasTouch) { // #1385 addEvent(doc, 'mousemove', mouseTracker.hideTooltipOnMouseMove); } container.ontouchstart = function (e) { // For touch devices, use touchmove to zoom if (mouseTracker.zoomX || mouseTracker.zoomY) { container.onmousedown(e); } // Show tooltip and prevent the lower mouse pseudo event mouseMove(e); }; /* * Allow dragging the finger over the chart to read the values on touch * devices */ container.ontouchmove = mouseMove; /* * Allow dragging the finger over the chart to read the values on touch * devices */ container.ontouchend = function () { if (hasDragged) { mouseTracker.resetTracker(); } }; // MooTools 1.2.3 doesn't fire this in IE when using addEvent container.onclick = function (e) { var hoverPoint = chart.hoverPoint, plotX, plotY; e = mouseTracker.normalizeMouseEvent(e); e.cancelBubble = true; // IE specific if (!chart.cancelClick) { // Detect clicks on trackers or tracker groups, #783 if (hoverPoint && (attr(e.target, 'isTracker') || attr(e.target.parentNode, 'isTracker'))) { plotX = hoverPoint.plotX; plotY = hoverPoint.plotY; // add page position info extend(hoverPoint, { pageX: mouseTracker.chartPosition.left + chart.plotLeft + (chart.inverted ? chart.plotWidth - plotY : plotX), pageY: mouseTracker.chartPosition.top + chart.plotTop + (chart.inverted ? chart.plotHeight - plotX : plotY) }); // the series click event fireEvent(hoverPoint.series, 'click', extend(e, { point: hoverPoint })); // the point click event hoverPoint.firePointEvent('click', e); } else { extend(e, mouseTracker.getMouseCoordinates(e)); // fire a click event in the chart if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { fireEvent(chart, 'click', e); } } } }; }, /** * Destroys the MouseTracker object and disconnects DOM events. */ destroy: function () { var mouseTracker = this, chart = mouseTracker.chart, container = chart.container; // Destroy the tracker group element if (chart.trackerGroup) { chart.trackerGroup = chart.trackerGroup.destroy(); } removeEvent(container, 'mouseleave', mouseTracker.hideTooltipOnMouseLeave); removeEvent(doc, 'mousemove', mouseTracker.hideTooltipOnMouseMove); container.onclick = container.onmousedown = container.onmousemove = container.ontouchstart = container.ontouchend = container.ontouchmove = null; // memory and CPU leak clearInterval(this.tooltipTimeout); }, // Run MouseTracker init: function (chart, options) { if (!chart.trackerGroup) { chart.trackerGroup = chart.renderer.g('tracker') .attr({ zIndex: 9 }) .add(); } if (options.enabled) { chart.tooltip = new Tooltip(chart, options); } this.setDOMEvents(); } }; /** * The overview of the chart's series */ function Legend(chart) { this.init(chart); } Legend.prototype = { /** * Initialize the legend */ init: function (chart) { var legend = this, options = legend.options = chart.options.legend; if (!options.enabled) { return; } var //style = options.style || {}, // deprecated itemStyle = options.itemStyle, padding = pick(options.padding, 8), itemMarginTop = options.itemMarginTop || 0; legend.baseline = pInt(itemStyle.fontSize) + 3 + itemMarginTop; // used in Series prototype legend.itemStyle = itemStyle; legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle); legend.itemMarginTop = itemMarginTop; legend.padding = padding; legend.initialItemX = padding; legend.initialItemY = padding - 5; // 5 is the number of pixels above the text legend.maxItemWidth = 0; legend.chart = chart; //legend.allItems = UNDEFINED; //legend.legendWidth = UNDEFINED; //legend.legendHeight = UNDEFINED; //legend.offsetWidth = UNDEFINED; legend.itemHeight = 0; legend.lastLineHeight = 0; //legend.itemX = UNDEFINED; //legend.itemY = UNDEFINED; //legend.lastItemY = UNDEFINED; // Elements //legend.group = UNDEFINED; //legend.box = UNDEFINED; // run legend legend.render(); // move checkboxes addEvent(legend.chart, 'endResize', function () { legend.positionCheckboxes(); }); /* // expose return { colorizeItem: colorizeItem, destroyItem: destroyItem, render: render, destroy: destroy, getLegendWidth: getLegendWidth, getLegendHeight: getLegendHeight };*/ }, /** * Set the colors for the legend item * @param {Object} item A Series or Point instance * @param {Object} visible Dimmed or colored */ colorizeItem: function (item, visible) { var legend = this, options = legend.options, legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, hiddenColor = legend.itemHiddenStyle.color, textColor = visible ? options.itemStyle.color : hiddenColor, symbolColor = visible ? item.color : hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { stroke: symbolColor, fill: symbolColor }, key, val; if (legendItem) { legendItem.css({ fill: textColor }); } if (legendLine) { legendLine.attr({ stroke: symbolColor }); } if (legendSymbol) { // Apply marker options if (markerOptions) { markerOptions = item.convertAttribs(markerOptions); for (key in markerOptions) { val = markerOptions[key]; if (val !== UNDEFINED) { symbolAttr[key] = val; } } } legendSymbol.attr(symbolAttr); } }, /** * Position the legend item * @param {Object} item A Series or Point instance */ positionItem: function (item) { var legend = this, options = legend.options, symbolPadding = options.symbolPadding, ltr = !options.rtl, legendItemPos = item._legendItemPos, itemX = legendItemPos[0], itemY = legendItemPos[1], checkbox = item.checkbox; if (item.legendGroup) { item.legendGroup.translate( ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4, itemY ); } if (checkbox) { checkbox.x = itemX; checkbox.y = itemY; } }, /** * Destroy a single legend item * @param {Object} item The series or point */ destroyItem: function (item) { var checkbox = item.checkbox; // destroy SVG elements each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) { if (item[key]) { item[key].destroy(); } }); if (checkbox) { discardElement(item.checkbox); } }, /** * Destroys the legend. */ destroy: function () { var legend = this, legendGroup = legend.group, box = legend.box; if (box) { legend.box = box.destroy(); } if (legendGroup) { legend.group = legendGroup.destroy(); } }, /** * Position the checkboxes after the width is determined */ positionCheckboxes: function (scrollOffset) { var alignAttr = this.group.alignAttr, translateY, clipHeight = this.clipHeight || this.legendHeight; if (alignAttr) { translateY = alignAttr.translateY; each(this.allItems, function (item) { var checkbox = item.checkbox, top; if (checkbox) { top = (translateY + checkbox.y + (scrollOffset || 0) + 3); css(checkbox, { left: (alignAttr.translateX + item.legendItemWidth + checkbox.x - 20) + PX, top: top + PX, display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE }); } }); } }, /** * Render a single specific legend item * @param {Object} item A series or point */ renderItem: function (item) { var legend = this, chart = legend.chart, renderer = chart.renderer, options = legend.options, horizontal = options.layout === 'horizontal', symbolWidth = options.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, padding = legend.padding, ltr = !options.rtl, itemHeight, widthOption = options.width, itemMarginBottom = options.itemMarginBottom || 0, itemMarginTop = legend.itemMarginTop, initialItemX = legend.initialItemX, bBox, itemWidth, li = item.legendItem, series = item.series || item, itemOptions = series.options, showCheckbox = itemOptions.showCheckbox, useHTML = options.useHTML; if (!li) { // generate it once, later move it // Generate the group box // A group to hold the symbol and text. Text is to be appended in Legend class. item.legendGroup = renderer.g('legend-item') .attr({ zIndex: 1 }) .add(legend.scrollGroup); // Draw the legend symbol inside the group box series.drawLegendSymbol(legend, item); // Generate the list item text and add it to the group item.legendItem = li = renderer.text( options.labelFormatter.call(item), ltr ? symbolWidth + symbolPadding : -symbolPadding, legend.baseline, useHTML ) .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021) .attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); // Set the events on the item group, or in case of useHTML, the item itself (#1249) (useHTML ? li : item.legendGroup).on('mouseover', function () { item.setState(HOVER_STATE); li.css(legend.options.itemHoverStyle); }) .on('mouseout', function () { li.css(item.visible ? itemStyle : itemHiddenStyle); item.setState(); }) .on('click', function (event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function () { item.setVisible(); }; // Pass over the click/touch event. #4. event = { browserEvent: event }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, event, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, event, fnLegendItemClick); } }); // Colorize the items legend.colorizeItem(item, item.visible); // add the HTML checkbox on top if (itemOptions && showCheckbox) { item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, options.itemCheckboxStyle, chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent(item, 'checkboxClick', { checked: target.checked }, function () { item.select(); } ); }); } } // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.legendItemWidth = options.itemWidth || symbolWidth + symbolPadding + bBox.width + padding + (showCheckbox ? 20 : 0); legend.itemHeight = itemHeight = bBox.height; // if the item exceeds the width, start a new line if (horizontal && legend.itemX - initialItemX + itemWidth > (widthOption || (chart.chartWidth - 2 * padding - initialItemX))) { legend.itemX = initialItemX; legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom; legend.lastLineHeight = 0; // reset for next line } // If the item exceeds the height, start a new column /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) { legend.itemY = legend.initialItemY; legend.itemX += legend.maxItemWidth; legend.maxItemWidth = 0; }*/ // Set the edge positions legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth); legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom; legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915 // cache the position of the newly generated or reordered items item._legendItemPos = [legend.itemX, legend.itemY]; // advance if (horizontal) { legend.itemX += itemWidth; } else { legend.itemY += itemMarginTop + itemHeight + itemMarginBottom; legend.lastLineHeight = itemHeight; } // the width of the widest item legend.offsetWidth = widthOption || mathMax( horizontal ? legend.itemX - initialItemX : itemWidth, legend.offsetWidth ); }, /** * Render the legend. This method can be called both before and after * chart.render. If called after, it will only rearrange items instead * of creating new ones. */ render: function () { var legend = this, chart = legend.chart, renderer = chart.renderer, legendGroup = legend.group, allItems, display, legendWidth, legendHeight, box = legend.box, options = legend.options, padding = legend.padding, legendBorderWidth = options.borderWidth, legendBackgroundColor = options.backgroundColor; legend.itemX = legend.initialItemX; legend.itemY = legend.initialItemY; legend.offsetWidth = 0; legend.lastItemY = 0; if (!legendGroup) { legend.group = legendGroup = renderer.g('legend') // #414, #759. Trackers will be drawn above the legend, but we have // to sacrifice that because tooltips need to be above the legend // and trackers above tooltips .attr({ zIndex: 7 }) .add(); legend.contentGroup = renderer.g() .attr({ zIndex: 1 }) // above background .add(legendGroup); legend.scrollGroup = renderer.g() .add(legend.contentGroup); legend.clipRect = renderer.clipRect(0, 0, 9999, chart.chartHeight); legend.contentGroup.clip(legend.clipRect); } // add each series or point allItems = []; each(chart.series, function (serie) { var seriesOptions = serie.options; if (!seriesOptions.showInLegend) { return; } // use points or series for the legend item depending on legendType allItems = allItems.concat( serie.legendItems || (seriesOptions.legendType === 'point' ? serie.data : serie) ); }); // sort by legendIndex stableSort(allItems, function (a, b) { return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0); }); // reversed legend if (options.reversed) { allItems.reverse(); } legend.allItems = allItems; legend.display = display = !!allItems.length; // render the items each(allItems, function (item) { legend.renderItem(item); }); // Draw the border legendWidth = options.width || legend.offsetWidth; legendHeight = legend.lastItemY + legend.lastLineHeight; legendHeight = legend.handleOverflow(legendHeight); if (legendBorderWidth || legendBackgroundColor) { legendWidth += padding; legendHeight += padding; if (!box) { legend.box = box = renderer.rect( 0, 0, legendWidth, legendHeight, options.borderRadius, legendBorderWidth || 0 ).attr({ stroke: options.borderColor, 'stroke-width': legendBorderWidth || 0, fill: legendBackgroundColor || NONE }) .add(legendGroup) .shadow(options.shadow); box.isNew = true; } else if (legendWidth > 0 && legendHeight > 0) { box[box.isNew ? 'attr' : 'animate']( box.crisp(null, null, null, legendWidth, legendHeight) ); box.isNew = false; } // hide the border if no items box[display ? 'show' : 'hide'](); } legend.legendWidth = legendWidth; legend.legendHeight = legendHeight; // Now that the legend width and height are established, put the items in the // final position each(allItems, function (item) { legend.positionItem(item); }); // 1.x compatibility: positioning based on style /*var props = ['left', 'right', 'top', 'bottom'], prop, i = 4; while (i--) { prop = props[i]; if (options.style[prop] && options.style[prop] !== 'auto') { options[i < 2 ? 'align' : 'verticalAlign'] = prop; options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1); } }*/ if (display) { legendGroup.align(extend({ width: legendWidth, height: legendHeight }, options), true, chart.spacingBox); } if (!chart.isResizing) { this.positionCheckboxes(); } }, /** * Set up the overflow handling by adding navigation with up and down arrows below the * legend. */ handleOverflow: function (legendHeight) { var legend = this, chart = this.chart, renderer = chart.renderer, pageCount, options = this.options, optionsY = options.y, alignTop = options.verticalAlign === 'top', spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding, maxHeight = options.maxHeight, clipHeight, clipRect = this.clipRect, navOptions = options.navigation, animation = pick(navOptions.animation, true), arrowSize = navOptions.arrowSize || 12, nav = this.nav; // Adjust the height if (options.layout === 'horizontal') { spaceHeight /= 2; } if (maxHeight) { spaceHeight = mathMin(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle if (legendHeight > spaceHeight) { this.clipHeight = clipHeight = spaceHeight - 20; this.pageCount = pageCount = mathCeil(legendHeight / clipHeight); this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; clipRect.attr({ height: clipHeight }); // Add navigation elements if (!nav) { this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group); this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(-1, animation); }) .add(nav); this.pager = renderer.text('', 15, 10) .css(navOptions.style) .add(nav); this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(1, animation); }) .add(nav); } // Set initial position legend.scroll(0); legendHeight = spaceHeight; } else if (nav) { clipRect.attr({ height: chart.chartHeight }); nav.hide(); this.scrollGroup.attr({ translateY: 1 }); this.clipHeight = 0; // #1379 } return legendHeight; }, /** * Scroll the legend by a number of pages * @param {Object} scrollBy * @param {Object} animation */ scroll: function (scrollBy, animation) { var pageCount = this.pageCount, currentPage = this.currentPage + scrollBy, clipHeight = this.clipHeight, navOptions = this.options.navigation, activeColor = navOptions.activeColor, inactiveColor = navOptions.inactiveColor, pager = this.pager, padding = this.padding, scrollOffset; // When resizing while looking at the last page if (currentPage > pageCount) { currentPage = pageCount; } if (currentPage > 0) { if (animation !== UNDEFINED) { setAnimation(animation, this.chart); } this.nav.attr({ translateX: padding, translateY: clipHeight + 7, visibility: VISIBLE }); this.up.attr({ fill: currentPage === 1 ? inactiveColor : activeColor }) .css({ cursor: currentPage === 1 ? 'default' : 'pointer' }); pager.attr({ text: currentPage + '/' + this.pageCount }); this.down.attr({ x: 18 + this.pager.getBBox().width, // adjust to text width fill: currentPage === pageCount ? inactiveColor : activeColor }) .css({ cursor: currentPage === pageCount ? 'default' : 'pointer' }); scrollOffset = -mathMin(clipHeight * (currentPage - 1), this.fullHeight - clipHeight + padding) + 1; this.scrollGroup.animate({ translateY: scrollOffset }); pager.attr({ text: currentPage + '/' + pageCount }); this.currentPage = currentPage; this.positionCheckboxes(scrollOffset); } } }; /** * The chart class * @param {Object} options * @param {Function} callback Function to run when the chart has loaded */ function Chart() { this.init.apply(this, arguments); } Chart.prototype = { /** * Initialize the chart */ init: function (userOptions, callback) { // Handle regular options var options, seriesOptions = userOptions.series; // skip merging data points to increase performance userOptions.series = null; options = merge(defaultOptions, userOptions); // do the merge options.series = userOptions.series = seriesOptions; // set back the series data var optionsChart = options.chart, optionsMargin = optionsChart.margin, margin = isObject(optionsMargin) ? optionsMargin : [optionsMargin, optionsMargin, optionsMargin, optionsMargin]; this.optionsMarginTop = pick(optionsChart.marginTop, margin[0]); this.optionsMarginRight = pick(optionsChart.marginRight, margin[1]); this.optionsMarginBottom = pick(optionsChart.marginBottom, margin[2]); this.optionsMarginLeft = pick(optionsChart.marginLeft, margin[3]); var chartEvents = optionsChart.events; this.runChartClick = chartEvents && !!chartEvents.click; this.callback = callback; this.isResizing = 0; this.options = options; //chartTitleOptions = UNDEFINED; //chartSubtitleOptions = UNDEFINED; this.axes = []; this.series = []; this.hasCartesianSeries = optionsChart.showAxes; //this.axisOffset = UNDEFINED; //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes //this.inverted = UNDEFINED; //this.loadingShown = UNDEFINED; //this.container = UNDEFINED; //this.chartWidth = UNDEFINED; //this.chartHeight = UNDEFINED; //this.marginRight = UNDEFINED; //this.marginBottom = UNDEFINED; //this.containerWidth = UNDEFINED; //this.containerHeight = UNDEFINED; //this.oldChartWidth = UNDEFINED; //this.oldChartHeight = UNDEFINED; //this.renderTo = UNDEFINED; //this.renderToClone = UNDEFINED; //this.tracker = UNDEFINED; //this.spacingBox = UNDEFINED //this.legend = UNDEFINED; // Elements //this.chartBackground = UNDEFINED; //this.plotBackground = UNDEFINED; //this.plotBGImage = UNDEFINED; //this.plotBorder = UNDEFINED; //this.loadingDiv = UNDEFINED; //this.loadingSpan = UNDEFINED; var chart = this, eventType; // Add the chart to the global lookup chart.index = charts.length; charts.push(chart); // Set up auto resize if (optionsChart.reflow !== false) { addEvent(chart, 'load', chart.initReflow); } // Chart event handlers if (chartEvents) { for (eventType in chartEvents) { addEvent(chart, eventType, chartEvents[eventType]); } } chart.xAxis = []; chart.yAxis = []; // Expose methods and variables chart.animation = useCanVG ? false : pick(optionsChart.animation, true); chart.pointCount = 0; chart.counters = new ChartCounters(); chart.firstRender(); }, /** * Initialize an individual series, called internally before render time */ initSeries: function (options) { var chart = this, optionsChart = chart.options.chart, type = options.type || optionsChart.type || optionsChart.defaultSeriesType, series = new seriesTypes[type](); series.init(this, options); return series; }, /** * Add a series dynamically after time * * @param {Object} options The config options * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * * @return {Object} series The newly created series object */ addSeries: function (options, redraw, animation) { var series, chart = this; if (options) { setAnimation(animation, chart); redraw = pick(redraw, true); // defaults to true fireEvent(chart, 'addSeries', { options: options }, function () { series = chart.initSeries(options); chart.isDirtyLegend = true; // the series array is out of sync with the display if (redraw) { chart.redraw(); } }); } return series; }, /** * Check whether a given point is within the plot area * * @param {Number} plotX Pixel x relative to the plot area * @param {Number} plotY Pixel y relative to the plot area * @param {Boolean} inverted Whether the chart is inverted */ isInsidePlot: function (plotX, plotY, inverted) { var x = inverted ? plotY : plotX, y = inverted ? plotX : plotY; return x >= 0 && x <= this.plotWidth && y >= 0 && y <= this.plotHeight; }, /** * Adjust all axes tick amounts */ adjustTickAmounts: function () { if (this.options.chart.alignTicks !== false) { each(this.axes, function (axis) { axis.adjustTickAmount(); }); } this.maxTicks = null; }, /** * Redraw legend, axes or series based on updated data * * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ redraw: function (animation) { var chart = this, axes = chart.axes, series = chart.series, tracker = chart.tracker, legend = chart.legend, redrawLegend = chart.isDirtyLegend, hasStackedSeries, isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed? seriesLength = series.length, i = seriesLength, serie, renderer = chart.renderer, isHiddenChart = renderer.isHidden(), afterRedraw = []; setAnimation(animation, chart); if (isHiddenChart) { chart.cloneRenderTo(); } // link stacked series while (i--) { serie = series[i]; if (serie.isDirty && serie.options.stacking) { hasStackedSeries = true; break; } } if (hasStackedSeries) { // mark others as dirty i = seriesLength; while (i--) { serie = series[i]; if (serie.options.stacking) { serie.isDirty = true; } } } // handle updated data in the series each(series, function (serie) { if (serie.isDirty) { // prepare the data so axis can read it if (serie.options.legendType === 'point') { redrawLegend = true; } } }); // handle added or removed series if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed // draw legend graphics legend.render(); chart.isDirtyLegend = false; } if (chart.hasCartesianSeries) { if (!chart.isResizing) { // reset maxTicks chart.maxTicks = null; // set axes scales each(axes, function (axis) { axis.setScale(); }); } chart.adjustTickAmounts(); chart.getMargins(); // redraw axes each(axes, function (axis) { // Fire 'afterSetExtremes' only if extremes are set if (axis.isDirtyExtremes) { // #821 axis.isDirtyExtremes = false; afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119) fireEvent(axis, 'afterSetExtremes', axis.getExtremes()); // #747, #751 }); } if (axis.isDirty || isDirtyBox || hasStackedSeries) { axis.redraw(); isDirtyBox = true; // #792 } }); } // the plot areas size has changed if (isDirtyBox) { chart.drawChartBox(); } // redraw affected series each(series, function (serie) { if (serie.isDirty && serie.visible && (!serie.isCartesian || serie.xAxis)) { // issue #153 serie.redraw(); } }); // move tooltip or reset if (tracker && tracker.resetTracker) { tracker.resetTracker(true); } // redraw if canvas renderer.draw(); // fire the event fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw if (isHiddenChart) { chart.cloneRenderTo(true); } // Fire callbacks that are put on hold until after the redraw each(afterRedraw, function (callback) { callback.call(); }); }, /** * Dim the chart and show a loading text or symbol * @param {String} str An optional text to show in the loading label instead of the default one */ showLoading: function (str) { var chart = this, options = chart.options, loadingDiv = chart.loadingDiv; var loadingOptions = options.loading; // create the layer at the first call if (!loadingDiv) { chart.loadingDiv = loadingDiv = createElement(DIV, { className: PREFIX + 'loading' }, extend(loadingOptions.style, { left: chart.plotLeft + PX, top: chart.plotTop + PX, width: chart.plotWidth + PX, height: chart.plotHeight + PX, zIndex: 10, display: NONE }), chart.container); chart.loadingSpan = createElement( 'span', null, loadingOptions.labelStyle, loadingDiv ); } // update text chart.loadingSpan.innerHTML = str || options.lang.loading; // show it if (!chart.loadingShown) { css(loadingDiv, { opacity: 0, display: '' }); animate(loadingDiv, { opacity: loadingOptions.style.opacity }, { duration: loadingOptions.showDuration || 0 }); chart.loadingShown = true; } }, /** * Hide the loading layer */ hideLoading: function () { var options = this.options, loadingDiv = this.loadingDiv; if (loadingDiv) { animate(loadingDiv, { opacity: 0 }, { duration: options.loading.hideDuration || 100, complete: function () { css(loadingDiv, { display: NONE }); } }); } this.loadingShown = false; }, /** * Get an axis, series or point object by id. * @param id {String} The id as given in the configuration options */ get: function (id) { var chart = this, axes = chart.axes, series = chart.series; var i, j, points; // search axes for (i = 0; i < axes.length; i++) { if (axes[i].options.id === id) { return axes[i]; } } // search series for (i = 0; i < series.length; i++) { if (series[i].options.id === id) { return series[i]; } } // search points for (i = 0; i < series.length; i++) { points = series[i].points || []; for (j = 0; j < points.length; j++) { if (points[j].id === id) { return points[j]; } } } return null; }, /** * Create the Axis instances based on the config options */ getAxes: function () { var chart = this, options = this.options; var xAxisOptions = options.xAxis || {}, yAxisOptions = options.yAxis || {}, optionsArray, axis; // make sure the options are arrays and add some members xAxisOptions = splat(xAxisOptions); each(xAxisOptions, function (axis, i) { axis.index = i; axis.isX = true; }); yAxisOptions = splat(yAxisOptions); each(yAxisOptions, function (axis, i) { axis.index = i; }); // concatenate all axis options into one array optionsArray = xAxisOptions.concat(yAxisOptions); each(optionsArray, function (axisOptions) { axis = new Axis(chart, axisOptions); }); chart.adjustTickAmounts(); }, /** * Get the currently selected points from all series */ getSelectedPoints: function () { var points = []; each(this.series, function (serie) { points = points.concat(grep(serie.points, function (point) { return point.selected; })); }); return points; }, /** * Get the currently selected series */ getSelectedSeries: function () { return grep(this.series, function (serie) { return serie.selected; }); }, /** * Display the zoom button */ showResetZoom: function () { var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox'; this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover) .attr({ align: btnOptions.position.align, title: lang.resetZoomTitle }) .add() .align(btnOptions.position, false, chart[alignTo]); this.resetZoomButton.alignTo = alignTo; }, /** * Zoom out to 1:1 */ zoomOut: function () { var chart = this, resetZoomButton = chart.resetZoomButton; fireEvent(chart, 'selection', { resetSelection: true }, function () { chart.zoom(); }); if (resetZoomButton) { chart.resetZoomButton = resetZoomButton.destroy(); } }, /** * Zoom into a given portion of the chart given by axis coordinates * @param {Object} event */ zoom: function (event) { var chart = this, hasZoomed; // if zoom is called with no arguments, reset the axes if (!event || event.resetSelection) { each(chart.axes, function (axis) { hasZoomed = axis.zoom(); }); } else { // else, zoom in on all axes each(event.xAxis.concat(event.yAxis), function (axisData) { var axis = axisData.axis; // don't zoom more than minRange if (chart.tracker[axis.isXAxis ? 'zoomX' : 'zoomY']) { hasZoomed = axis.zoom(axisData.min, axisData.max); } }); } // Show the Reset zoom button if (!chart.resetZoomButton) { chart.showResetZoom(); } // Redraw if (hasZoomed) { chart.redraw( pick(chart.options.chart.animation, chart.pointCount < 100) // animation ); } }, /** * Pan the chart by dragging the mouse across the pane. This function is called * on mouse move, and the distance to pan is computed from chartX compared to * the first chartX position in the dragging operation. */ pan: function (chartX) { var chart = this; var xAxis = chart.xAxis[0], mouseDownX = chart.mouseDownX, halfPointRange = xAxis.pointRange / 2, extremes = xAxis.getExtremes(), newMin = xAxis.translate(mouseDownX - chartX, true) + halfPointRange, newMax = xAxis.translate(mouseDownX + chart.plotWidth - chartX, true) - halfPointRange, hoverPoints = chart.hoverPoints; // remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } if (xAxis.series.length && newMin > mathMin(extremes.dataMin, extremes.min) && newMax < mathMax(extremes.dataMax, extremes.max)) { xAxis.setExtremes(newMin, newMax, true, false, { trigger: 'pan' }); } chart.mouseDownX = chartX; // set new reference for next run css(chart.container, { cursor: 'move' }); }, /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ setTitle: function (titleOptions, subtitleOptions) { var chart = this, options = chart.options, chartTitleOptions, chartSubtitleOptions; chart.chartTitleOptions = chartTitleOptions = merge(options.title, titleOptions); chart.chartSubtitleOptions = chartSubtitleOptions = merge(options.subtitle, subtitleOptions); // add title and subtitle each([ ['title', titleOptions, chartTitleOptions], ['subtitle', subtitleOptions, chartSubtitleOptions] ], function (arr) { var name = arr[0], title = chart[name], titleOptions = arr[1], chartTitleOptions = arr[2]; if (title && titleOptions) { chart[name] = title = title.destroy(); // remove old } if (chartTitleOptions && chartTitleOptions.text && !title) { chart[name] = chart.renderer.text( chartTitleOptions.text, 0, 0, chartTitleOptions.useHTML ) .attr({ align: chartTitleOptions.align, 'class': PREFIX + name, zIndex: chartTitleOptions.zIndex || 4 }) .css(chartTitleOptions.style) .add() .align(chartTitleOptions, false, chart.spacingBox); } }); }, /** * Get chart width and height according to options and container size */ getChartSize: function () { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderToClone || chart.renderTo; // get inner width and height from jQuery (#824) chart.containerWidth = adapterRun(renderTo, 'width'); chart.containerHeight = adapterRun(renderTo, 'height'); chart.chartWidth = mathMax(0, pick(optionsChart.width, chart.containerWidth, 600)); chart.chartHeight = mathMax(0, pick(optionsChart.height, // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7: chart.containerHeight > 19 ? chart.containerHeight : 400)); }, /** * Create a clone of the chart's renderTo div and place it outside the viewport to allow * size computation on chart.render and chart.redraw */ cloneRenderTo: function (revert) { var clone = this.renderToClone, container = this.container; // Destroy the clone and bring the container back to the real renderTo div if (revert) { if (clone) { this.renderTo.appendChild(container); discardElement(clone); delete this.renderToClone; } // Set up the clone } else { if (container) { this.renderTo.removeChild(container); // do not clone this } this.renderToClone = clone = this.renderTo.cloneNode(0); css(clone, { position: ABSOLUTE, top: '-9999px', display: 'block' // #833 }); doc.body.appendChild(clone); if (container) { clone.appendChild(container); } } }, /** * Get the containing element, determine the size and create the inner container * div to hold the chart */ getContainer: function () { var chart = this, container, optionsChart = chart.options.chart, chartWidth, chartHeight, renderTo, indexAttrName = 'data-highcharts-chart', oldChartIndex, containerId; chart.renderTo = renderTo = optionsChart.renderTo; containerId = PREFIX + idCounter++; if (isString(renderTo)) { chart.renderTo = renderTo = doc.getElementById(renderTo); } // Display an error if the renderTo is wrong if (!renderTo) { error(13, true); } // If the container already holds a chart, destroy it oldChartIndex = pInt(attr(renderTo, indexAttrName)); if (!isNaN(oldChartIndex) && charts[oldChartIndex]) { charts[oldChartIndex].destroy(); } // Make a reference to the chart from the div attr(renderTo, indexAttrName, chart.index); // remove previous chart renderTo.innerHTML = ''; // If the container doesn't have an offsetWidth, it has or is a child of a node // that has display:none. We need to temporarily move it out to a visible // state to determine the size, else the legend and tooltips won't render // properly if (!renderTo.offsetWidth) { chart.cloneRenderTo(); } // get the width and height chart.getChartSize(); chartWidth = chart.chartWidth; chartHeight = chart.chartHeight; // create the inner container chart.container = container = createElement(DIV, { className: PREFIX + 'container' + (optionsChart.className ? ' ' + optionsChart.className : ''), id: containerId }, extend({ position: RELATIVE, overflow: HIDDEN, // needed for context menu (avoid scrollbars) and // content overflow in IE width: chartWidth + PX, height: chartHeight + PX, textAlign: 'left', lineHeight: 'normal', // #427 zIndex: 0 // #1072 }, optionsChart.style), chart.renderToClone || renderTo ); chart.renderer = optionsChart.forExport ? // force SVG, used for SVG export new SVGRenderer(container, chartWidth, chartHeight, true) : new Renderer(container, chartWidth, chartHeight); if (useCanVG) { // If we need canvg library, extend and configure the renderer // to get the tracker for translating mouse events chart.renderer.create(chart, container, chartWidth, chartHeight); } }, /** * Calculate margins by rendering axis labels in a preliminary position. Title, * subtitle and legend have already been rendered at this stage, but will be * moved into their final positions */ getMargins: function () { var chart = this, optionsChart = chart.options.chart, spacingTop = optionsChart.spacingTop, spacingRight = optionsChart.spacingRight, spacingBottom = optionsChart.spacingBottom, spacingLeft = optionsChart.spacingLeft, axisOffset, legend = chart.legend, optionsMarginTop = chart.optionsMarginTop, optionsMarginLeft = chart.optionsMarginLeft, optionsMarginRight = chart.optionsMarginRight, optionsMarginBottom = chart.optionsMarginBottom, chartTitleOptions = chart.chartTitleOptions, chartSubtitleOptions = chart.chartSubtitleOptions, legendOptions = chart.options.legend, legendMargin = pick(legendOptions.margin, 10), legendX = legendOptions.x, legendY = legendOptions.y, align = legendOptions.align, verticalAlign = legendOptions.verticalAlign, titleOffset; chart.resetMargins(); axisOffset = chart.axisOffset; // adjust for title and subtitle if ((chart.title || chart.subtitle) && !defined(chart.optionsMarginTop)) { titleOffset = mathMax( (chart.title && !chartTitleOptions.floating && !chartTitleOptions.verticalAlign && chartTitleOptions.y) || 0, (chart.subtitle && !chartSubtitleOptions.floating && !chartSubtitleOptions.verticalAlign && chartSubtitleOptions.y) || 0 ); if (titleOffset) { chart.plotTop = mathMax(chart.plotTop, titleOffset + pick(chartTitleOptions.margin, 15) + spacingTop); } } // adjust for legend if (legend.display && !legendOptions.floating) { if (align === 'right') { // horizontal alignment handled first if (!defined(optionsMarginRight)) { chart.marginRight = mathMax( chart.marginRight, legend.legendWidth - legendX + legendMargin + spacingRight ); } } else if (align === 'left') { if (!defined(optionsMarginLeft)) { chart.plotLeft = mathMax( chart.plotLeft, legend.legendWidth + legendX + legendMargin + spacingLeft ); } } else if (verticalAlign === 'top') { if (!defined(optionsMarginTop)) { chart.plotTop = mathMax( chart.plotTop, legend.legendHeight + legendY + legendMargin + spacingTop ); } } else if (verticalAlign === 'bottom') { if (!defined(optionsMarginBottom)) { chart.marginBottom = mathMax( chart.marginBottom, legend.legendHeight - legendY + legendMargin + spacingBottom ); } } } // adjust for scroller if (chart.extraBottomMargin) { chart.marginBottom += chart.extraBottomMargin; } if (chart.extraTopMargin) { chart.plotTop += chart.extraTopMargin; } // pre-render axes to get labels offset width if (chart.hasCartesianSeries) { each(chart.axes, function (axis) { axis.getOffset(); }); } if (!defined(optionsMarginLeft)) { chart.plotLeft += axisOffset[3]; } if (!defined(optionsMarginTop)) { chart.plotTop += axisOffset[0]; } if (!defined(optionsMarginBottom)) { chart.marginBottom += axisOffset[2]; } if (!defined(optionsMarginRight)) { chart.marginRight += axisOffset[1]; } chart.setChartSize(); }, /** * Add the event handlers necessary for auto resizing * */ initReflow: function () { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, reflowTimeout; function reflow(e) { var width = optionsChart.width || adapterRun(renderTo, 'width'), height = optionsChart.height || adapterRun(renderTo, 'height'), target = e ? e.target : win; // #805 - MooTools doesn't supply e // Width and height checks for display:none. Target is doc in IE8 and Opera, // win in Firefox, Chrome and IE9. if (!chart.hasUserSize && width && height && (target === win || target === doc)) { if (width !== chart.containerWidth || height !== chart.containerHeight) { clearTimeout(reflowTimeout); chart.reflowTimeout = reflowTimeout = setTimeout(function () { if (chart.container) { // It may have been destroyed in the meantime (#1257) chart.setSize(width, height, false); chart.hasUserSize = null; } }, 100); } chart.containerWidth = width; chart.containerHeight = height; } } addEvent(win, 'resize', reflow); addEvent(chart, 'destroy', function () { removeEvent(win, 'resize', reflow); }); }, /** * Resize the chart to a given width and height * @param {Number} width * @param {Number} height * @param {Object|Boolean} animation */ setSize: function (width, height, animation) { var chart = this, chartWidth, chartHeight, spacingBox, resetZoomButton = chart.resetZoomButton, chartTitle = chart.title, chartSubtitle = chart.subtitle, fireEndResize; // Handle the isResizing counter chart.isResizing += 1; fireEndResize = function () { if (chart) { fireEvent(chart, 'endResize', null, function () { chart.isResizing -= 1; }); } }; // set the animation for the current process setAnimation(animation, chart); chart.oldChartHeight = chart.chartHeight; chart.oldChartWidth = chart.chartWidth; if (defined(width)) { chart.chartWidth = chartWidth = mathMax(0, mathRound(width)); chart.hasUserSize = !!chartWidth; } if (defined(height)) { chart.chartHeight = chartHeight = mathMax(0, mathRound(height)); } css(chart.container, { width: chartWidth + PX, height: chartHeight + PX }); chart.renderer.setSize(chartWidth, chartHeight, animation); // update axis lengths for more correct tick intervals: chart.plotWidth = chartWidth - chart.plotLeft - chart.marginRight; chart.plotHeight = chartHeight - chart.plotTop - chart.marginBottom; // handle axes chart.maxTicks = null; each(chart.axes, function (axis) { axis.isDirty = true; axis.setScale(); }); // make sure non-cartesian series are also handled each(chart.series, function (serie) { serie.isDirty = true; }); chart.isDirtyLegend = true; // force legend redraw chart.isDirtyBox = true; // force redraw of plot and chart border chart.getMargins(); // move titles spacingBox = chart.spacingBox; if (chartTitle) { chartTitle.align(null, null, spacingBox); } if (chartSubtitle) { chartSubtitle.align(null, null, spacingBox); } // Move resize button (#1115) if (resetZoomButton && resetZoomButton.align) { resetZoomButton.align(null, null, chart[resetZoomButton.alignTo]); } chart.redraw(animation); chart.oldChartHeight = null; fireEvent(chart, 'resize'); // fire endResize and set isResizing back // If animation is disabled, fire without delay if (globalAnimation === false) { fireEndResize(); } else { // else set a timeout with the animation duration setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500); } }, /** * Set the public chart properties. This is done before and after the pre-render * to determine margin sizes */ setChartSize: function () { var chart = this, inverted = chart.inverted, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, optionsChart = chart.options.chart, spacingTop = optionsChart.spacingTop, spacingRight = optionsChart.spacingRight, spacingBottom = optionsChart.spacingBottom, spacingLeft = optionsChart.spacingLeft, plotLeft, plotTop, plotWidth, plotHeight, plotBorderWidth; chart.plotLeft = plotLeft = mathRound(chart.plotLeft); chart.plotTop = plotTop = mathRound(chart.plotTop); chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight)); chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom)); chart.plotSizeX = inverted ? plotHeight : plotWidth; chart.plotSizeY = inverted ? plotWidth : plotHeight; chart.plotBorderWidth = plotBorderWidth = optionsChart.plotBorderWidth || 0; // Set boxes used for alignment chart.spacingBox = { x: spacingLeft, y: spacingTop, width: chartWidth - spacingLeft - spacingRight, height: chartHeight - spacingTop - spacingBottom }; chart.plotBox = { x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }; chart.clipBox = { x: plotBorderWidth / 2, y: plotBorderWidth / 2, width: chart.plotSizeX - plotBorderWidth, height: chart.plotSizeY - plotBorderWidth }; each(chart.axes, function (axis) { axis.setAxisSize(); axis.setAxisTranslation(); }); }, /** * Initial margins before auto size margins are applied */ resetMargins: function () { var chart = this, optionsChart = chart.options.chart, spacingTop = optionsChart.spacingTop, spacingRight = optionsChart.spacingRight, spacingBottom = optionsChart.spacingBottom, spacingLeft = optionsChart.spacingLeft; chart.plotTop = pick(chart.optionsMarginTop, spacingTop); chart.marginRight = pick(chart.optionsMarginRight, spacingRight); chart.marginBottom = pick(chart.optionsMarginBottom, spacingBottom); chart.plotLeft = pick(chart.optionsMarginLeft, spacingLeft); chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left }, /** * Draw the borders and backgrounds for chart and plot area */ drawChartBox: function () { var chart = this, optionsChart = chart.options.chart, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartBackground = chart.chartBackground, plotBackground = chart.plotBackground, plotBorder = chart.plotBorder, plotBGImage = chart.plotBGImage, chartBorderWidth = optionsChart.borderWidth || 0, chartBackgroundColor = optionsChart.backgroundColor, plotBackgroundColor = optionsChart.plotBackgroundColor, plotBackgroundImage = optionsChart.plotBackgroundImage, plotBorderWidth = optionsChart.plotBorderWidth || 0, mgn, bgAttr, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, plotBox = chart.plotBox, clipRect = chart.clipRect, clipBox = chart.clipBox; // Chart area mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0); if (chartBorderWidth || chartBackgroundColor) { if (!chartBackground) { bgAttr = { fill: chartBackgroundColor || NONE }; if (chartBorderWidth) { // #980 bgAttr.stroke = optionsChart.borderColor; bgAttr['stroke-width'] = chartBorderWidth; } chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn, optionsChart.borderRadius, chartBorderWidth) .attr(bgAttr) .add() .shadow(optionsChart.shadow); } else { // resize chartBackground.animate( chartBackground.crisp(null, null, null, chartWidth - mgn, chartHeight - mgn) ); } } // Plot background if (plotBackgroundColor) { if (!plotBackground) { chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0) .attr({ fill: plotBackgroundColor }) .add() .shadow(optionsChart.plotShadow); } else { plotBackground.animate(plotBox); } } if (plotBackgroundImage) { if (!plotBGImage) { chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight) .add(); } else { plotBGImage.animate(plotBox); } } // Plot clip if (!clipRect) { chart.clipRect = renderer.clipRect(clipBox); } else { clipRect.animate({ width: clipBox.width, height: clipBox.height }); } // Plot area border if (plotBorderWidth) { if (!plotBorder) { chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, plotBorderWidth) .attr({ stroke: optionsChart.plotBorderColor, 'stroke-width': plotBorderWidth, zIndex: 1 }) .add(); } else { plotBorder.animate( plotBorder.crisp(null, plotLeft, plotTop, plotWidth, plotHeight) ); } } // reset chart.isDirtyBox = false; }, /** * Detect whether a certain chart property is needed based on inspecting its options * and series. This mainly applies to the chart.invert property, and in extensions to * the chart.angular and chart.polar properties. */ propFromSeries: function () { var chart = this, optionsChart = chart.options.chart, klass, seriesOptions = chart.options.series, i, value; each(['inverted', 'angular', 'polar'], function (key) { // The default series type's class klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType]; // Get the value from available chart-wide properties value = ( chart[key] || // 1. it is set before optionsChart[key] || // 2. it is set in the options (klass && klass.prototype[key]) // 3. it's default series class requires it ); // 4. Check if any the chart's series require it i = seriesOptions && seriesOptions.length; while (!value && i--) { klass = seriesTypes[seriesOptions[i].type]; if (klass && klass.prototype[key]) { value = true; } } // Set the chart property chart[key] = value; }); }, /** * Render all graphics for the chart */ render: function () { var chart = this, axes = chart.axes, renderer = chart.renderer, options = chart.options; var labels = options.labels, credits = options.credits, creditsHref; // Title chart.setTitle(); // Legend chart.legend = new Legend(chart); // Get margins by pre-rendering axes // set axes scales each(axes, function (axis) { axis.setScale(); }); chart.getMargins(); chart.maxTicks = null; // reset for second pass each(axes, function (axis) { axis.setTickPositions(true); // update to reflect the new margins axis.setMaxTicks(); }); chart.adjustTickAmounts(); chart.getMargins(); // second pass to check for new labels // Draw the borders and backgrounds chart.drawChartBox(); // Axes if (chart.hasCartesianSeries) { each(axes, function (axis) { axis.render(); }); } // The series if (!chart.seriesGroup) { chart.seriesGroup = renderer.g('series-group') .attr({ zIndex: 3 }) .add(); } each(chart.series, function (serie) { serie.translate(); serie.setTooltipPoints(); serie.render(); }); // Labels if (labels.items) { each(labels.items, function (label) { var style = extend(labels.style, label.style), x = pInt(style.left) + chart.plotLeft, y = pInt(style.top) + chart.plotTop + 12; // delete to prevent rewriting in IE delete style.left; delete style.top; renderer.text( label.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } // Credits if (credits.enabled && !chart.credits) { creditsHref = credits.href; chart.credits = renderer.text( credits.text, 0, 0 ) .on('click', function () { if (creditsHref) { location.href = creditsHref; } }) .attr({ align: credits.position.align, zIndex: 8 }) .css(credits.style) .add() .align(credits.position); } // Set flag chart.hasRendered = true; }, /** * Clean up memory usage */ destroy: function () { var chart = this, axes = chart.axes, series = chart.series, container = chart.container, i, parentNode = container && container.parentNode; // fire the chart.destoy event fireEvent(chart, 'destroy'); // Delete the chart from charts lookup array charts[chart.index] = UNDEFINED; chart.renderTo.removeAttribute('data-highcharts-chart'); // remove events removeEvent(chart); // ==== Destroy collections: // Destroy axes i = axes.length; while (i--) { axes[i] = axes[i].destroy(); } // Destroy each series i = series.length; while (i--) { series[i] = series[i].destroy(); } // ==== Destroy chart properties: each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage', 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'tracker', 'scroller', 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) { var prop = chart[name]; if (prop && prop.destroy) { chart[name] = prop.destroy(); } }); // remove container and all SVG if (container) { // can break in IE when destroyed before finished loading container.innerHTML = ''; removeEvent(container); if (parentNode) { discardElement(container); } } // clean it all up for (i in chart) { delete chart[i]; } }, /** * VML namespaces can't be added until after complete. Listening * for Perini's doScroll hack is not enough. */ isReadyToRender: function () { var chart = this; // Note: in spite of JSLint's complaints, win == win.top is required /*jslint eqeq: true*/ if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) { /*jslint eqeq: false*/ if (useCanVG) { // Delay rendering until canvg library is downloaded and ready CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL); } else { doc.attachEvent('onreadystatechange', function () { doc.detachEvent('onreadystatechange', chart.firstRender); if (doc.readyState === 'complete') { chart.firstRender(); } }); } return false; } return true; }, /** * Prepare for first rendering after all data are loaded */ firstRender: function () { var chart = this, options = chart.options, callback = chart.callback; // Check whether the chart is ready to render if (!chart.isReadyToRender()) { return; } // Create the container chart.getContainer(); // Run an early event after the container and renderer are established fireEvent(chart, 'init'); // Initialize range selector for stock charts if (Highcharts.RangeSelector && options.rangeSelector.enabled) { chart.rangeSelector = new Highcharts.RangeSelector(chart); } chart.resetMargins(); chart.setChartSize(); // Set the common chart properties (mainly invert) from the given series chart.propFromSeries(); // get axes chart.getAxes(); // Initialize the series each(options.series || [], function (serieOptions) { chart.initSeries(serieOptions); }); // Run an event where series and axes can be added //fireEvent(chart, 'beforeRender'); // Initialize scroller for stock charts if (Highcharts.Scroller && (options.navigator.enabled || options.scrollbar.enabled)) { chart.scroller = new Highcharts.Scroller(chart); } // depends on inverted and on margins being set chart.tracker = new MouseTracker(chart, options); chart.render(); // add canvas chart.renderer.draw(); // run callbacks if (callback) { callback.apply(chart, [chart]); } each(chart.callbacks, function (fn) { fn.apply(chart, [chart]); }); // If the chart was rendered outside the top container, put it back in chart.cloneRenderTo(true); fireEvent(chart, 'load'); } }; // end Chart // Hook for exporting module Chart.prototype.callbacks = []; /** * The Point object and prototype. Inheritable and used as base for PiePoint */ var Point = function () {}; Point.prototype = { /** * Initialize the point * @param {Object} series The series object containing this point * @param {Object} options The data in either number, array or object format */ init: function (series, options, x) { var point = this, counters = series.chart.counters, defaultColors; point.series = series; point.applyOptions(options, x); point.pointAttr = {}; if (series.options.colorByPoint) { defaultColors = series.chart.options.colors; point.color = point.color || defaultColors[counters.color++]; // loop back to zero counters.wrapColor(defaultColors.length); } series.chart.pointCount++; return point; }, /** * Apply the options containing the x and y data and possible some extra properties. * This is called on point init or from point.update. * * @param {Object} options */ applyOptions: function (options, x) { var point = this, series = point.series, optionsType = typeof options; point.config = options; // onedimensional array input if (optionsType === 'number' || options === null) { point.y = options; } else if (typeof options[0] === 'number') { // two-dimentional array point.x = options[0]; point.y = options[1]; } else if (optionsType === 'object' && typeof options.length !== 'number') { // object input // copy options directly to point extend(point, options); point.options = options; // This is the fastest way to detect if there are individual point dataLabels that need // to be considered in drawDataLabels. These can only occur in object configs. if (options.dataLabels) { series._hasPointLabels = true; } // Same approach as above for markers if (options.marker) { series._hasPointMarkers = true; } } else if (typeof options[0] === 'string') { // categorized data with name in first position point.name = options[0]; point.y = options[1]; } /* * If no x is set by now, get auto incremented value. All points must have an * x value, however the y value can be null to create a gap in the series */ // todo: skip this? It is only used in applyOptions, in translate it should not be used if (point.x === UNDEFINED) { point.x = x === UNDEFINED ? series.autoIncrement() : x; } }, /** * Destroy a point to clear memory. Its reference still stays in series.data. */ destroy: function () { var point = this, series = point.series, chart = series.chart, hoverPoints = chart.hoverPoints, prop; chart.pointCount--; if (hoverPoints) { point.setState(); erase(hoverPoints, point); if (!hoverPoints.length) { chart.hoverPoints = null; } } if (point === chart.hoverPoint) { point.onMouseOut(); } // remove all events if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive removeEvent(point); point.destroyElements(); } if (point.legendItem) { // pies have legend items chart.legend.destroyItem(point); } for (prop in point) { point[prop] = null; } }, /** * Destroy SVG elements associated with the point */ destroyElements: function () { var point = this, props = ['graphic', 'tracker', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'], prop, i = 6; while (i--) { prop = props[i]; if (point[prop]) { point[prop] = point[prop].destroy(); } } }, /** * Return the configuration hash needed for the data label and tooltip formatters */ getLabelConfig: function () { var point = this; return { x: point.category, y: point.y, key: point.name || point.category, series: point.series, point: point, percentage: point.percentage, total: point.total || point.stackTotal }; }, /** * Toggle the selection status of a point * @param {Boolean} selected Whether to select or unselect the point. * @param {Boolean} accumulate Whether to add to the previous selection. By default, * this happens if the control key (Cmd on Mac) was pressed during clicking. */ select: function (selected, accumulate) { var point = this, series = point.series, chart = series.chart; selected = pick(selected, !point.selected); // fire the event with the defalut handler point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () { point.selected = selected; point.setState(selected && SELECT_STATE); // unselect all other points unless Ctrl or Cmd + click if (!accumulate) { each(chart.getSelectedPoints(), function (loopPoint) { if (loopPoint.selected && loopPoint !== point) { loopPoint.selected = false; loopPoint.setState(NORMAL_STATE); loopPoint.firePointEvent('unselect'); } }); } }); }, onMouseOver: function () { var point = this, series = point.series, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // set normal state to previous series if (hoverPoint && hoverPoint !== point) { hoverPoint.onMouseOut(); } // trigger the event point.firePointEvent('mouseOver'); // update the tooltip if (tooltip && (!tooltip.shared || series.noSharedTooltip)) { tooltip.refresh(point); } // hover this point.setState(HOVER_STATE); chart.hoverPoint = point; }, onMouseOut: function () { var chart = this.series.chart, hoverPoints = chart.hoverPoints; if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887 this.firePointEvent('mouseOut'); this.setState(); chart.hoverPoint = null; } }, /** * Extendable method for formatting each point's tooltip line * * @return {String} A string to be concatenated in to the common tooltip text */ tooltipFormatter: function (pointFormat) { var point = this, series = point.series, seriesTooltipOptions = series.tooltipOptions, match = pointFormat.match(/\{(series|point)\.[a-zA-Z]+\}/g), splitter = /[{\.}]/, obj, key, replacement, repOptionKey, parts, prop, i, cfg = { y: 0, // 0: use 'value' for repOptionKey open: 0, high: 0, low: 0, close: 0, percentage: 1, // 1: use the self name for repOptionKey total: 1 }; // Backwards compatibility to y naming in early Highstock seriesTooltipOptions.valuePrefix = seriesTooltipOptions.valuePrefix || seriesTooltipOptions.yPrefix; seriesTooltipOptions.valueDecimals = pick(seriesTooltipOptions.valueDecimals, seriesTooltipOptions.yDecimals); // #1248 seriesTooltipOptions.valueSuffix = seriesTooltipOptions.valueSuffix || seriesTooltipOptions.ySuffix; // loop over the variables defined on the form {series.name}, {point.y} etc for (i in match) { key = match[i]; if (isString(key) && key !== pointFormat) { // IE matches more than just the variables // Split it further into parts parts = (' ' + key).split(splitter); // add empty string because IE and the rest handles it differently obj = { 'point': point, 'series': series }[parts[1]]; prop = parts[2]; // Add some preformatting if (obj === point && cfg.hasOwnProperty(prop)) { repOptionKey = cfg[prop] ? prop : 'value'; replacement = (seriesTooltipOptions[repOptionKey + 'Prefix'] || '') + numberFormat(point[prop], pick(seriesTooltipOptions[repOptionKey + 'Decimals'], -1)) + (seriesTooltipOptions[repOptionKey + 'Suffix'] || ''); // Automatic replacement } else { replacement = obj[prop]; } pointFormat = pointFormat.replace(key, replacement); } } return pointFormat; }, /** * Update the point with new options (typically x/y data) and optionally redraw the series. * * @param {Object} options Point options as defined in the series.data array * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * */ update: function (options, redraw, animation) { var point = this, series = point.series, graphic = point.graphic, i, data = series.data, dataLength = data.length, chart = series.chart; redraw = pick(redraw, true); // fire the event with a default handler of doing the update point.firePointEvent('update', { options: options }, function () { point.applyOptions(options); // update visuals if (isObject(options)) { series.getAttribs(); if (graphic) { graphic.attr(point.pointAttr[series.state]); } } // record changes in the parallel arrays for (i = 0; i < dataLength; i++) { if (data[i] === point) { series.xData[i] = point.x; series.yData[i] = point.toYData ? point.toYData() : point.y; series.options.data[i] = options; break; } } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(animation); } }); }, /** * Remove a point and optionally redraw the series and if necessary the axes * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var point = this, series = point.series, chart = series.chart, i, data = series.data, dataLength = data.length; setAnimation(animation, chart); redraw = pick(redraw, true); // fire the event with a default handler of removing the point point.firePointEvent('remove', null, function () { //erase(series.data, point); for (i = 0; i < dataLength; i++) { if (data[i] === point) { // splice all the parallel arrays data.splice(i, 1); series.options.data.splice(i, 1); series.xData.splice(i, 1); series.yData.splice(i, 1); break; } } point.destroy(); // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }); }, /** * Fire an event on the Point object. Must not be renamed to fireEvent, as this * causes a name clash in MooTools * @param {String} eventType * @param {Object} eventArgs Additional event arguments * @param {Function} defaultFunction Default event handler */ firePointEvent: function (eventType, eventArgs, defaultFunction) { var point = this, series = this.series, seriesOptions = series.options; // load event handlers on demand to save time on mouseover/out if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) { this.importEvents(); } // add default handler if in selection mode if (eventType === 'click' && seriesOptions.allowPointSelect) { defaultFunction = function (event) { // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera point.select(null, event.ctrlKey || event.metaKey || event.shiftKey); }; } fireEvent(this, eventType, eventArgs, defaultFunction); }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. */ importEvents: function () { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events, eventType; point.events = events; for (eventType in events) { addEvent(point, eventType, events[eventType]); } this.hasImportedEvents = true; } }, /** * Set the point's state * @param {String} state */ setState: function (state) { var point = this, plotX = point.plotX, plotY = point.plotY, series = point.series, stateOptions = series.options.states, markerOptions = defaultPlotOptions[series.type].marker && series.options.marker, normalDisabled = markerOptions && !markerOptions.enabled, markerStateOptions = markerOptions && markerOptions.states[state], stateDisabled = markerStateOptions && markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, chart = series.chart, radius, pointAttr = point.pointAttr; state = state || NORMAL_STATE; // empty string if ( // already has this state state === point.state || // selected points don't respond to hover (point.selected && state !== SELECT_STATE) || // series' state options is disabled (stateOptions[state] && stateOptions[state].enabled === false) || // point marker's state options is disabled (state && (stateDisabled || (normalDisabled && !markerStateOptions.enabled))) ) { return; } // apply hover styles to the existing point if (point.graphic) { radius = markerOptions && point.graphic.symbolName && pointAttr[state].r; point.graphic.attr(merge( pointAttr[state], radius ? { // new symbol attributes (#507, #612) x: plotX - radius, y: plotY - radius, width: 2 * radius, height: 2 * radius } : {} )); } else { // if a graphic is not applied to each point in the normal state, create a shared // graphic for the hover state if (state && markerStateOptions) { radius = markerStateOptions.radius; if (!stateMarkerGraphic) { // add series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol( series.symbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr[state]) .add(series.markerGroup); } else { // update stateMarkerGraphic.attr({ // #1054 x: plotX - radius, y: plotY - radius }); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY) ? 'show' : 'hide'](); } } point.state = state; } }; /** * @classDescription The base function which all other series types inherit from. The data in the series is stored * in various arrays. * * - First, series.options.data contains all the original config options for * each point whether added by options or methods like series.addPoint. * - Next, series.data contains those values converted to points, but in case the series data length * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It * only contains the points that have been created on demand. * - Then there's series.points that contains all currently visible point objects. In case of cropping, * the cropped-away points are not part of this array. The series.points array starts at series.cropStart * compared to series.data and series.options.data. If however the series data is grouped, these can't * be correlated one to one. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points. * * @param {Object} chart * @param {Object} options */ var Series = function () {}; Series.prototype = { isCartesian: true, type: 'line', pointClass: Point, sorted: true, // requires the data to be sorted requireSorting: true, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor', r: 'radius' }, init: function (chart, options) { var series = this, eventType, events; series.chart = chart; series.options = options = series.setOptions(options); // merge with plotOptions // bind the axes series.bindAxes(); // set some variables extend(series, { name: options.name, state: NORMAL_STATE, pointAttr: {}, visible: options.visible !== false, // true by default selected: options.selected === true // false by default }); // special if (useCanVG) { options.animation = false; } // register event listeners events = options.events; for (eventType in events) { addEvent(series, eventType, events[eventType]); } if ( (events && events.click) || (options.point && options.point.events && options.point.events.click) || options.allowPointSelect ) { chart.runTrackerClick = true; } series.getColor(); series.getSymbol(); // set the data series.setData(options.data, false); // Mark cartesian if (series.isCartesian) { chart.hasCartesianSeries = true; } // Register it in the chart chart.series.push(series); // Sort series according to index option (#248, #1123) stableSort(chart.series, function (a, b) { return (a.options.index || 0) - (b.options.index || 0); }); each(chart.series, function (series, i) { series.index = i; series.name = series.name || 'Series ' + (i + 1); }); }, /** * Set the xAxis and yAxis properties of cartesian series, and register the series * in the axis.series array */ bindAxes: function () { var series = this, seriesOptions = series.options, chart = series.chart, axisOptions; if (series.isCartesian) { each(['xAxis', 'yAxis'], function (AXIS) { // repeat for xAxis and yAxis each(chart[AXIS], function (axis) { // loop through the chart's axis objects axisOptions = axis.options; // apply if the series xAxis or yAxis option mathches the number of the // axis, or if undefined, use the first axis if ((seriesOptions[AXIS] === axisOptions.index) || (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) { // register this series in the axis.series lookup axis.series.push(series); // set this series.xAxis or series.yAxis reference series[AXIS] = axis; // mark dirty for redraw axis.isDirty = true; } }); }); } }, /** * Return an auto incremented x value based on the pointStart and pointInterval options. * This is only used if an x value is not given for the point that calls autoIncrement. */ autoIncrement: function () { var series = this, options = series.options, xIncrement = series.xIncrement; xIncrement = pick(xIncrement, options.pointStart, 0); series.pointInterval = pick(series.pointInterval, options.pointInterval, 1); series.xIncrement = xIncrement + series.pointInterval; return xIncrement; }, /** * Divide the series data into segments divided by null values. */ getSegments: function () { var series = this, lastNull = -1, segments = [], i, points = series.points, pointsLength = points.length; if (pointsLength) { // no action required for [] // if connect nulls, just remove null points if (series.options.connectNulls) { i = pointsLength; while (i--) { if (points[i].y === null) { points.splice(i, 1); } } if (points.length) { segments = [points]; } // else, split on null points } else { each(points, function (point, i) { if (point.y === null) { if (i > lastNull + 1) { segments.push(points.slice(lastNull + 1, i)); } lastNull = i; } else if (i === pointsLength - 1) { // last value segments.push(points.slice(lastNull + 1, i + 1)); } }); } } // register it series.segments = segments; }, /** * Set the series options by merging from the options tree * @param {Object} itemOptions */ setOptions: function (itemOptions) { var chart = this.chart, chartOptions = chart.options, plotOptions = chartOptions.plotOptions, typeOptions = plotOptions[this.type], data = itemOptions.data, options; itemOptions.data = null; // remove from merge to prevent looping over the data set options = merge( typeOptions, plotOptions.series, itemOptions ); // Re-insert the data array to the options and the original config (#717) options.data = itemOptions.data = data; // the tooltip options are merged between global and series specific options this.tooltipOptions = merge(chartOptions.tooltip, options.tooltip); // Delte marker object if not allowed (#1125) if (typeOptions.marker === null) { delete options.marker; } return options; }, /** * Get the series' color */ getColor: function () { var options = this.options, defaultColors = this.chart.options.colors, counters = this.chart.counters; this.color = options.color || (!options.colorByPoint && defaultColors[counters.color++]) || 'gray'; counters.wrapColor(defaultColors.length); }, /** * Get the series' symbol */ getSymbol: function () { var series = this, seriesMarkerOption = series.options.marker, chart = series.chart, defaultSymbols = chart.options.symbols, counters = chart.counters; series.symbol = seriesMarkerOption.symbol || defaultSymbols[counters.symbol++]; // don't substract radius in image symbols (#604) if (/^url/.test(series.symbol)) { seriesMarkerOption.radius = 0; } counters.wrapSymbol(defaultSymbols.length); }, /** * Get the series' symbol in the legend. This method should be overridable to create custom * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols. * * @param {Object} legend The legend object */ drawLegendSymbol: function (legend) { var options = this.options, markerOptions = options.marker, radius, legendOptions = legend.options, legendSymbol, symbolWidth = legendOptions.symbolWidth, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, baseline = legend.baseline, attr; // Draw the line if (options.lineWidth) { attr = { 'stroke-width': options.lineWidth }; if (options.dashStyle) { attr.dashstyle = options.dashStyle; } this.legendLine = renderer.path([ M, 0, baseline - 4, L, symbolWidth, baseline - 4 ]) .attr(attr) .add(legendItemGroup); } // Draw the marker if (markerOptions && markerOptions.enabled) { radius = markerOptions.radius; this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, baseline - 4 - radius, 2 * radius, 2 * radius ) .add(legendItemGroup); } }, /** * Add a point dynamically after chart load time * @param {Object} options Point options as given in series.data * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean} shift If shift is true, a point is shifted off the start * of the series as one is appended to the end. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ addPoint: function (options, redraw, shift, animation) { var series = this, seriesOptions = series.options, data = series.data, graph = series.graph, area = series.area, chart = series.chart, xData = series.xData, yData = series.yData, currentShift = (graph && graph.shift) || 0, dataOptions = seriesOptions.data, point, proto = series.pointClass.prototype; setAnimation(animation, chart); // Make graph animate sideways if (graph && shift) { graph.shift = currentShift + 1; } if (area) { if (shift) { // #780 area.shift = currentShift + 1; } area.isArea = true; // needed in animation, both with and without shift } // Optional redraw, defaults to true redraw = pick(redraw, true); // Get options and push the point to xData, yData and series.options. In series.generatePoints // the Point instance will be created on demand and pushed to the series.data array. point = { series: series }; proto.applyOptions.apply(point, [options]); xData.push(point.x); yData.push(proto.toYData ? proto.toYData.call(point) : point.y); dataOptions.push(options); // Generate points to be added to the legend (#1329) if (seriesOptions.legendType === 'point') { series.generatePoints(); } // Shift the first point off the parallel arrays // todo: consider series.removePoint(i) method if (shift) { if (data[0] && data[0].remove) { data[0].remove(false); } else { data.shift(); xData.shift(); yData.shift(); dataOptions.shift(); } } series.getAttribs(); // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function (data, redraw) { var series = this, oldData = series.points, options = series.options, initialColor = series.initialColor, chart = series.chart, firstPoint = null, xAxis = series.xAxis, i, pointProto = series.pointClass.prototype; // reset properties series.xIncrement = null; series.pointRange = xAxis && xAxis.categories ? 1 : options.pointRange; if (defined(initialColor)) { // reset colors for pie chart.counters.color = initialColor; } // parallel arrays var xData = [], yData = [], dataLength = data ? data.length : [], turboThreshold = options.turboThreshold || 1000, pt, pointArrayMap = series.pointArrayMap, valueCount = pointArrayMap && pointArrayMap.length; // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The // first value is tested, and we assume that all the rest are defined the same // way. Although the 'for' loops are similar, they are repeated inside each // if-else conditional for max performance. if (dataLength > turboThreshold) { // find the first non-null point i = 0; while (firstPoint === null && i < dataLength) { firstPoint = data[i]; i++; } if (isNumber(firstPoint)) { // assume all points are numbers var x = pick(options.pointStart, 0), pointInterval = pick(options.pointInterval, 1); for (i = 0; i < dataLength; i++) { xData[i] = x; yData[i] = data[i]; x += pointInterval; } series.xIncrement = x; } else if (isArray(firstPoint)) { // assume all points are arrays if (valueCount) { // [x, low, high] or [x, o, h, l, c] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt.slice(1, valueCount + 1); } } else { // [x, y] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt[1]; } } } /* else { error(12); // Highcharts expects configs to be numbers or arrays in turbo mode }*/ } else { for (i = 0; i < dataLength; i++) { pt = { series: series }; pointProto.applyOptions.apply(pt, [data[i]]); xData[i] = pt.x; yData[i] = pointProto.toYData ? pointProto.toYData.call(pt) : pt.y; } } // Unsorted data is not supported by the line tooltip as well as data grouping and // navigation in Stock charts (#725) if (series.requireSorting && xData.length > 1 && xData[1] < xData[0]) { error(15); } // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON if (isString(yData[0])) { error(14, true); } series.data = []; series.options.data = data; series.xData = xData; series.yData = yData; // destroy old points i = (oldData && oldData.length) || 0; while (i--) { if (oldData[i] && oldData[i].destroy) { oldData[i].destroy(); } } // reset minRange (#878) if (xAxis) { xAxis.minRange = xAxis.userMinRange; } // redraw series.isDirty = series.isDirtyData = chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(false); } }, /** * Remove a series and optionally redraw the chart * * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var series = this, chart = series.chart; redraw = pick(redraw, true); if (!series.isRemoving) { /* prevent triggering native event in jQuery (calling the remove function from the remove event) */ series.isRemoving = true; // fire the event with a default handler of removing the point fireEvent(series, 'remove', null, function () { // destroy elements series.destroy(); // redraw chart.isDirtyLegend = chart.isDirtyBox = true; if (redraw) { chart.redraw(animation); } }); } series.isRemoving = false; }, /** * Process the data by cropping away unused data points if the series is longer * than the crop threshold. This saves computing time for lage series. */ processData: function (force) { var series = this, processedXData = series.xData, // copied during slice operation below processedYData = series.yData, dataLength = processedXData.length, cropStart = 0, cropEnd = dataLength, cropped, distance, closestPointRange, xAxis = series.xAxis, i, // loop variable options = series.options, cropThreshold = options.cropThreshold, isCartesian = series.isCartesian; // If the series data or axes haven't changed, don't go through this. Return false to pass // the message on to override methods like in data grouping. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) { return false; } // optionally filter out points outside the plot area if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) { var extremes = xAxis.getExtremes(), min = extremes.min, max = extremes.max; // it's outside current extremes if (processedXData[dataLength - 1] < min || processedXData[0] > max) { processedXData = []; processedYData = []; // only crop if it's actually spilling out } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) { // iterate up to find slice start for (i = 0; i < dataLength; i++) { if (processedXData[i] >= min) { cropStart = mathMax(0, i - 1); break; } } // proceed to find slice end for (; i < dataLength; i++) { if (processedXData[i] > max) { cropEnd = i + 1; break; } } processedXData = processedXData.slice(cropStart, cropEnd); processedYData = processedYData.slice(cropStart, cropEnd); cropped = true; } } // Find the closest distance between processed points for (i = processedXData.length - 1; i > 0; i--) { distance = processedXData[i] - processedXData[i - 1]; if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) { closestPointRange = distance; } } // Record the properties series.cropped = cropped; // undefined or true series.cropStart = cropStart; series.processedXData = processedXData; series.processedYData = processedYData; if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC series.pointRange = closestPointRange || 1; } series.closestPointRange = closestPointRange; }, /** * Generate the data point after the data has been processed by cropping away * unused points and optionally grouped in Highcharts Stock. */ generatePoints: function () { var series = this, options = series.options, dataOptions = options.data, data = series.data, dataLength, processedXData = series.processedXData, processedYData = series.processedYData, pointClass = series.pointClass, processedDataLength = processedXData.length, cropStart = series.cropStart || 0, cursor, hasGroupedData = series.hasGroupedData, point, points = [], i; if (!data && !hasGroupedData) { var arr = []; arr.length = dataOptions.length; data = series.data = arr; } for (i = 0; i < processedDataLength; i++) { cursor = cropStart + i; if (!hasGroupedData) { if (data[cursor]) { point = data[cursor]; } else if (dataOptions[cursor] !== UNDEFINED) { // #970 data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]); } points[i] = point; } else { // splat the y data in case of ohlc data array points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i]))); } } // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when // swithching view from non-grouped data to grouped data (#637) if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) { for (i = 0; i < dataLength; i++) { if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points i += processedDataLength; } if (data[i]) { data[i].destroyElements(); data[i].plotX = UNDEFINED; // #1003 } } } series.data = data; series.points = points; }, /** * Translate data points from raw data values to chart specific positioning data * needed later in drawPoints, drawGraph and drawTracker. */ translate: function () { if (!this.processedXData) { // hidden series this.processData(); } this.generatePoints(); var series = this, chart = series.chart, options = series.options, stacking = options.stacking, xAxis = series.xAxis, categories = xAxis.categories, yAxis = series.yAxis, points = series.points, dataLength = points.length, hasModifyValue = !!series.modifyValue, isBottomSeries, allStackSeries = yAxis.series, i = allStackSeries.length, placeBetween = options.pointPlacement === 'between'; //nextSeriesDown; // Is it the last visible series? while (i--) { if (allStackSeries[i].visible) { if (allStackSeries[i] === series) { // #809 isBottomSeries = true; } break; } } // Translate each point for (i = 0; i < dataLength; i++) { var point = points[i], xValue = point.x, yValue = point.y, yBottom = point.low, stack = yAxis.stacks[(yValue < options.threshold ? '-' : '') + series.stackKey], pointStack, pointStackTotal; // get the plotX translation //point.plotX = mathRound(xAxis.translate(xValue, 0, 0, 0, 1) * 10) / 10; // Math.round fixes #591 point.plotX = xAxis.translate(xValue, 0, 0, 0, 1, placeBetween); // Math.round fixes #591 // calculate the bottom y value for stacked series if (stacking && series.visible && stack && stack[xValue]) { pointStack = stack[xValue]; pointStackTotal = pointStack.total; pointStack.cum = yBottom = pointStack.cum - yValue; // start from top yValue = yBottom + yValue; if (isBottomSeries) { yBottom = pick(options.threshold, yAxis.min); } if (yAxis.isLog && yBottom <= 0) { // #1200, #1232 yBottom = null; } if (stacking === 'percent') { yBottom = pointStackTotal ? yBottom * 100 / pointStackTotal : 0; yValue = pointStackTotal ? yValue * 100 / pointStackTotal : 0; } point.percentage = pointStackTotal ? point.y * 100 / pointStackTotal : 0; point.total = point.stackTotal = pointStackTotal; point.stackY = yValue; } // Set translated yBottom or remove it point.yBottom = defined(yBottom) ? yAxis.translate(yBottom, 0, 1, 0, 1) : null; // general hook, used for Highstock compare mode if (hasModifyValue) { yValue = series.modifyValue(yValue, point); } // Set the the plotY value, reset it for redraws point.plotY = (typeof yValue === 'number') ? mathRound(yAxis.translate(yValue, 0, 1, 0, 1) * 10) / 10 : // Math.round fixes #591 UNDEFINED; // set client related positions for mouse tracking point.clientX = chart.inverted ? chart.plotHeight - point.plotX : point.plotX; // for mouse tracking // some API data point.category = categories && categories[point.x] !== UNDEFINED ? categories[point.x] : point.x; } // now that we have the cropped data, build the segments series.getSegments(); }, /** * Memoize tooltip texts and positions */ setTooltipPoints: function (renew) { var series = this, points = [], pointsLength, low, high, xAxis = series.xAxis, axisLength = xAxis ? (xAxis.tooltipLen || xAxis.len) : series.chart.plotSizeX, // tooltipLen and tooltipPosName used in polar plotX = (xAxis && xAxis.tooltipPosName) || 'plotX', point, i, tooltipPoints = []; // a lookup array for each pixel in the x dimension // don't waste resources if tracker is disabled if (series.options.enableMouseTracking === false) { return; } // renew if (renew) { series.tooltipPoints = null; } // concat segments to overcome null values each(series.segments || series.points, function (segment) { points = points.concat(segment); }); // Reverse the points in case the X axis is reversed if (xAxis && xAxis.reversed) { points = points.reverse(); } // Assign each pixel position to the nearest point pointsLength = points.length; for (i = 0; i < pointsLength; i++) { point = points[i]; // Set this range's low to the last range's high plus one low = points[i - 1] ? high + 1 : 0; // Now find the new high high = points[i + 1] ? mathMax(0, mathFloor((point[plotX] + (points[i + 1] ? points[i + 1][plotX] : axisLength)) / 2)) : axisLength; while (low >= 0 && low <= high) { tooltipPoints[low++] = point; } } series.tooltipPoints = tooltipPoints; }, /** * Format the header of the tooltip */ tooltipHeaderFormatter: function (key) { var series = this, tooltipOptions = series.tooltipOptions, xDateFormat = tooltipOptions.xDateFormat, xAxis = series.xAxis, isDateTime = xAxis && xAxis.options.type === 'datetime', n; // Guess the best date format based on the closest point distance (#568) if (isDateTime && !xDateFormat) { for (n in timeUnits) { if (timeUnits[n] >= xAxis.closestPointRange) { xDateFormat = tooltipOptions.dateTimeLabelFormats[n]; break; } } } return tooltipOptions.headerFormat .replace('{point.key}', isDateTime && isNumber(key) ? dateFormat(xDateFormat, key) : key) .replace('{series.name}', series.name) .replace('{series.color}', series.color); }, /** * Series mouse over handler */ onMouseOver: function () { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; // set normal state to previous series if (hoverSeries && hoverSeries !== series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // hover this series.setState(HOVER_STATE); chart.hoverSeries = series; }, /** * Series mouse out handler */ onMouseOut: function () { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !options.stickyTracking && !tooltip.shared) { tooltip.hide(); } // set normal state series.setState(); chart.hoverSeries = null; }, /** * Animate in the series */ animate: function (init) { var series = this, chart = series.chart, renderer = chart.renderer, clipRect, markerClipRect, animation = series.options.animation, clipBox = chart.clipBox, inverted = chart.inverted, sharedClipKey; // Animation option is set to true if (animation && !isObject(animation)) { animation = defaultPlotOptions[series.type].animation; } sharedClipKey = '_sharedClip' + animation.duration + animation.easing; // Initialize the animation. Set up the clipping rectangle. if (init) { // If a clipping rectangle with the same properties is currently present in the chart, use that. clipRect = chart[sharedClipKey]; markerClipRect = chart[sharedClipKey + 'm']; if (!clipRect) { chart[sharedClipKey] = clipRect = renderer.clipRect( extend(clipBox, { width: 0 }) ); chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect( -99, // include the width of the first marker inverted ? -chart.plotLeft : -chart.plotTop, 99, inverted ? chart.chartWidth : chart.chartHeight ); } series.group.clip(clipRect); series.markerGroup.clip(markerClipRect); series.sharedClipKey = sharedClipKey; // Run the animation } else { clipRect = chart[sharedClipKey]; if (clipRect) { clipRect.animate({ width: chart.plotSizeX }, animation); chart[sharedClipKey + 'm'].animate({ width: chart.plotSizeX + 99 }, animation); } // Delete this function to allow it only once series.animate = null; // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option // which should be available to the user). series.animationTimeout = setTimeout(function () { series.afterAnimate(); }, animation.duration); } }, /** * This runs after animation to land on the final plot clipping */ afterAnimate: function () { var chart = this.chart, sharedClipKey = this.sharedClipKey, group = this.group, trackerGroup = this.trackerGroup; if (group && this.options.clip !== false) { group.clip(chart.clipRect); if (trackerGroup) { trackerGroup.clip(chart.clipRect); // #484 } this.markerGroup.clip(); // no clip } // Remove the shared clipping rectancgle when all series are shown setTimeout(function () { if (sharedClipKey && chart[sharedClipKey]) { chart[sharedClipKey] = chart[sharedClipKey].destroy(); chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy(); } }, 100); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, points = series.points, chart = series.chart, plotX, plotY, i, point, radius, symbol, isImage, graphic, options = series.options, seriesMarkerOptions = options.marker, pointMarkerOptions, enabled, isInside, markerGroup = series.markerGroup; if (seriesMarkerOptions.enabled || series._hasPointMarkers) { i = points.length; while (i--) { point = points[i]; plotX = point.plotX; plotY = point.plotY; graphic = point.graphic; pointMarkerOptions = point.marker || {}; enabled = (seriesMarkerOptions.enabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled; isInside = chart.isInsidePlot(plotX, plotY, chart.inverted); // only draw the point if y is defined if (enabled && plotY !== UNDEFINED && !isNaN(plotY)) { // shortcuts pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]; radius = pointAttr.r; symbol = pick(pointMarkerOptions.symbol, series.symbol); isImage = symbol.indexOf('url') === 0; if (graphic) { // update graphic .attr({ // Since the marker group isn't clipped, each individual marker must be toggled visibility: isInside ? (hasSVG ? 'inherit' : VISIBLE) : HIDDEN }) .animate(extend({ x: plotX - radius, y: plotY - radius }, graphic.symbolName ? { // don't apply to image symbols #507 width: 2 * radius, height: 2 * radius } : {})); } else if (isInside && (radius > 0 || isImage)) { point.graphic = graphic = chart.renderer.symbol( symbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr) .add(markerGroup); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } } } }, /** * Convert state properties from API naming conventions to SVG attributes * * @param {Object} options API options object * @param {Object} base1 SVG attribute object to inherit from * @param {Object} base2 Second level SVG attribute object to inherit from */ convertAttribs: function (options, base1, base2, base3) { var conversion = this.pointAttrToOptions, attr, option, obj = {}; options = options || {}; base1 = base1 || {}; base2 = base2 || {}; base3 = base3 || {}; for (attr in conversion) { option = conversion[attr]; obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]); } return obj; }, /** * Get the state attributes. Each series type has its own set of attributes * that are allowed to change on a point's state change. Series wide attributes are stored for * all series, and additionally point specific attributes are stored for all * points with individual marker options. If such options are not defined for the point, * a reference to the series wide attributes is stored in point.pointAttr. */ getAttribs: function () { var series = this, normalOptions = defaultPlotOptions[series.type].marker ? series.options.marker : series.options, stateOptions = normalOptions.states, stateOptionsHover = stateOptions[HOVER_STATE], pointStateOptionsHover, seriesColor = series.color, normalDefaults = { stroke: seriesColor, fill: seriesColor }, points = series.points || [], // #927 i, point, seriesPointAttr = [], pointAttr, pointAttrToOptions = series.pointAttrToOptions, hasPointSpecificOptions, key; // series type specific modifications if (series.options.marker) { // line, spline, area, areaspline, scatter // if no hover radius is given, default to normal radius + 2 stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + 2; stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + 1; } else { // column, bar, pie // if no hover color is given, brighten the normal color stateOptionsHover.color = stateOptionsHover.color || Color(stateOptionsHover.color || seriesColor) .brighten(stateOptionsHover.brightness).get(); } // general point attributes for the series normal state seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults); // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius each([HOVER_STATE, SELECT_STATE], function (state) { seriesPointAttr[state] = series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]); }); // set it series.pointAttr = seriesPointAttr; // Generate the point-specific attribute collections if specific point // options are given. If not, create a referance to the series wide point // attributes i = points.length; while (i--) { point = points[i]; normalOptions = (point.options && point.options.marker) || point.options; if (normalOptions && normalOptions.enabled === false) { normalOptions.radius = 0; } hasPointSpecificOptions = series.options.colorByPoint; // #868 // check if the point has specific visual options if (point.options) { for (key in pointAttrToOptions) { if (defined(normalOptions[pointAttrToOptions[key]])) { hasPointSpecificOptions = true; } } } // a specific marker config object is defined for the individual point: // create it's own attribute collection if (hasPointSpecificOptions) { normalOptions = normalOptions || {}; pointAttr = []; stateOptions = normalOptions.states || {}; // reassign for individual point pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {}; // Handle colors for column and pies if (!series.options.marker) { // column, bar, point // if no hover color is given, brighten the normal color pointStateOptionsHover.color = Color(pointStateOptionsHover.color || point.color) .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness).get(); } // normal point state inherits series wide normal state pointAttr[NORMAL_STATE] = series.convertAttribs(extend({ color: point.color // #868 }, normalOptions), seriesPointAttr[NORMAL_STATE]); // inherit from point normal and series hover pointAttr[HOVER_STATE] = series.convertAttribs( stateOptions[HOVER_STATE], seriesPointAttr[HOVER_STATE], pointAttr[NORMAL_STATE] ); // inherit from point normal and series hover pointAttr[SELECT_STATE] = series.convertAttribs( stateOptions[SELECT_STATE], seriesPointAttr[SELECT_STATE], pointAttr[NORMAL_STATE] ); // no marker config object is created: copy a reference to the series-wide // attribute collection } else { pointAttr = seriesPointAttr; } point.pointAttr = pointAttr; } }, /** * Clear DOM objects and free up memory */ destroy: function () { var series = this, chart = series.chart, issue134 = /AppleWebKit\/533/.test(userAgent), destroy, i, data = series.data || [], point, prop, axis; // add event hook fireEvent(series, 'destroy'); // remove all events removeEvent(series); // erase from axes each(['xAxis', 'yAxis'], function (AXIS) { axis = series[AXIS]; if (axis) { erase(axis.series, series); axis.isDirty = true; } }); // remove legend items if (series.legendItem) { series.chart.legend.destroyItem(series); } // destroy all points with their elements i = data.length; while (i--) { point = data[i]; if (point && point.destroy) { point.destroy(); } } series.points = null; // Clear the animation timeout if we are destroying the series during initial animation clearTimeout(series.animationTimeout); // destroy all SVGElements associated to the series each(['area', 'graph', 'dataLabelsGroup', 'group', 'markerGroup', 'tracker', 'trackerGroup'], function (prop) { if (series[prop]) { // issue 134 workaround destroy = issue134 && prop === 'group' ? 'hide' : 'destroy'; series[prop][destroy](); } }); // remove from hoverSeries if (chart.hoverSeries === series) { chart.hoverSeries = null; } erase(chart.series, series); // clear all members for (prop in series) { delete series[prop]; } }, /** * Draw the data labels */ drawDataLabels: function () { var series = this, seriesOptions = series.options, options = seriesOptions.dataLabels, points = series.points, pointOptions, generalOptions, str, dataLabelsGroup; if (options.enabled || series._hasPointLabels) { // Process default alignment of data labels for columns if (series.dlProcessOptions) { series.dlProcessOptions(options); } // Create a separate group for the data labels to avoid rotation dataLabelsGroup = series.plotGroup( 'dataLabelsGroup', 'data-labels', series.visible ? VISIBLE : HIDDEN, options.zIndex || 6 ); // Make the labels for each point generalOptions = options; each(points, function (point) { var enabled, dataLabel = point.dataLabel, attr, name, rotation, isNew = true; // Determine if each data label is enabled pointOptions = point.options && point.options.dataLabels; enabled = generalOptions.enabled || (pointOptions && pointOptions.enabled); // If the point is outside the plot area, destroy it. #678, #820 if (dataLabel && !enabled) { point.dataLabel = dataLabel.destroy(); // Individual labels are disabled if the are explicitly disabled // in the point options, or if they fall outside the plot area. } else if (enabled) { rotation = options.rotation; // Create individual options structure that can be extended without // affecting others options = merge(generalOptions, pointOptions); // Get the string str = options.formatter.call(point.getLabelConfig(), options); // Determine the color options.style.color = pick(options.color, options.style.color, series.color, 'black'); // update existing label if (dataLabel) { // vertically centered dataLabel .attr({ text: str }); isNew = false; // create new label } else if (defined(str)) { attr = { //align: align, fill: options.backgroundColor, stroke: options.borderColor, 'stroke-width': options.borderWidth, r: options.borderRadius || 0, rotation: rotation, padding: options.padding, zIndex: 1 }; // Remove unused attributes (#947) for (name in attr) { if (attr[name] === UNDEFINED) { delete attr[name]; } } dataLabel = point.dataLabel = series.chart.renderer[rotation ? 'text' : 'label']( // labels don't support rotation str, 0, -999, null, null, null, options.useHTML ) .attr(attr) .css(options.style) .add(dataLabelsGroup) .shadow(options.shadow); } // Now the data label is created and placed at 0,0, so we need to align it if (dataLabel) { series.alignDataLabel(point, dataLabel, options, null, isNew); } } }); } }, /** * Align each individual data label */ alignDataLabel: function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, plotX = pick(point.plotX, -999), plotY = pick(point.plotY, -999), bBox = dataLabel.getBBox(), alignAttr; // the final position; // The alignment box is a singular point alignTo = extend({ x: inverted ? chart.plotWidth - plotY : plotX, y: mathRound(inverted ? chart.plotHeight - plotX : plotY), width: 0, height: 0 }, alignTo); // Add the text size for alignment calculation extend(options, { width: bBox.width, height: bBox.height }); // Allow a hook for changing alignment in the last moment, then do the alignment if (options.rotation) { // Fancy box alignment isn't supported for rotated text alignAttr = { align: options.align, x: alignTo.x + options.x + alignTo.width / 2, y: alignTo.y + options.y + alignTo.height / 2 }; dataLabel[isNew ? 'attr' : 'animate'](alignAttr); } else { dataLabel.align(options, null, alignTo); alignAttr = dataLabel.alignAttr; } // Show or hide based on the final aligned position dataLabel.attr({ visibility: options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) || chart.isInsidePlot(plotX, plotY, inverted) ? (chart.renderer.isSVG ? 'inherit' : VISIBLE) : HIDDEN }); }, /** * Return the graph path of a segment */ getSegmentPath: function (segment) { var series = this, segmentPath = [], step = series.options.step; // build the segment line each(segment, function (point, i) { var plotX = point.plotX, plotY = point.plotY, lastPoint; if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i)); } else { // moveTo or lineTo segmentPath.push(i ? L : M); // step line? if (step && i) { lastPoint = segment[i - 1]; if (step === 'right') { segmentPath.push( lastPoint.plotX, plotY ); } else if (step === 'center') { segmentPath.push( (lastPoint.plotX + plotX) / 2, lastPoint.plotY, (lastPoint.plotX + plotX) / 2, plotY ); } else { segmentPath.push( plotX, lastPoint.plotY ); } } // normal line to next point segmentPath.push( point.plotX, point.plotY ); } }); return segmentPath; }, /** * Get the graph path */ getGraphPath: function () { var series = this, graphPath = [], segmentPath, singlePoints = []; // used in drawTracker // Divide into segments and build graph and area paths each(series.segments, function (segment) { segmentPath = series.getSegmentPath(segment); // add the segment to the graph, or a single point for tracking if (segment.length > 1) { graphPath = graphPath.concat(segmentPath); } else { singlePoints.push(segment[0]); } }); // Record it for use in drawGraph and drawTracker, and return graphPath series.singlePoints = singlePoints; series.graphPath = graphPath; return graphPath; }, /** * Draw the actual graph */ drawGraph: function () { var options = this.options, graph = this.graph, group = this.group, color = options.lineColor || this.color, lineWidth = options.lineWidth, dashStyle = options.dashStyle, attribs, graphPath = this.getGraphPath(); // draw the graph if (graph) { stop(graph); // cancel running animations, #459 graph.animate({ d: graphPath }); } else { if (lineWidth) { attribs = { stroke: color, 'stroke-width': lineWidth, zIndex: 1 // #1069 }; if (dashStyle) { attribs.dashstyle = dashStyle; } this.graph = this.chart.renderer.path(graphPath) .attr(attribs).add(group).shadow(options.shadow); } } }, /** * Initialize and perform group inversion on series.group and series.trackerGroup */ invertGroups: function () { var series = this, chart = series.chart; // A fixed size is needed for inversion to work function setInvert() { var size = { width: series.yAxis.len, height: series.xAxis.len }; each(['group', 'trackerGroup', 'markerGroup'], function (groupName) { if (series[groupName]) { series[groupName].attr(size).invert(); } }); } addEvent(chart, 'resize', setInvert); // do it on resize addEvent(series, 'destroy', function () { removeEvent(chart, 'resize', setInvert); }); // Do it now setInvert(); // do it now // On subsequent render and redraw, just do setInvert without setting up events again series.invertGroups = setInvert; }, /** * General abstraction for creating plot groups like series.group, series.trackerGroup, series.dataLabelsGroup and * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size. */ plotGroup: function (prop, name, visibility, zIndex, parent) { var group = this[prop], chart = this.chart, xAxis = this.xAxis, yAxis = this.yAxis; // Generate it on first call if (!group) { this[prop] = group = chart.renderer.g(name) .attr({ visibility: visibility, zIndex: zIndex || 0.1 // IE8 needs this }) .add(parent); } // Place it on first and subsequent (redraw) calls group.translate( xAxis ? xAxis.left : chart.plotLeft, yAxis ? yAxis.top : chart.plotTop ); return group; }, /** * Render the graph and markers */ render: function () { var series = this, chart = series.chart, group, options = series.options, animation = options.animation, doAnimation = animation && !!series.animate, visibility = series.visible ? VISIBLE : HIDDEN, zIndex = options.zIndex, hasRendered = series.hasRendered, chartSeriesGroup = chart.seriesGroup; // the group group = series.plotGroup( 'group', 'series', visibility, zIndex, chartSeriesGroup ); series.markerGroup = series.plotGroup( 'markerGroup', 'markers', visibility, zIndex, chartSeriesGroup ); // initiate the animation if (doAnimation) { series.animate(true); } // cache attributes for shapes series.getAttribs(); // SVGRenderer needs to know this before drawing elements (#1089) group.inverted = chart.inverted; // draw the graph if any if (series.drawGraph) { series.drawGraph(); } // draw the points series.drawPoints(); // draw the data labels series.drawDataLabels(); // draw the mouse tracking area if (series.options.enableMouseTracking !== false) { series.drawTracker(); } // Handle inverted series and tracker groups if (chart.inverted) { series.invertGroups(); } // Initial clipping, must be defined after inverting groups for VML if (options.clip !== false && !series.sharedClipKey && !hasRendered) { group.clip(chart.clipRect); if (this.trackerGroup) { this.trackerGroup.clip(chart.clipRect); } } // Run the animation if (doAnimation) { series.animate(); } else if (!hasRendered) { series.afterAnimate(); } series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see series.hasRendered = true; }, /** * Redraw the series after an update in the axes. */ redraw: function () { var series = this, chart = series.chart, wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after group = series.group; // reposition on resize if (group) { if (chart.inverted) { group.attr({ width: chart.plotWidth, height: chart.plotHeight }); } group.animate({ translateX: series.xAxis.left, translateY: series.yAxis.top }); } series.translate(); series.setTooltipPoints(true); series.render(); if (wasDirtyData) { fireEvent(series, 'updatedData'); } }, /** * Set the state of the graph */ setState: function (state) { var series = this, options = series.options, graph = series.graph, stateOptions = options.states, lineWidth = options.lineWidth; state = state || NORMAL_STATE; if (series.state !== state) { series.state = state; if (stateOptions[state] && stateOptions[state].enabled === false) { return; } if (state) { lineWidth = stateOptions[state].lineWidth || lineWidth + 1; } if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML graph.attr({ // use attr because animate will cause any other animation on the graph to stop 'stroke-width': lineWidth }, state ? 0 : 500); } } }, /** * Set the visibility of the graph * * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED, * the visibility is toggled. */ setVisible: function (vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, seriesGroup = series.group, seriesTracker = series.tracker, dataLabelsGroup = series.dataLabelsGroup, markerGroup = series.markerGroup, showOrHide, i, points = series.points, point, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = vis === UNDEFINED ? !oldVisibility : vis; showOrHide = vis ? 'show' : 'hide'; // show or hide series if (seriesGroup) { // pies don't have one seriesGroup[showOrHide](); } if (markerGroup) { markerGroup[showOrHide](); } // show or hide trackers if (seriesTracker) { seriesTracker[showOrHide](); } else if (points) { i = points.length; while (i--) { point = points[i]; if (point.tracker) { point.tracker[showOrHide](); } } } // hide tooltip (#1361) if (chart.hoverSeries === series) { series.onMouseOut(); } if (dataLabelsGroup) { dataLabelsGroup[showOrHide](); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { each(chart.series, function (otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } if (ignoreHiddenSeries) { chart.isDirtyBox = true; } if (redraw !== false) { chart.redraw(); } fireEvent(series, showOrHide); }, /** * Show the graph */ show: function () { this.setVisible(true); }, /** * Hide the graph */ hide: function () { this.setVisible(false); }, /** * Set the selected state of the graph * * @param selected {Boolean} True to select the series, false to unselect. If * UNDEFINED, the selection state is toggled. */ select: function (selected) { var series = this; // if called without an argument, toggle series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected; if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. */ drawTracker: function () { var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, cursor = options.cursor, css = cursor && { cursor: cursor }, singlePoints = series.singlePoints, trackerGroup = this.isCartesian && this.plotGroup('trackerGroup', null, VISIBLE, options.zIndex || 1, chart.trackerGroup), singlePoint, i, onMouseOver = function () { if (chart.hoverSeries !== series) { series.onMouseOver(); } }, onMouseOut = function () { if (!options.stickyTracking) { series.onMouseOut(); } }; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength && !trackByArea) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] === M) { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L); } if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // handle single points for (i = 0; i < singlePoints.length; i++) { singlePoint = singlePoints[i]; trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY, L, singlePoint.plotX + snap, singlePoint.plotY); } // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else { // create series.tracker = tracker = renderer.path(trackerPath) .attr({ isTracker: true, 'stroke-linejoin': 'round', // #1225 visibility: series.visible ? VISIBLE : HIDDEN, stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : NONE, 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap) }) .on('mouseover', onMouseOver) .on('mouseout', onMouseOut) .css(css) .add(trackerGroup); if (hasTouch) { tracker.on('touchstart', onMouseOver); } } } }; // end Series prototype /** * LineSeries object */ var LineSeries = extendClass(Series); seriesTypes.line = LineSeries; /** * Set the default options for area */ defaultPlotOptions.area = merge(defaultSeriesOptions, { threshold: 0 // trackByArea: false, // lineColor: null, // overrides color, but lets fillColor be unaltered // fillOpacity: 0.75, // fillColor: null }); /** * AreaSeries object */ var AreaSeries = extendClass(Series, { type: 'area', /** * Extend the base Series getSegmentPath method by adding the path for the area. * This path is pushed to the series.areaPath property. */ getSegmentPath: function (segment) { var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path i, options = this.options, segLength = segmentPath.length; if (segLength === 3) { // for animation from 1 to two points areaSegmentPath.push(L, segmentPath[1], segmentPath[2]); } if (options.stacking && !this.closedStacks) { // Follow stack back. Todo: implement areaspline. A general solution could be to // reverse the entire graphPath of the previous series, though may be hard with // splines and with series with different extremes for (i = segment.length - 1; i >= 0; i--) { // step line? if (i < segment.length - 1 && options.step) { areaSegmentPath.push(segment[i + 1].plotX, segment[i].yBottom); } areaSegmentPath.push(segment[i].plotX, segment[i].yBottom); } } else { // follow zero line back this.closeSegment(areaSegmentPath, segment); } this.areaPath = this.areaPath.concat(areaSegmentPath); return segmentPath; }, /** * Extendable method to close the segment path of an area. This is overridden in polar * charts. */ closeSegment: function (path, segment) { var translatedThreshold = this.yAxis.getThreshold(this.options.threshold); path.push( L, segment[segment.length - 1].plotX, translatedThreshold, L, segment[0].plotX, translatedThreshold ); }, /** * Draw the graph and the underlying area. This method calls the Series base * function and adds the area. The areaPath is calculated in the getSegmentPath * method called from Series.prototype.drawGraph. */ drawGraph: function () { // Define or reset areaPath this.areaPath = []; // Call the base method Series.prototype.drawGraph.apply(this); // Define local variables var areaPath = this.areaPath, options = this.options, area = this.area; // Create or update the area if (area) { // update area.animate({ d: areaPath }); } else { // create this.area = this.chart.renderer.path(areaPath) .attr({ fill: pick( options.fillColor, Color(this.color).setOpacity(options.fillOpacity || 0.75).get() ), zIndex: 0 // #1069 }).add(this.group); } }, /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawLegendSymbol: function (legend, item) { item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - 11, legend.options.symbolWidth, 12, 2 ).attr({ zIndex: 3 }).add(item.legendGroup); } }); seriesTypes.area = AreaSeries;/** * Set the default options for spline */ defaultPlotOptions.spline = merge(defaultSeriesOptions); /** * SplineSeries object */ var SplineSeries = extendClass(Series, { type: 'spline', /** * Get the spline segment from a given point's previous neighbour to the given point */ getPointSpline: function (segment, point, i) { var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc denom = smoothing + 1, plotX = point.plotX, plotY = point.plotY, lastPoint = segment[i - 1], nextPoint = segment[i + 1], leftContX, leftContY, rightContX, rightContY, ret; // find control points if (lastPoint && nextPoint) { var lastX = lastPoint.plotX, lastY = lastPoint.plotY, nextX = nextPoint.plotX, nextY = nextPoint.plotY, correction; leftContX = (smoothing * plotX + lastX) / denom; leftContY = (smoothing * plotY + lastY) / denom; rightContX = (smoothing * plotX + nextX) / denom; rightContY = (smoothing * plotY + nextY) / denom; // have the two control points make a straight line through main point correction = ((rightContY - leftContY) * (rightContX - plotX)) / (rightContX - leftContX) + plotY - rightContY; leftContY += correction; rightContY += correction; // to prevent false extremes, check that control points are between // neighbouring points' y values if (leftContY > lastY && leftContY > plotY) { leftContY = mathMax(lastY, plotY); rightContY = 2 * plotY - leftContY; // mirror of left control point } else if (leftContY < lastY && leftContY < plotY) { leftContY = mathMin(lastY, plotY); rightContY = 2 * plotY - leftContY; } if (rightContY > nextY && rightContY > plotY) { rightContY = mathMax(nextY, plotY); leftContY = 2 * plotY - rightContY; } else if (rightContY < nextY && rightContY < plotY) { rightContY = mathMin(nextY, plotY); leftContY = 2 * plotY - rightContY; } // record for drawing in next point point.rightContX = rightContX; point.rightContY = rightContY; } // Visualize control points for debugging /* if (leftContX) { this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2) .attr({ stroke: 'red', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'red', 'stroke-width': 1 }) .add(); this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2) .attr({ stroke: 'green', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'green', 'stroke-width': 1 }) .add(); } // */ // moveTo or lineTo if (!i) { ret = [M, plotX, plotY]; } else { // curve from last point to this ret = [ 'C', lastPoint.rightContX || lastPoint.plotX, lastPoint.rightContY || lastPoint.plotY, leftContX || plotX, leftContY || plotY, plotX, plotY ]; lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later } return ret; } }); seriesTypes.spline = SplineSeries; /** * Set the default options for areaspline */ defaultPlotOptions.areaspline = merge(defaultPlotOptions.area); /** * AreaSplineSeries object */ var areaProto = AreaSeries.prototype, AreaSplineSeries = extendClass(SplineSeries, { type: 'areaspline', closedStacks: true, // instead of following the previous graph back, follow the threshold back // Mix in methods from the area series getSegmentPath: areaProto.getSegmentPath, closeSegment: areaProto.closeSegment, drawGraph: areaProto.drawGraph }); seriesTypes.areaspline = AreaSplineSeries; /** * Set the default options for column */ defaultPlotOptions.column = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', borderWidth: 1, borderRadius: 0, //colorByPoint: undefined, groupPadding: 0.2, //grouping: true, marker: null, // point options are specified in the base options pointPadding: 0.1, //pointWidth: null, minPointLength: 0, cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories states: { hover: { brightness: 0.1, shadow: false }, select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } }, dataLabels: { align: null, // auto verticalAlign: null, // auto y: null }, threshold: 0 }); /** * ColumnSeries object */ var ColumnSeries = extendClass(Series, { type: 'column', tooltipOutsidePlot: true, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color', r: 'borderRadius' }, /** * Initialize the series */ init: function () { Series.prototype.init.apply(this, arguments); var series = this, chart = series.chart; // if the series is added dynamically, force redraw of other // series affected by a new column if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } }, /** * Translate each point to the plot area coordinate system and find shape positions */ translate: function () { var series = this, chart = series.chart, options = series.options, stacking = options.stacking, borderWidth = options.borderWidth, columnCount = 0, xAxis = series.xAxis, yAxis = series.yAxis, reversedXAxis = xAxis.reversed, stackGroups = {}, stackKey, columnIndex; Series.prototype.translate.apply(series); // Get the total number of column type series. // This is called on every series. Consider moving this logic to a // chart.orderStacks() function and call it on init, addSeries and removeSeries if (options.grouping === false) { columnCount = 1; } else { each(chart.series, function (otherSeries) { var otherOptions = otherSeries.options; if (otherSeries.type === series.type && otherSeries.visible && series.options.group === otherOptions.group) { // used in Stock charts navigator series if (otherOptions.stacking) { stackKey = otherSeries.stackKey; if (stackGroups[stackKey] === UNDEFINED) { stackGroups[stackKey] = columnCount++; } columnIndex = stackGroups[stackKey]; } else if (otherOptions.grouping !== false) { // #1162 columnIndex = columnCount++; } otherSeries.columnIndex = columnIndex; } }); } // calculate the width and position of each column based on // the number of column series in the plot, the groupPadding // and the pointPadding options var points = series.points, categoryWidth = mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || 1), groupPadding = categoryWidth * options.groupPadding, groupWidth = categoryWidth - 2 * groupPadding, pointOffsetWidth = groupWidth / columnCount, optionPointWidth = options.pointWidth, pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 : pointOffsetWidth * options.pointPadding, pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts barW = mathCeil(mathMax(pointWidth, 1 + 2 * borderWidth)), // rounded and postprocessed for border width colIndex = (reversedXAxis ? columnCount - (series.columnIndex || 0) : // #1251 series.columnIndex) || 0, pointXOffset = pointPadding + (groupPadding + colIndex * pointOffsetWidth - (categoryWidth / 2)) * (reversedXAxis ? -1 : 1), threshold = options.threshold, translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5); // record the new values each(points, function (point) { var plotY = mathMin(mathMax(-999, point.plotY), yAxis.len + 999), // Don't draw too far outside plot area (#1303) yBottom = pick(point.yBottom, translatedThreshold), barX = point.plotX + pointXOffset, barY = mathCeil(mathMin(plotY, yBottom)), barH = mathCeil(mathMax(plotY, yBottom) - barY), stack = yAxis.stacks[(point.y < 0 ? '-' : '') + series.stackKey], shapeArgs; // Record the offset'ed position and width of the bar to be able to align the stacking total correctly if (stacking && series.visible && stack && stack[point.x]) { stack[point.x].setOffset(pointXOffset, barW); } // handle options.minPointLength if (mathAbs(barH) < minPointLength) { if (minPointLength) { barH = minPointLength; barY = mathAbs(barY - translatedThreshold) > minPointLength ? // stacked yBottom - minPointLength : // keep position translatedThreshold - (plotY <= translatedThreshold ? minPointLength : 0); } } point.barX = barX; point.pointWidth = pointWidth; // create shape type and shape args that are reused in drawPoints and drawTracker point.shapeType = 'rect'; point.shapeArgs = shapeArgs = chart.renderer.Element.prototype.crisp.call(0, borderWidth, barX, barY, barW, barH); if (borderWidth % 2) { // correct for shorting in crisp method, visible in stacked columns with 1px border shapeArgs.y -= 1; shapeArgs.height += 1; } // make small columns responsive to mouse point.trackerArgs = mathAbs(barH) < 3 && merge(point.shapeArgs, { height: 6, y: barY - 3 }); }); }, getSymbol: noop, /** * Use a solid rectangle like the area series types */ drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol, /** * Columns have no graph */ drawGraph: noop, /** * Draw the columns. For bars, the series.group is rotated, so the same coordinates * apply for columns and bars. This method is inherited by scatter series. * */ drawPoints: function () { var series = this, options = series.options, renderer = series.chart.renderer, shapeArgs; // draw the columns each(series.points, function (point) { var plotY = point.plotY, graphic = point.graphic; if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { shapeArgs = point.shapeArgs; if (graphic) { // update stop(graphic); graphic.animate(merge(shapeArgs)); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .attr(point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]) .add(series.group) .shadow(options.shadow, null, options.stacking && !options.borderRadius); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }); }, /** * Draw the individual tracker elements. * This method is inherited by pie charts too. */ drawTracker: function () { var series = this, chart = series.chart, renderer = chart.renderer, shapeArgs, tracker, trackerLabel = +new Date(), options = series.options, cursor = options.cursor, css = cursor && { cursor: cursor }, trackerGroup = series.isCartesian && series.plotGroup('trackerGroup', null, VISIBLE, options.zIndex || 1, chart.trackerGroup), rel, plotY, validPlotY, points = series.points, point, i = points.length, onMouseOver = function (event) { rel = event.relatedTarget || event.fromElement; if (chart.hoverSeries !== series && attr(rel, 'isTracker') !== trackerLabel) { series.onMouseOver(); } points[event.target._i].onMouseOver(); }, onMouseOut = function (event) { if (!options.stickyTracking) { rel = event.relatedTarget || event.toElement; if (attr(rel, 'isTracker') !== trackerLabel) { series.onMouseOut(); } } }; while (i--) { point = points[i]; tracker = point.tracker; shapeArgs = point.trackerArgs || point.shapeArgs; plotY = point.plotY; validPlotY = !series.isCartesian || (plotY !== UNDEFINED && !isNaN(plotY)); delete shapeArgs.strokeWidth; if (point.y !== null && validPlotY) { if (tracker) {// update tracker.attr(shapeArgs); } else { point.tracker = tracker = renderer[point.shapeType](shapeArgs) .attr({ isTracker: trackerLabel, fill: TRACKER_FILL, visibility: series.visible ? VISIBLE : HIDDEN }) .on('mouseover', onMouseOver) .on('mouseout', onMouseOut) .css(css) .add(point.group || trackerGroup); // pies have point group - see issue #118 if (hasTouch) { tracker.on('touchstart', onMouseOver); } } tracker.element._i = i; } } }, /** * Override the basic data label alignment by adjusting for the position of the column */ alignDataLabel: function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, below = point.below || (point.plotY > pick(this.translatedThreshold, chart.plotSizeY)), inside = (this.options.stacking || options.inside); // draw it inside the box? // Align to the column itself, or the top of it if (point.shapeArgs) { // Area range uses this method but not alignTo alignTo = merge(point.shapeArgs); if (inverted) { alignTo = { x: chart.plotWidth - alignTo.y - alignTo.height, y: chart.plotHeight - alignTo.x - alignTo.width, width: alignTo.height, height: alignTo.width }; } // Compute the alignment box if (!inside) { if (inverted) { alignTo.x += below ? 0 : alignTo.width; alignTo.width = 0; } else { alignTo.y += below ? alignTo.height : 0; alignTo.height = 0; } } } // When alignment is undefined (typically columns and bars), display the individual // point below or above the point depending on the threshold options.align = pick( options.align, !inverted || inside ? 'center' : below ? 'right' : 'left' ); options.verticalAlign = pick( options.verticalAlign, inverted || inside ? 'middle' : below ? 'top' : 'bottom' ); // Call the parent method Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew); }, /** * Animate the column heights one by one from zero * @param {Boolean} init Whether to initialize the animation or run it */ animate: function (init) { var series = this, points = series.points, options = series.options; if (!init) { // run the animation /* * Note: Ideally the animation should be initialized by calling * series.group.hide(), and then calling series.group.show() * after the animation was started. But this rendered the shadows * invisible in IE8 standards mode. If the columns flicker on large * datasets, this is the cause. */ each(points, function (point) { var graphic = point.graphic, shapeArgs = point.shapeArgs, yAxis = series.yAxis, threshold = options.threshold; if (graphic) { // start values graphic.attr({ height: 0, y: defined(threshold) ? yAxis.getThreshold(threshold) : yAxis.translate(yAxis.getExtremes().min, 0, 1, 0, 1) }); // animate graphic.animate({ height: shapeArgs.height, y: shapeArgs.y }, options.animation); } }); // delete this function to allow it only once series.animate = null; } }, /** * Remove this series from the chart */ remove: function () { var series = this, chart = series.chart; // column and bar series affects other series of the same type // as they are either stacked or grouped if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } Series.prototype.remove.apply(series, arguments); } }); seriesTypes.column = ColumnSeries; /** * Set the default options for bar */ defaultPlotOptions.bar = merge(defaultPlotOptions.column); /** * The Bar series class */ var BarSeries = extendClass(ColumnSeries, { type: 'bar', inverted: true }); seriesTypes.bar = BarSeries; /** * Set the default options for scatter */ defaultPlotOptions.scatter = merge(defaultSeriesOptions, { lineWidth: 0, states: { hover: { lineWidth: 0 } }, tooltip: { headerFormat: '<span style="font-size: 10px; color:{series.color}">{series.name}</span><br/>', pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>' } }); /** * The scatter series class */ var ScatterSeries = extendClass(Series, { type: 'scatter', sorted: false, requireSorting: false, /** * Extend the base Series' translate method by adding shape type and * arguments for the point trackers */ translate: function () { var series = this; Series.prototype.translate.apply(series); each(series.points, function (point) { point.shapeType = 'circle'; point.shapeArgs = { x: point.plotX, y: point.plotY, r: series.chart.options.tooltip.snap }; }); }, /** * Add tracking event listener to the series group, so the point graphics * themselves act as trackers */ drawTracker: function () { var series = this, cursor = series.options.cursor, css = cursor && { cursor: cursor }, points = series.points, i = points.length, graphic, markerGroup = series.markerGroup, onMouseOver = function (e) { series.onMouseOver(); if (e.target._i !== UNDEFINED) { // undefined on graph in scatterchart points[e.target._i].onMouseOver(); } }, onMouseOut = function () { if (!series.options.stickyTracking) { series.onMouseOut(); } }; // Set an expando property for the point index, used below while (i--) { graphic = points[i].graphic; if (graphic) { // doesn't exist for null points graphic.element._i = i; } } // Add the event listeners, we need to do this only once if (!series._hasTracking) { markerGroup .attr({ isTracker: true }) .on('mouseover', onMouseOver) .on('mouseout', onMouseOut) .css(css); if (hasTouch) { markerGroup.on('touchstart', onMouseOver); } } else { series._hasTracking = true; } }, setTooltipPoints: noop }); seriesTypes.scatter = ScatterSeries; /** * Set the default options for pie */ defaultPlotOptions.pie = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', borderWidth: 1, center: ['50%', '50%'], colorByPoint: true, // always true for pies dataLabels: { // align: null, // connectorWidth: 1, // connectorColor: point.color, // connectorPadding: 5, distance: 30, enabled: true, formatter: function () { return this.point.name; } // softConnector: true, //y: 0 }, //innerSize: 0, legendType: 'point', marker: null, // point options are specified in the base options size: '75%', showInLegend: false, slicedOffset: 10, states: { hover: { brightness: 0.1, shadow: false } } }); /** * Extended point object for pies */ var PiePoint = extendClass(Point, { /** * Initiate the pie slice */ init: function () { Point.prototype.init.apply(this, arguments); var point = this, toggleSlice; //visible: options.visible !== false, extend(point, { visible: point.visible !== false, name: pick(point.name, 'Slice') }); // add event listener for select toggleSlice = function () { point.slice(); }; addEvent(point, 'select', toggleSlice); addEvent(point, 'unselect', toggleSlice); return point; }, /** * Toggle the visibility of the pie slice * @param {Boolean} vis Whether to show the slice or not. If undefined, the * visibility is toggled */ setVisible: function (vis) { var point = this, series = point.series, chart = series.chart, tracker = point.tracker, dataLabel = point.dataLabel, connector = point.connector, shadowGroup = point.shadowGroup, method; // if called without an argument, toggle visibility point.visible = vis = vis === UNDEFINED ? !point.visible : vis; method = vis ? 'show' : 'hide'; point.group[method](); if (tracker) { tracker[method](); } if (dataLabel) { dataLabel[method](); } if (connector) { connector[method](); } if (shadowGroup) { shadowGroup[method](); } if (point.legendItem) { chart.legend.colorizeItem(point, vis); } // Handle ignore hidden slices if (!series.isDirty && series.options.ignoreHiddenPoint) { series.isDirty = true; chart.redraw(); } }, /** * Set or toggle whether the slice is cut out from the pie * @param {Boolean} sliced When undefined, the slice state is toggled * @param {Boolean} redraw Whether to redraw the chart. True by default. */ slice: function (sliced, redraw, animation) { var point = this, series = point.series, chart = series.chart, slicedTranslation = point.slicedTranslation, translation; setAnimation(animation, chart); // redraw is true by default redraw = pick(redraw, true); // if called without an argument, toggle sliced = point.sliced = defined(sliced) ? sliced : !point.sliced; translation = { translateX: (sliced ? slicedTranslation[0] : chart.plotLeft), translateY: (sliced ? slicedTranslation[1] : chart.plotTop) }; point.group.animate(translation); if (point.shadowGroup) { point.shadowGroup.animate(translation); } } }); /** * The Pie series class */ var PieSeries = { type: 'pie', isCartesian: false, pointClass: PiePoint, requireSorting: false, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color' }, /** * Pies have one color each point */ getColor: function () { // record first color for use in setData this.initialColor = this.chart.counters.color; }, /** * Animate the pies in */ animate: function () { var series = this, points = series.points, startAngleRad = series.startAngleRad; each(points, function (point) { var graphic = point.graphic, args = point.shapeArgs; if (graphic) { // start values graphic.attr({ r: series.center[3] / 2, // animate from inner radius (#779) start: startAngleRad, end: startAngleRad }); // animate graphic.animate({ r: args.r, start: args.start, end: args.end }, series.options.animation); } }); // delete this function to allow it only once series.animate = null; }, /** * Extend the basic setData method by running processData and generatePoints immediately, * in order to access the points from the legend. */ setData: function (data, redraw) { Series.prototype.setData.call(this, data, false); this.processData(); this.generatePoints(); if (pick(redraw, true)) { this.chart.redraw(); } }, /** * Get the center of the pie based on the size and center options relative to the * plot area. Borrowed by the polar and gauge series types. */ getCenter: function () { var options = this.options, chart = this.chart, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, positions = options.center.concat([options.size, options.innerSize || 0]), smallestSize = mathMin(plotWidth, plotHeight), isPercent; return map(positions, function (length, i) { isPercent = /%$/.test(length); return isPercent ? // i == 0: centerX, relative to width // i == 1: centerY, relative to height // i == 2: size, relative to smallestSize // i == 4: innerSize, relative to smallestSize [plotWidth, plotHeight, smallestSize, smallestSize][i] * pInt(length) / 100 : length; }); }, /** * Do translation for pie slices */ translate: function () { this.generatePoints(); var total = 0, series = this, cumulative = 0, precision = 1000, // issue #172 options = series.options, slicedOffset = options.slicedOffset, connectorOffset = slicedOffset + options.borderWidth, positions, chart = series.chart, start, end, angle, startAngleRad = series.startAngleRad = mathPI / 180 * ((options.startAngle || 0) % 360 - 90), points = series.points, circ = 2 * mathPI, fraction, radiusX, // the x component of the radius vector for a given point radiusY, labelDistance = options.dataLabels.distance, ignoreHiddenPoint = options.ignoreHiddenPoint, i, len = points.length, point; // get positions - either an integer or a percentage string must be given series.center = positions = series.getCenter(); // utility for getting the x value from a given y, used for anticollision logic in data labels series.getX = function (y, left) { angle = math.asin((y - positions[1]) / (positions[2] / 2 + labelDistance)); return positions[0] + (left ? -1 : 1) * (mathCos(angle) * (positions[2] / 2 + labelDistance)); }; // get the total sum for (i = 0; i < len; i++) { point = points[i]; total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y; } // Calculate the geometry for each point for (i = 0; i < len; i++) { point = points[i]; // set start and end angle fraction = total ? point.y / total : 0; start = mathRound((startAngleRad + (cumulative * circ)) * precision) / precision; if (!ignoreHiddenPoint || point.visible) { cumulative += fraction; } end = mathRound((startAngleRad + (cumulative * circ)) * precision) / precision; // set the shape point.shapeType = 'arc'; point.shapeArgs = { x: positions[0], y: positions[1], r: positions[2] / 2, innerR: positions[3] / 2, start: start, end: end }; // center for the sliced out slice angle = (end + start) / 2; if (angle > 0.75 * circ) { angle -= 2 * mathPI; } point.slicedTranslation = map([ mathCos(angle) * slicedOffset + chart.plotLeft, mathSin(angle) * slicedOffset + chart.plotTop ], mathRound); // set the anchor point for tooltips radiusX = mathCos(angle) * positions[2] / 2; radiusY = mathSin(angle) * positions[2] / 2; point.tooltipPos = [ positions[0] + radiusX * 0.7, positions[1] + radiusY * 0.7 ]; point.half = angle < circ / 4 ? 0 : 1; point.angle = angle; // set the anchor point for data labels point.labelPos = [ positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a positions[0] + radiusX, // landing point for connector positions[1] + radiusY, // a/a labelDistance < 0 ? // alignment 'center' : point.half ? 'right' : 'left', // alignment angle // center angle ]; // API properties point.percentage = fraction * 100; point.total = total; } this.setTooltipPoints(); }, /** * Render the slices */ render: function () { var series = this; // cache attributes for shapes series.getAttribs(); this.drawPoints(); // draw the mouse tracking area if (series.options.enableMouseTracking !== false) { series.drawTracker(); } this.drawDataLabels(); if (series.options.animation && series.animate) { series.animate(); } // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see series.isDirty = false; // means data is in accordance with what you see }, /** * Draw the data points */ drawPoints: function () { var series = this, chart = series.chart, renderer = chart.renderer, groupTranslation, //center, graphic, group, shadow = series.options.shadow, shadowGroup, shapeArgs; // draw the slices each(series.points, function (point) { graphic = point.graphic; shapeArgs = point.shapeArgs; group = point.group; shadowGroup = point.shadowGroup; // put the shadow behind all points if (shadow && !shadowGroup) { shadowGroup = point.shadowGroup = renderer.g('shadow') .attr({ zIndex: 4 }) .add(); } // create the group the first time if (!group) { group = point.group = renderer.g('point') .attr({ zIndex: 5 }) .add(); } // if the point is sliced, use special translation, else use plot area traslation groupTranslation = point.sliced ? point.slicedTranslation : [chart.plotLeft, chart.plotTop]; group.translate(groupTranslation[0], groupTranslation[1]); if (shadowGroup) { shadowGroup.translate(groupTranslation[0], groupTranslation[1]); } // draw the slice if (graphic) { graphic.animate(shapeArgs); } else { point.graphic = graphic = renderer.arc(shapeArgs) .setRadialReference(series.center) .attr(extend( point.pointAttr[NORMAL_STATE], { 'stroke-linejoin': 'round' } )) .add(point.group) .shadow(shadow, shadowGroup); } // detect point specific visibility if (point.visible === false) { point.setVisible(false); } }); }, /** * Override the base drawDataLabels method by pie specific functionality */ drawDataLabels: function () { var series = this, data = series.data, point, chart = series.chart, options = series.options.dataLabels, connectorPadding = pick(options.connectorPadding, 10), connectorWidth = pick(options.connectorWidth, 1), connector, connectorPath, softConnector = pick(options.softConnector, true), distanceOption = options.distance, seriesCenter = series.center, radius = seriesCenter[2] / 2, centerY = seriesCenter[1], outside = distanceOption > 0, dataLabel, labelPos, labelHeight, halves = [// divide the points into right and left halves for anti collision [], // right [] // left ], x, y, visibility, rankArr, i = 2, j, sort = function (a, b) { return b.y - a.y; }, sortByAngle = function (points, sign) { points.sort(function (a, b) { return (b.angle - a.angle) * sign; }); }; // get out if not enabled if (!options.enabled && !series._hasPointLabels) { return; } // run parent method Series.prototype.drawDataLabels.apply(series); // arrange points for detection collision each(data, function (point) { if (point.dataLabel) { // it may have been cancelled in the base method (#407) halves[point.half].push(point); } }); // assume equal label heights labelHeight = halves[0][0] && halves[0][0].dataLabel && (halves[0][0].dataLabel.getBBox().height || 21); // 21 is for #968 /* Loop over the points in each half, starting from the top and bottom * of the pie to detect overlapping labels. */ while (i--) { var slots = [], slotsLength, usedSlots = [], points = halves[i], pos, length = points.length, slotIndex; // Sort by angle sortByAngle(points, i - 0.5); // Only do anti-collision when we are outside the pie and have connectors (#856) if (distanceOption > 0) { // build the slots for (pos = centerY - radius - distanceOption; pos <= centerY + radius + distanceOption; pos += labelHeight) { slots.push(pos); // visualize the slot /* var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0), slotY = pos + chart.plotTop; if (!isNaN(slotX)) { chart.renderer.rect(slotX, slotY - 7, 100, labelHeight) .attr({ 'stroke-width': 1, stroke: 'silver' }) .add(); chart.renderer.text('Slot '+ (slots.length - 1), slotX, slotY + 4) .attr({ fill: 'silver' }).add(); } // */ } slotsLength = slots.length; // if there are more values than available slots, remove lowest values if (length > slotsLength) { // create an array for sorting and ranking the points within each quarter rankArr = [].concat(points); rankArr.sort(sort); j = length; while (j--) { rankArr[j].rank = j; } j = length; while (j--) { if (points[j].rank >= slotsLength) { points.splice(j, 1); } } length = points.length; } // The label goes to the nearest open slot, but not closer to the edge than // the label's index. for (j = 0; j < length; j++) { point = points[j]; labelPos = point.labelPos; var closest = 9999, distance, slotI; // find the closest slot index for (slotI = 0; slotI < slotsLength; slotI++) { distance = mathAbs(slots[slotI] - labelPos[1]); if (distance < closest) { closest = distance; slotIndex = slotI; } } // if that slot index is closer to the edges of the slots, move it // to the closest appropriate slot if (slotIndex < j && slots[j] !== null) { // cluster at the top slotIndex = j; } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom slotIndex = slotsLength - length + j; while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } else { // Slot is taken, find next free slot below. In the next run, the next slice will find the // slot above these, because it is the closest one while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } usedSlots.push({ i: slotIndex, y: slots[slotIndex] }); slots[slotIndex] = null; // mark as taken } // sort them in order to fill in from the top usedSlots.sort(sort); } // now the used slots are sorted, fill them up sequentially for (j = 0; j < length; j++) { var slot, naturalY; point = points[j]; labelPos = point.labelPos; dataLabel = point.dataLabel; visibility = point.visible === false ? HIDDEN : VISIBLE; naturalY = labelPos[1]; if (distanceOption > 0) { slot = usedSlots.pop(); slotIndex = slot.i; // if the slot next to currrent slot is free, the y value is allowed // to fall back to the natural position y = slot.y; if ((naturalY > y && slots[slotIndex + 1] !== null) || (naturalY < y && slots[slotIndex - 1] !== null)) { y = naturalY; } } else { y = naturalY; } // get the x - use the natural x position for first and last slot, to prevent the top // and botton slice connectors from touching each other on either side x = options.justify ? seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) : series.getX(slotIndex === 0 || slotIndex === slots.length - 1 ? naturalY : y, i); // move or place the data label dataLabel .attr({ visibility: visibility, align: labelPos[6] })[dataLabel.moved ? 'animate' : 'attr']({ x: x + options.x + ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0), y: y + options.y - 10 // 10 is for the baseline (label vs text) }); dataLabel.moved = true; // draw the connector if (outside && connectorWidth) { connector = point.connector; connectorPath = softConnector ? [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label 'C', x, y, // first break, next to the label 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5], labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ] : [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label L, labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ]; if (connector) { connector.animate({ d: connectorPath }); connector.attr('visibility', visibility); } else { point.connector = connector = series.chart.renderer.path(connectorPath).attr({ 'stroke-width': connectorWidth, stroke: options.connectorColor || point.color || '#606060', visibility: visibility, zIndex: 3 }) .translate(chart.plotLeft, chart.plotTop) .add(); } } } } }, alignDataLabel: noop, /** * Draw point specific tracker objects. Inherit directly from column series. */ drawTracker: ColumnSeries.prototype.drawTracker, /** * Use a simple symbol from column prototype */ drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol, /** * Pies don't have point marker symbols */ getSymbol: function () {} }; PieSeries = extendClass(Series, PieSeries); seriesTypes.pie = PieSeries; // global variables extend(Highcharts, { // Constructors Axis: Axis, CanVGRenderer: CanVGRenderer, Chart: Chart, Color: Color, Legend: Legend, MouseTracker: MouseTracker, Point: Point, Tick: Tick, Tooltip: Tooltip, Renderer: Renderer, Series: Series, SVGRenderer: SVGRenderer, VMLRenderer: VMLRenderer, // Various arrayMin: arrayMin, arrayMax: arrayMax, charts: charts, dateFormat: dateFormat, pathAnim: pathAnim, getOptions: getOptions, hasBidiBug: hasBidiBug, isTouchDevice: isTouchDevice, numberFormat: numberFormat, seriesTypes: seriesTypes, setOptions: setOptions, addEvent: addEvent, removeEvent: removeEvent, createElement: createElement, discardElement: discardElement, css: css, each: each, extend: extend, map: map, merge: merge, pick: pick, splat: splat, extendClass: extendClass, pInt: pInt, wrap: wrap, svg: hasSVG, canvas: useCanVG, vml: !hasSVG && !useCanVG, product: 'Highcharts', version: '2.3.5' }); }());
JavaScript
/** * @license Highcharts JS v2.3.5 (2012-12-19) * MooTools adapter * * (c) 2010-2011 Torstein Hønsi * * License: www.highcharts.com/license */ // JSLint options: /*global Fx, $, $extend, $each, $merge, Events, Event, DOMEvent */ (function () { var win = window, doc = document, mooVersion = win.MooTools.version.substring(0, 3), // Get the first three characters of the version number legacy = mooVersion === '1.2' || mooVersion === '1.1', // 1.1 && 1.2 considered legacy, 1.3 is not. legacyEvent = legacy || mooVersion === '1.3', // In versions 1.1 - 1.3 the event class is named Event, in newer versions it is named DOMEvent. $extend = win.$extend || function () { return Object.append.apply(Object, arguments); }; win.HighchartsAdapter = { /** * Initialize the adapter. This is run once as Highcharts is first run. * @param {Object} pathAnim The helper object to do animations across adapters. */ init: function (pathAnim) { var fxProto = Fx.prototype, fxStart = fxProto.start, morphProto = Fx.Morph.prototype, morphCompute = morphProto.compute; // override Fx.start to allow animation of SVG element wrappers /*jslint unparam: true*//* allow unused parameters in fx functions */ fxProto.start = function (from, to) { var fx = this, elem = fx.element; // special for animating paths if (from.d) { //this.fromD = this.element.d.split(' '); fx.paths = pathAnim.init( elem, elem.d, fx.toD ); } fxStart.apply(fx, arguments); return this; // chainable }; // override Fx.step to allow animation of SVG element wrappers morphProto.compute = function (from, to, delta) { var fx = this, paths = fx.paths; if (paths) { fx.element.attr( 'd', pathAnim.step(paths[0], paths[1], delta, fx.toD) ); } else { return morphCompute.apply(fx, arguments); } }; /*jslint unparam: false*/ }, /** * Run a general method on the framework, following jQuery syntax * @param {Object} el The HTML element * @param {String} method Which method to run on the wrapped element */ adapterRun: function (el, method) { // This currently works for getting inner width and height. If adding // more methods later, we need a conditional implementation for each. if (method === 'width' || method === 'height') { return parseInt($(el).getStyle(method), 10); } }, /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ getScript: function (scriptLocation, callback) { // We cannot assume that Assets class from mootools-more is available so instead insert a script tag to download script. var head = doc.getElementsByTagName('head')[0]; var script = doc.createElement('script'); script.type = 'text/javascript'; script.src = scriptLocation; script.onload = callback; head.appendChild(script); }, /** * Animate a HTML element or SVG element wrapper * @param {Object} el * @param {Object} params * @param {Object} options jQuery-like animation options: duration, easing, callback */ animate: function (el, params, options) { var isSVGElement = el.attr, effect, complete = options && options.complete; if (isSVGElement && !el.setStyle) { // add setStyle and getStyle methods for internal use in Moo el.getStyle = el.attr; el.setStyle = function () { // property value is given as array in Moo - break it down var args = arguments; this.attr.call(this, args[0], args[1][0]); }; // dirty hack to trick Moo into handling el as an element wrapper el.$family = function () { return true; }; } // stop running animations win.HighchartsAdapter.stop(el); // define and run the effect effect = new Fx.Morph( isSVGElement ? el : $(el), $extend({ transition: Fx.Transitions.Quad.easeInOut }, options) ); // Make sure that the element reference is set when animating svg elements if (isSVGElement) { effect.element = el; } // special treatment for paths if (params.d) { effect.toD = params.d; } // jQuery-like events if (complete) { effect.addEvent('complete', complete); } // run effect.start(params); // record for use in stop method el.fx = effect; }, /** * MooTool's each function * */ each: function (arr, fn) { return legacy ? $each(arr, fn) : Array.each(arr, fn); }, /** * Map an array * @param {Array} arr * @param {Function} fn */ map: function (arr, fn) { return arr.map(fn); }, /** * Grep or filter an array * @param {Array} arr * @param {Function} fn */ grep: function (arr, fn) { return arr.filter(fn); }, /** * Return the index of an item in an array, or -1 if not matched */ inArray: function (item, arr, from) { return arr.indexOf(item, from); }, /** * Deep merge two objects and return a third */ merge: function () { var args = arguments, args13 = [{}], // MooTools 1.3+ i = args.length, ret; if (legacy) { ret = $merge.apply(null, args); } else { while (i--) { // Boolean argumens should not be merged. // JQuery explicitly skips this, so we do it here as well. if (typeof args[i] !== 'boolean') { args13[i + 1] = args[i]; } } ret = Object.merge.apply(Object, args13); } return ret; }, /** * Get the offset of an element relative to the top left corner of the web page */ offset: function (el) { var offsets = $(el).getOffsets(); return { left: offsets.x, top: offsets.y }; }, /** * Extends an object with Events, if its not done */ extendWithEvents: function (el) { // if the addEvent method is not defined, el is a custom Highcharts object // like series or point if (!el.addEvent) { if (el.nodeName) { el = $(el); // a dynamically generated node } else { $extend(el, new Events()); // a custom object } } }, /** * Add an event listener * @param {Object} el HTML element or custom object * @param {String} type Event type * @param {Function} fn Event handler */ addEvent: function (el, type, fn) { if (typeof type === 'string') { // chart broke due to el being string, type function if (type === 'unload') { // Moo self destructs before custom unload events type = 'beforeunload'; } win.HighchartsAdapter.extendWithEvents(el); el.addEvent(type, fn); } }, removeEvent: function (el, type, fn) { if (typeof el === 'string') { // el.removeEvents below apperantly calls this method again. Do not quite understand why, so for now just bail out. return; } if (el.addEvent) { // If el doesn't have an addEvent method, there are no events to remove if (type) { if (type === 'unload') { // Moo self destructs before custom unload events type = 'beforeunload'; } if (fn) { el.removeEvent(type, fn); } else if (el.removeEvents) { // #958 el.removeEvents(type); } } else { el.removeEvents(); } } }, fireEvent: function (el, event, eventArguments, defaultFunction) { var eventArgs = { type: event, target: el }; // create an event object that keeps all functions event = legacyEvent ? new Event(eventArgs) : new DOMEvent(eventArgs); event = $extend(event, eventArguments); // override the preventDefault function to be able to use // this for custom events event.preventDefault = function () { defaultFunction = null; }; // if fireEvent is not available on the object, there hasn't been added // any events to it above if (el.fireEvent) { el.fireEvent(event.type, event); } // fire the default if it is passed and it is not prevented above if (defaultFunction) { defaultFunction(event); } }, /** * Set back e.pageX and e.pageY that MooTools has abstracted away */ washMouseEvent: function (e) { return e.event || e; }, /** * Stop running animations on the object */ stop: function (el) { if (el.fx) { el.fx.cancel(); } } }; }());
JavaScript
/** * @license A class to parse color values * @author Stoyan Stefanov <sstoo@gmail.com> * @link http://www.phpied.com/rgb-color-parser-in-javascript/ * Use it if you like it * */ function RGBColor(color_string) { this.ok = false; // strip any leading # if (color_string.charAt(0) == '#') { // remove # if any color_string = color_string.substr(1,6); } color_string = color_string.replace(/ /g,''); color_string = color_string.toLowerCase(); // before getting into regexps, try simple matches // and overwrite the input var simple_colors = { aliceblue: 'f0f8ff', antiquewhite: 'faebd7', aqua: '00ffff', aquamarine: '7fffd4', azure: 'f0ffff', beige: 'f5f5dc', bisque: 'ffe4c4', black: '000000', blanchedalmond: 'ffebcd', blue: '0000ff', blueviolet: '8a2be2', brown: 'a52a2a', burlywood: 'deb887', cadetblue: '5f9ea0', chartreuse: '7fff00', chocolate: 'd2691e', coral: 'ff7f50', cornflowerblue: '6495ed', cornsilk: 'fff8dc', crimson: 'dc143c', cyan: '00ffff', darkblue: '00008b', darkcyan: '008b8b', darkgoldenrod: 'b8860b', darkgray: 'a9a9a9', darkgreen: '006400', darkkhaki: 'bdb76b', darkmagenta: '8b008b', darkolivegreen: '556b2f', darkorange: 'ff8c00', darkorchid: '9932cc', darkred: '8b0000', darksalmon: 'e9967a', darkseagreen: '8fbc8f', darkslateblue: '483d8b', darkslategray: '2f4f4f', darkturquoise: '00ced1', darkviolet: '9400d3', deeppink: 'ff1493', deepskyblue: '00bfff', dimgray: '696969', dodgerblue: '1e90ff', feldspar: 'd19275', firebrick: 'b22222', floralwhite: 'fffaf0', forestgreen: '228b22', fuchsia: 'ff00ff', gainsboro: 'dcdcdc', ghostwhite: 'f8f8ff', gold: 'ffd700', goldenrod: 'daa520', gray: '808080', green: '008000', greenyellow: 'adff2f', honeydew: 'f0fff0', hotpink: 'ff69b4', indianred : 'cd5c5c', indigo : '4b0082', ivory: 'fffff0', khaki: 'f0e68c', lavender: 'e6e6fa', lavenderblush: 'fff0f5', lawngreen: '7cfc00', lemonchiffon: 'fffacd', lightblue: 'add8e6', lightcoral: 'f08080', lightcyan: 'e0ffff', lightgoldenrodyellow: 'fafad2', lightgrey: 'd3d3d3', lightgreen: '90ee90', lightpink: 'ffb6c1', lightsalmon: 'ffa07a', lightseagreen: '20b2aa', lightskyblue: '87cefa', lightslateblue: '8470ff', lightslategray: '778899', lightsteelblue: 'b0c4de', lightyellow: 'ffffe0', lime: '00ff00', limegreen: '32cd32', linen: 'faf0e6', magenta: 'ff00ff', maroon: '800000', mediumaquamarine: '66cdaa', mediumblue: '0000cd', mediumorchid: 'ba55d3', mediumpurple: '9370d8', mediumseagreen: '3cb371', mediumslateblue: '7b68ee', mediumspringgreen: '00fa9a', mediumturquoise: '48d1cc', mediumvioletred: 'c71585', midnightblue: '191970', mintcream: 'f5fffa', mistyrose: 'ffe4e1', moccasin: 'ffe4b5', navajowhite: 'ffdead', navy: '000080', oldlace: 'fdf5e6', olive: '808000', olivedrab: '6b8e23', orange: 'ffa500', orangered: 'ff4500', orchid: 'da70d6', palegoldenrod: 'eee8aa', palegreen: '98fb98', paleturquoise: 'afeeee', palevioletred: 'd87093', papayawhip: 'ffefd5', peachpuff: 'ffdab9', peru: 'cd853f', pink: 'ffc0cb', plum: 'dda0dd', powderblue: 'b0e0e6', purple: '800080', red: 'ff0000', rosybrown: 'bc8f8f', royalblue: '4169e1', saddlebrown: '8b4513', salmon: 'fa8072', sandybrown: 'f4a460', seagreen: '2e8b57', seashell: 'fff5ee', sienna: 'a0522d', silver: 'c0c0c0', skyblue: '87ceeb', slateblue: '6a5acd', slategray: '708090', snow: 'fffafa', springgreen: '00ff7f', steelblue: '4682b4', tan: 'd2b48c', teal: '008080', thistle: 'd8bfd8', tomato: 'ff6347', turquoise: '40e0d0', violet: 'ee82ee', violetred: 'd02090', wheat: 'f5deb3', white: 'ffffff', whitesmoke: 'f5f5f5', yellow: 'ffff00', yellowgreen: '9acd32' }; for (var key in simple_colors) { if (color_string == key) { color_string = simple_colors[key]; } } // emd of simple type-in colors // array of color definition objects var color_defs = [ { re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/, example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'], process: function (bits){ return [ parseInt(bits[1]), parseInt(bits[2]), parseInt(bits[3]) ]; } }, { re: /^(\w{2})(\w{2})(\w{2})$/, example: ['#00ff00', '336699'], process: function (bits){ return [ parseInt(bits[1], 16), parseInt(bits[2], 16), parseInt(bits[3], 16) ]; } }, { re: /^(\w{1})(\w{1})(\w{1})$/, example: ['#fb0', 'f0f'], process: function (bits){ return [ parseInt(bits[1] + bits[1], 16), parseInt(bits[2] + bits[2], 16), parseInt(bits[3] + bits[3], 16) ]; } } ]; // search through the definitions to find a match for (var i = 0; i < color_defs.length; i++) { var re = color_defs[i].re; var processor = color_defs[i].process; var bits = re.exec(color_string); if (bits) { channels = processor(bits); this.r = channels[0]; this.g = channels[1]; this.b = channels[2]; this.ok = true; } } // validate/cleanup values this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r); this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g); this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b); // some getters this.toRGB = function () { return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')'; } this.toHex = function () { var r = this.r.toString(16); var g = this.g.toString(16); var b = this.b.toString(16); if (r.length == 1) r = '0' + r; if (g.length == 1) g = '0' + g; if (b.length == 1) b = '0' + b; return '#' + r + g + b; } // help this.getHelpXML = function () { var examples = new Array(); // add regexps for (var i = 0; i < color_defs.length; i++) { var example = color_defs[i].example; for (var j = 0; j < example.length; j++) { examples[examples.length] = example[j]; } } // add type-in colors for (var sc in simple_colors) { examples[examples.length] = sc; } var xml = document.createElement('ul'); xml.setAttribute('id', 'rgbcolor-examples'); for (var i = 0; i < examples.length; i++) { try { var list_item = document.createElement('li'); var list_color = new RGBColor(examples[i]); var example_div = document.createElement('div'); example_div.style.cssText = 'margin: 3px; ' + 'border: 1px solid black; ' + 'background:' + list_color.toHex() + '; ' + 'color:' + list_color.toHex() ; example_div.appendChild(document.createTextNode('test')); var list_item_value = document.createTextNode( ' ' + examples[i] + ' -> ' + list_color.toRGB() + ' -> ' + list_color.toHex() ); list_item.appendChild(example_div); list_item.appendChild(list_item_value); xml.appendChild(list_item); } catch(e){} } return xml; } } /** * @license canvg.js - Javascript SVG parser and renderer on Canvas * MIT Licensed * Gabe Lerner (gabelerner@gmail.com) * http://code.google.com/p/canvg/ * * Requires: rgbcolor.js - http://www.phpied.com/rgb-color-parser-in-javascript/ * */ if(!window.console) { window.console = {}; window.console.log = function(str) {}; window.console.dir = function(str) {}; } if(!Array.prototype.indexOf){ Array.prototype.indexOf = function(obj){ for(var i=0; i<this.length; i++){ if(this[i]==obj){ return i; } } return -1; } } (function(){ // canvg(target, s) // empty parameters: replace all 'svg' elements on page with 'canvas' elements // target: canvas element or the id of a canvas element // s: svg string, url to svg file, or xml document // opts: optional hash of options // ignoreMouse: true => ignore mouse events // ignoreAnimation: true => ignore animations // ignoreDimensions: true => does not try to resize canvas // ignoreClear: true => does not clear canvas // offsetX: int => draws at a x offset // offsetY: int => draws at a y offset // scaleWidth: int => scales horizontally to width // scaleHeight: int => scales vertically to height // renderCallback: function => will call the function after the first render is completed // forceRedraw: function => will call the function on every frame, if it returns true, will redraw this.canvg = function (target, s, opts) { // no parameters if (target == null && s == null && opts == null) { var svgTags = document.getElementsByTagName('svg'); for (var i=0; i<svgTags.length; i++) { var svgTag = svgTags[i]; var c = document.createElement('canvas'); c.width = svgTag.clientWidth; c.height = svgTag.clientHeight; svgTag.parentNode.insertBefore(c, svgTag); svgTag.parentNode.removeChild(svgTag); var div = document.createElement('div'); div.appendChild(svgTag); canvg(c, div.innerHTML); } return; } opts = opts || {}; if (typeof target == 'string') { target = document.getElementById(target); } // reuse class per canvas var svg; if (target.svg == null) { svg = build(); target.svg = svg; } else { svg = target.svg; svg.stop(); } svg.opts = opts; var ctx = target.getContext('2d'); if (typeof(s.documentElement) != 'undefined') { // load from xml doc svg.loadXmlDoc(ctx, s); } else if (s.substr(0,1) == '<') { // load from xml string svg.loadXml(ctx, s); } else { // load from url svg.load(ctx, s); } } function build() { var svg = { }; svg.FRAMERATE = 30; svg.MAX_VIRTUAL_PIXELS = 30000; // globals svg.init = function(ctx) { svg.Definitions = {}; svg.Styles = {}; svg.Animations = []; svg.Images = []; svg.ctx = ctx; svg.ViewPort = new (function () { this.viewPorts = []; this.Clear = function() { this.viewPorts = []; } this.SetCurrent = function(width, height) { this.viewPorts.push({ width: width, height: height }); } this.RemoveCurrent = function() { this.viewPorts.pop(); } this.Current = function() { return this.viewPorts[this.viewPorts.length - 1]; } this.width = function() { return this.Current().width; } this.height = function() { return this.Current().height; } this.ComputeSize = function(d) { if (d != null && typeof(d) == 'number') return d; if (d == 'x') return this.width(); if (d == 'y') return this.height(); return Math.sqrt(Math.pow(this.width(), 2) + Math.pow(this.height(), 2)) / Math.sqrt(2); } }); } svg.init(); // images loaded svg.ImagesLoaded = function() { for (var i=0; i<svg.Images.length; i++) { if (!svg.Images[i].loaded) return false; } return true; } // trim svg.trim = function(s) { return s.replace(/^\s+|\s+$/g, ''); } // compress spaces svg.compressSpaces = function(s) { return s.replace(/[\s\r\t\n]+/gm,' '); } // ajax svg.ajax = function(url) { var AJAX; if(window.XMLHttpRequest){AJAX=new XMLHttpRequest();} else{AJAX=new ActiveXObject('Microsoft.XMLHTTP');} if(AJAX){ AJAX.open('GET',url,false); AJAX.send(null); return AJAX.responseText; } return null; } // parse xml svg.parseXml = function(xml) { if (window.DOMParser) { var parser = new DOMParser(); return parser.parseFromString(xml, 'text/xml'); } else { xml = xml.replace(/<!DOCTYPE svg[^>]*>/, ''); var xmlDoc = new ActiveXObject('Microsoft.XMLDOM'); xmlDoc.async = 'false'; xmlDoc.loadXML(xml); return xmlDoc; } } svg.Property = function(name, value) { this.name = name; this.value = value; this.hasValue = function() { return (this.value != null && this.value !== ''); } // return the numerical value of the property this.numValue = function() { if (!this.hasValue()) return 0; var n = parseFloat(this.value); if ((this.value + '').match(/%$/)) { n = n / 100.0; } return n; } this.valueOrDefault = function(def) { if (this.hasValue()) return this.value; return def; } this.numValueOrDefault = function(def) { if (this.hasValue()) return this.numValue(); return def; } /* EXTENSIONS */ var that = this; // color extensions this.Color = { // augment the current color value with the opacity addOpacity: function(opacity) { var newValue = that.value; if (opacity != null && opacity != '') { var color = new RGBColor(that.value); if (color.ok) { newValue = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + opacity + ')'; } } return new svg.Property(that.name, newValue); } } // definition extensions this.Definition = { // get the definition from the definitions table getDefinition: function() { var name = that.value.replace(/^(url\()?#([^\)]+)\)?$/, '$2'); return svg.Definitions[name]; }, isUrl: function() { return that.value.indexOf('url(') == 0 }, getFillStyle: function(e) { var def = this.getDefinition(); // gradient if (def != null && def.createGradient) { return def.createGradient(svg.ctx, e); } // pattern if (def != null && def.createPattern) { return def.createPattern(svg.ctx, e); } return null; } } // length extensions this.Length = { DPI: function(viewPort) { return 96.0; // TODO: compute? }, EM: function(viewPort) { var em = 12; var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize); if (fontSize.hasValue()) em = fontSize.Length.toPixels(viewPort); return em; }, // get the length as pixels toPixels: function(viewPort) { if (!that.hasValue()) return 0; var s = that.value+''; if (s.match(/em$/)) return that.numValue() * this.EM(viewPort); if (s.match(/ex$/)) return that.numValue() * this.EM(viewPort) / 2.0; if (s.match(/px$/)) return that.numValue(); if (s.match(/pt$/)) return that.numValue() * 1.25; if (s.match(/pc$/)) return that.numValue() * 15; if (s.match(/cm$/)) return that.numValue() * this.DPI(viewPort) / 2.54; if (s.match(/mm$/)) return that.numValue() * this.DPI(viewPort) / 25.4; if (s.match(/in$/)) return that.numValue() * this.DPI(viewPort); if (s.match(/%$/)) return that.numValue() * svg.ViewPort.ComputeSize(viewPort); return that.numValue(); } } // time extensions this.Time = { // get the time as milliseconds toMilliseconds: function() { if (!that.hasValue()) return 0; var s = that.value+''; if (s.match(/s$/)) return that.numValue() * 1000; if (s.match(/ms$/)) return that.numValue(); return that.numValue(); } } // angle extensions this.Angle = { // get the angle as radians toRadians: function() { if (!that.hasValue()) return 0; var s = that.value+''; if (s.match(/deg$/)) return that.numValue() * (Math.PI / 180.0); if (s.match(/grad$/)) return that.numValue() * (Math.PI / 200.0); if (s.match(/rad$/)) return that.numValue(); return that.numValue() * (Math.PI / 180.0); } } } // fonts svg.Font = new (function() { this.Styles = ['normal','italic','oblique','inherit']; this.Variants = ['normal','small-caps','inherit']; this.Weights = ['normal','bold','bolder','lighter','100','200','300','400','500','600','700','800','900','inherit']; this.CreateFont = function(fontStyle, fontVariant, fontWeight, fontSize, fontFamily, inherit) { var f = inherit != null ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font); return { fontFamily: fontFamily || f.fontFamily, fontSize: fontSize || f.fontSize, fontStyle: fontStyle || f.fontStyle, fontWeight: fontWeight || f.fontWeight, fontVariant: fontVariant || f.fontVariant, toString: function () { return [this.fontStyle, this.fontVariant, this.fontWeight, this.fontSize, this.fontFamily].join(' ') } } } var that = this; this.Parse = function(s) { var f = {}; var d = svg.trim(svg.compressSpaces(s || '')).split(' '); var set = { fontSize: false, fontStyle: false, fontWeight: false, fontVariant: false } var ff = ''; for (var i=0; i<d.length; i++) { if (!set.fontStyle && that.Styles.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontStyle = d[i]; set.fontStyle = true; } else if (!set.fontVariant && that.Variants.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontVariant = d[i]; set.fontStyle = set.fontVariant = true; } else if (!set.fontWeight && that.Weights.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontWeight = d[i]; set.fontStyle = set.fontVariant = set.fontWeight = true; } else if (!set.fontSize) { if (d[i] != 'inherit') f.fontSize = d[i].split('/')[0]; set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true; } else { if (d[i] != 'inherit') ff += d[i]; } } if (ff != '') f.fontFamily = ff; return f; } }); // points and paths svg.ToNumberArray = function(s) { var a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' '); for (var i=0; i<a.length; i++) { a[i] = parseFloat(a[i]); } return a; } svg.Point = function(x, y) { this.x = x; this.y = y; this.angleTo = function(p) { return Math.atan2(p.y - this.y, p.x - this.x); } this.applyTransform = function(v) { var xp = this.x * v[0] + this.y * v[2] + v[4]; var yp = this.x * v[1] + this.y * v[3] + v[5]; this.x = xp; this.y = yp; } } svg.CreatePoint = function(s) { var a = svg.ToNumberArray(s); return new svg.Point(a[0], a[1]); } svg.CreatePath = function(s) { var a = svg.ToNumberArray(s); var path = []; for (var i=0; i<a.length; i+=2) { path.push(new svg.Point(a[i], a[i+1])); } return path; } // bounding box svg.BoundingBox = function(x1, y1, x2, y2) { // pass in initial points if you want this.x1 = Number.NaN; this.y1 = Number.NaN; this.x2 = Number.NaN; this.y2 = Number.NaN; this.x = function() { return this.x1; } this.y = function() { return this.y1; } this.width = function() { return this.x2 - this.x1; } this.height = function() { return this.y2 - this.y1; } this.addPoint = function(x, y) { if (x != null) { if (isNaN(this.x1) || isNaN(this.x2)) { this.x1 = x; this.x2 = x; } if (x < this.x1) this.x1 = x; if (x > this.x2) this.x2 = x; } if (y != null) { if (isNaN(this.y1) || isNaN(this.y2)) { this.y1 = y; this.y2 = y; } if (y < this.y1) this.y1 = y; if (y > this.y2) this.y2 = y; } } this.addX = function(x) { this.addPoint(x, null); } this.addY = function(y) { this.addPoint(null, y); } this.addBoundingBox = function(bb) { this.addPoint(bb.x1, bb.y1); this.addPoint(bb.x2, bb.y2); } this.addQuadraticCurve = function(p0x, p0y, p1x, p1y, p2x, p2y) { var cp1x = p0x + 2/3 * (p1x - p0x); // CP1 = QP0 + 2/3 *(QP1-QP0) var cp1y = p0y + 2/3 * (p1y - p0y); // CP1 = QP0 + 2/3 *(QP1-QP0) var cp2x = cp1x + 1/3 * (p2x - p0x); // CP2 = CP1 + 1/3 *(QP2-QP0) var cp2y = cp1y + 1/3 * (p2y - p0y); // CP2 = CP1 + 1/3 *(QP2-QP0) this.addBezierCurve(p0x, p0y, cp1x, cp2x, cp1y, cp2y, p2x, p2y); } this.addBezierCurve = function(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) { // from http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html var p0 = [p0x, p0y], p1 = [p1x, p1y], p2 = [p2x, p2y], p3 = [p3x, p3y]; this.addPoint(p0[0], p0[1]); this.addPoint(p3[0], p3[1]); for (i=0; i<=1; i++) { var f = function(t) { return Math.pow(1-t, 3) * p0[i] + 3 * Math.pow(1-t, 2) * t * p1[i] + 3 * (1-t) * Math.pow(t, 2) * p2[i] + Math.pow(t, 3) * p3[i]; } var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]; var c = 3 * p1[i] - 3 * p0[i]; if (a == 0) { if (b == 0) continue; var t = -c / b; if (0 < t && t < 1) { if (i == 0) this.addX(f(t)); if (i == 1) this.addY(f(t)); } continue; } var b2ac = Math.pow(b, 2) - 4 * c * a; if (b2ac < 0) continue; var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); if (0 < t1 && t1 < 1) { if (i == 0) this.addX(f(t1)); if (i == 1) this.addY(f(t1)); } var t2 = (-b - Math.sqrt(b2ac)) / (2 * a); if (0 < t2 && t2 < 1) { if (i == 0) this.addX(f(t2)); if (i == 1) this.addY(f(t2)); } } } this.isPointInBox = function(x, y) { return (this.x1 <= x && x <= this.x2 && this.y1 <= y && y <= this.y2); } this.addPoint(x1, y1); this.addPoint(x2, y2); } // transforms svg.Transform = function(v) { var that = this; this.Type = {} // translate this.Type.translate = function(s) { this.p = svg.CreatePoint(s); this.apply = function(ctx) { ctx.translate(this.p.x || 0.0, this.p.y || 0.0); } this.applyToPoint = function(p) { p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]); } } // rotate this.Type.rotate = function(s) { var a = svg.ToNumberArray(s); this.angle = new svg.Property('angle', a[0]); this.cx = a[1] || 0; this.cy = a[2] || 0; this.apply = function(ctx) { ctx.translate(this.cx, this.cy); ctx.rotate(this.angle.Angle.toRadians()); ctx.translate(-this.cx, -this.cy); } this.applyToPoint = function(p) { var a = this.angle.Angle.toRadians(); p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]); p.applyTransform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]); p.applyTransform([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]); } } this.Type.scale = function(s) { this.p = svg.CreatePoint(s); this.apply = function(ctx) { ctx.scale(this.p.x || 1.0, this.p.y || this.p.x || 1.0); } this.applyToPoint = function(p) { p.applyTransform([this.p.x || 0.0, 0, 0, this.p.y || 0.0, 0, 0]); } } this.Type.matrix = function(s) { this.m = svg.ToNumberArray(s); this.apply = function(ctx) { ctx.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]); } this.applyToPoint = function(p) { p.applyTransform(this.m); } } this.Type.SkewBase = function(s) { this.base = that.Type.matrix; this.base(s); this.angle = new svg.Property('angle', s); } this.Type.SkewBase.prototype = new this.Type.matrix; this.Type.skewX = function(s) { this.base = that.Type.SkewBase; this.base(s); this.m = [1, 0, Math.tan(this.angle.Angle.toRadians()), 1, 0, 0]; } this.Type.skewX.prototype = new this.Type.SkewBase; this.Type.skewY = function(s) { this.base = that.Type.SkewBase; this.base(s); this.m = [1, Math.tan(this.angle.Angle.toRadians()), 0, 1, 0, 0]; } this.Type.skewY.prototype = new this.Type.SkewBase; this.transforms = []; this.apply = function(ctx) { for (var i=0; i<this.transforms.length; i++) { this.transforms[i].apply(ctx); } } this.applyToPoint = function(p) { for (var i=0; i<this.transforms.length; i++) { this.transforms[i].applyToPoint(p); } } var data = svg.trim(svg.compressSpaces(v)).split(/\s(?=[a-z])/); for (var i=0; i<data.length; i++) { var type = data[i].split('(')[0]; var s = data[i].split('(')[1].replace(')',''); var transform = new this.Type[type](s); this.transforms.push(transform); } } // aspect ratio svg.AspectRatio = function(ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) { // aspect ratio - http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute aspectRatio = svg.compressSpaces(aspectRatio); aspectRatio = aspectRatio.replace(/^defer\s/,''); // ignore defer var align = aspectRatio.split(' ')[0] || 'xMidYMid'; var meetOrSlice = aspectRatio.split(' ')[1] || 'meet'; // calculate scale var scaleX = width / desiredWidth; var scaleY = height / desiredHeight; var scaleMin = Math.min(scaleX, scaleY); var scaleMax = Math.max(scaleX, scaleY); if (meetOrSlice == 'meet') { desiredWidth *= scaleMin; desiredHeight *= scaleMin; } if (meetOrSlice == 'slice') { desiredWidth *= scaleMax; desiredHeight *= scaleMax; } refX = new svg.Property('refX', refX); refY = new svg.Property('refY', refY); if (refX.hasValue() && refY.hasValue()) { ctx.translate(-scaleMin * refX.Length.toPixels('x'), -scaleMin * refY.Length.toPixels('y')); } else { // align if (align.match(/^xMid/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width / 2.0 - desiredWidth / 2.0, 0); if (align.match(/YMid$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height / 2.0 - desiredHeight / 2.0); if (align.match(/^xMax/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width - desiredWidth, 0); if (align.match(/YMax$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height - desiredHeight); } // scale if (align == 'none') ctx.scale(scaleX, scaleY); else if (meetOrSlice == 'meet') ctx.scale(scaleMin, scaleMin); else if (meetOrSlice == 'slice') ctx.scale(scaleMax, scaleMax); // translate ctx.translate(minX == null ? 0 : -minX, minY == null ? 0 : -minY); } // elements svg.Element = {} svg.Element.ElementBase = function(node) { this.attributes = {}; this.styles = {}; this.children = []; // get or create attribute this.attribute = function(name, createIfNotExists) { var a = this.attributes[name]; if (a != null) return a; a = new svg.Property(name, ''); if (createIfNotExists == true) this.attributes[name] = a; return a; } // get or create style, crawls up node tree this.style = function(name, createIfNotExists) { var s = this.styles[name]; if (s != null) return s; var a = this.attribute(name); if (a != null && a.hasValue()) { return a; } var p = this.parent; if (p != null) { var ps = p.style(name); if (ps != null && ps.hasValue()) { return ps; } } s = new svg.Property(name, ''); if (createIfNotExists == true) this.styles[name] = s; return s; } // base render this.render = function(ctx) { // don't render display=none if (this.style('display').value == 'none') return; // don't render visibility=hidden if (this.attribute('visibility').value == 'hidden') return; ctx.save(); this.setContext(ctx); // mask if (this.attribute('mask').hasValue()) { var mask = this.attribute('mask').Definition.getDefinition(); if (mask != null) mask.apply(ctx, this); } else if (this.style('filter').hasValue()) { var filter = this.style('filter').Definition.getDefinition(); if (filter != null) filter.apply(ctx, this); } else this.renderChildren(ctx); this.clearContext(ctx); ctx.restore(); } // base set context this.setContext = function(ctx) { // OVERRIDE ME! } // base clear context this.clearContext = function(ctx) { // OVERRIDE ME! } // base render children this.renderChildren = function(ctx) { for (var i=0; i<this.children.length; i++) { this.children[i].render(ctx); } } this.addChild = function(childNode, create) { var child = childNode; if (create) child = svg.CreateElement(childNode); child.parent = this; this.children.push(child); } if (node != null && node.nodeType == 1) { //ELEMENT_NODE // add children for (var i=0; i<node.childNodes.length; i++) { var childNode = node.childNodes[i]; if (childNode.nodeType == 1) this.addChild(childNode, true); //ELEMENT_NODE } // add attributes for (var i=0; i<node.attributes.length; i++) { var attribute = node.attributes[i]; this.attributes[attribute.nodeName] = new svg.Property(attribute.nodeName, attribute.nodeValue); } // add tag styles var styles = svg.Styles[node.nodeName]; if (styles != null) { for (var name in styles) { this.styles[name] = styles[name]; } } // add class styles if (this.attribute('class').hasValue()) { var classes = svg.compressSpaces(this.attribute('class').value).split(' '); for (var j=0; j<classes.length; j++) { styles = svg.Styles['.'+classes[j]]; if (styles != null) { for (var name in styles) { this.styles[name] = styles[name]; } } styles = svg.Styles[node.nodeName+'.'+classes[j]]; if (styles != null) { for (var name in styles) { this.styles[name] = styles[name]; } } } } // add inline styles if (this.attribute('style').hasValue()) { var styles = this.attribute('style').value.split(';'); for (var i=0; i<styles.length; i++) { if (svg.trim(styles[i]) != '') { var style = styles[i].split(':'); var name = svg.trim(style[0]); var value = svg.trim(style[1]); this.styles[name] = new svg.Property(name, value); } } } // add id if (this.attribute('id').hasValue()) { if (svg.Definitions[this.attribute('id').value] == null) { svg.Definitions[this.attribute('id').value] = this; } } } } svg.Element.RenderedElementBase = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.setContext = function(ctx) { // fill if (this.style('fill').Definition.isUrl()) { var fs = this.style('fill').Definition.getFillStyle(this); if (fs != null) ctx.fillStyle = fs; } else if (this.style('fill').hasValue()) { var fillStyle = this.style('fill'); if (this.style('fill-opacity').hasValue()) fillStyle = fillStyle.Color.addOpacity(this.style('fill-opacity').value); ctx.fillStyle = (fillStyle.value == 'none' ? 'rgba(0,0,0,0)' : fillStyle.value); } // stroke if (this.style('stroke').Definition.isUrl()) { var fs = this.style('stroke').Definition.getFillStyle(this); if (fs != null) ctx.strokeStyle = fs; } else if (this.style('stroke').hasValue()) { var strokeStyle = this.style('stroke'); if (this.style('stroke-opacity').hasValue()) strokeStyle = strokeStyle.Color.addOpacity(this.style('stroke-opacity').value); ctx.strokeStyle = (strokeStyle.value == 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value); } if (this.style('stroke-width').hasValue()) ctx.lineWidth = this.style('stroke-width').Length.toPixels(); if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value; if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value; if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value; // font if (typeof(ctx.font) != 'undefined') { ctx.font = svg.Font.CreateFont( this.style('font-style').value, this.style('font-variant').value, this.style('font-weight').value, this.style('font-size').hasValue() ? this.style('font-size').Length.toPixels() + 'px' : '', this.style('font-family').value).toString(); } // transform if (this.attribute('transform').hasValue()) { var transform = new svg.Transform(this.attribute('transform').value); transform.apply(ctx); } // clip if (this.attribute('clip-path').hasValue()) { var clip = this.attribute('clip-path').Definition.getDefinition(); if (clip != null) clip.apply(ctx); } // opacity if (this.style('opacity').hasValue()) { ctx.globalAlpha = this.style('opacity').numValue(); } } } svg.Element.RenderedElementBase.prototype = new svg.Element.ElementBase; svg.Element.PathElementBase = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.path = function(ctx) { if (ctx != null) ctx.beginPath(); return new svg.BoundingBox(); } this.renderChildren = function(ctx) { this.path(ctx); svg.Mouse.checkPath(this, ctx); if (ctx.fillStyle != '') ctx.fill(); if (ctx.strokeStyle != '') ctx.stroke(); var markers = this.getMarkers(); if (markers != null) { if (this.style('marker-start').Definition.isUrl()) { var marker = this.style('marker-start').Definition.getDefinition(); marker.render(ctx, markers[0][0], markers[0][1]); } if (this.style('marker-mid').Definition.isUrl()) { var marker = this.style('marker-mid').Definition.getDefinition(); for (var i=1;i<markers.length-1;i++) { marker.render(ctx, markers[i][0], markers[i][1]); } } if (this.style('marker-end').Definition.isUrl()) { var marker = this.style('marker-end').Definition.getDefinition(); marker.render(ctx, markers[markers.length-1][0], markers[markers.length-1][1]); } } } this.getBoundingBox = function() { return this.path(); } this.getMarkers = function() { return null; } } svg.Element.PathElementBase.prototype = new svg.Element.RenderedElementBase; // svg element svg.Element.svg = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.baseClearContext = this.clearContext; this.clearContext = function(ctx) { this.baseClearContext(ctx); svg.ViewPort.RemoveCurrent(); } this.baseSetContext = this.setContext; this.setContext = function(ctx) { // initial values ctx.strokeStyle = 'rgba(0,0,0,0)'; ctx.lineCap = 'butt'; ctx.lineJoin = 'miter'; ctx.miterLimit = 4; this.baseSetContext(ctx); // create new view port if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) { ctx.translate(this.attribute('x').Length.toPixels('x'), this.attribute('y').Length.toPixels('y')); } var width = svg.ViewPort.width(); var height = svg.ViewPort.height(); if (typeof(this.root) == 'undefined' && this.attribute('width').hasValue() && this.attribute('height').hasValue()) { width = this.attribute('width').Length.toPixels('x'); height = this.attribute('height').Length.toPixels('y'); var x = 0; var y = 0; if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) { x = -this.attribute('refX').Length.toPixels('x'); y = -this.attribute('refY').Length.toPixels('y'); } ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(width, y); ctx.lineTo(width, height); ctx.lineTo(x, height); ctx.closePath(); ctx.clip(); } svg.ViewPort.SetCurrent(width, height); // viewbox if (this.attribute('viewBox').hasValue()) { var viewBox = svg.ToNumberArray(this.attribute('viewBox').value); var minX = viewBox[0]; var minY = viewBox[1]; width = viewBox[2]; height = viewBox[3]; svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, svg.ViewPort.width(), width, svg.ViewPort.height(), height, minX, minY, this.attribute('refX').value, this.attribute('refY').value); svg.ViewPort.RemoveCurrent(); svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]); } } } svg.Element.svg.prototype = new svg.Element.RenderedElementBase; // rect element svg.Element.rect = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.path = function(ctx) { var x = this.attribute('x').Length.toPixels('x'); var y = this.attribute('y').Length.toPixels('y'); var width = this.attribute('width').Length.toPixels('x'); var height = this.attribute('height').Length.toPixels('y'); var rx = this.attribute('rx').Length.toPixels('x'); var ry = this.attribute('ry').Length.toPixels('y'); if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx; if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry; if (ctx != null) { ctx.beginPath(); ctx.moveTo(x + rx, y); ctx.lineTo(x + width - rx, y); ctx.quadraticCurveTo(x + width, y, x + width, y + ry) ctx.lineTo(x + width, y + height - ry); ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height) ctx.lineTo(x + rx, y + height); ctx.quadraticCurveTo(x, y + height, x, y + height - ry) ctx.lineTo(x, y + ry); ctx.quadraticCurveTo(x, y, x + rx, y) ctx.closePath(); } return new svg.BoundingBox(x, y, x + width, y + height); } } svg.Element.rect.prototype = new svg.Element.PathElementBase; // circle element svg.Element.circle = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.path = function(ctx) { var cx = this.attribute('cx').Length.toPixels('x'); var cy = this.attribute('cy').Length.toPixels('y'); var r = this.attribute('r').Length.toPixels(); if (ctx != null) { ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2, true); ctx.closePath(); } return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r); } } svg.Element.circle.prototype = new svg.Element.PathElementBase; // ellipse element svg.Element.ellipse = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.path = function(ctx) { var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3); var rx = this.attribute('rx').Length.toPixels('x'); var ry = this.attribute('ry').Length.toPixels('y'); var cx = this.attribute('cx').Length.toPixels('x'); var cy = this.attribute('cy').Length.toPixels('y'); if (ctx != null) { ctx.beginPath(); ctx.moveTo(cx, cy - ry); ctx.bezierCurveTo(cx + (KAPPA * rx), cy - ry, cx + rx, cy - (KAPPA * ry), cx + rx, cy); ctx.bezierCurveTo(cx + rx, cy + (KAPPA * ry), cx + (KAPPA * rx), cy + ry, cx, cy + ry); ctx.bezierCurveTo(cx - (KAPPA * rx), cy + ry, cx - rx, cy + (KAPPA * ry), cx - rx, cy); ctx.bezierCurveTo(cx - rx, cy - (KAPPA * ry), cx - (KAPPA * rx), cy - ry, cx, cy - ry); ctx.closePath(); } return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry); } } svg.Element.ellipse.prototype = new svg.Element.PathElementBase; // line element svg.Element.line = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.getPoints = function() { return [ new svg.Point(this.attribute('x1').Length.toPixels('x'), this.attribute('y1').Length.toPixels('y')), new svg.Point(this.attribute('x2').Length.toPixels('x'), this.attribute('y2').Length.toPixels('y'))]; } this.path = function(ctx) { var points = this.getPoints(); if (ctx != null) { ctx.beginPath(); ctx.moveTo(points[0].x, points[0].y); ctx.lineTo(points[1].x, points[1].y); } return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y); } this.getMarkers = function() { var points = this.getPoints(); var a = points[0].angleTo(points[1]); return [[points[0], a], [points[1], a]]; } } svg.Element.line.prototype = new svg.Element.PathElementBase; // polyline element svg.Element.polyline = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.points = svg.CreatePath(this.attribute('points').value); this.path = function(ctx) { var bb = new svg.BoundingBox(this.points[0].x, this.points[0].y); if (ctx != null) { ctx.beginPath(); ctx.moveTo(this.points[0].x, this.points[0].y); } for (var i=1; i<this.points.length; i++) { bb.addPoint(this.points[i].x, this.points[i].y); if (ctx != null) ctx.lineTo(this.points[i].x, this.points[i].y); } return bb; } this.getMarkers = function() { var markers = []; for (var i=0; i<this.points.length - 1; i++) { markers.push([this.points[i], this.points[i].angleTo(this.points[i+1])]); } markers.push([this.points[this.points.length-1], markers[markers.length-1][1]]); return markers; } } svg.Element.polyline.prototype = new svg.Element.PathElementBase; // polygon element svg.Element.polygon = function(node) { this.base = svg.Element.polyline; this.base(node); this.basePath = this.path; this.path = function(ctx) { var bb = this.basePath(ctx); if (ctx != null) { ctx.lineTo(this.points[0].x, this.points[0].y); ctx.closePath(); } return bb; } } svg.Element.polygon.prototype = new svg.Element.polyline; // path element svg.Element.path = function(node) { this.base = svg.Element.PathElementBase; this.base(node); var d = this.attribute('d').value; // TODO: convert to real lexer based on http://www.w3.org/TR/SVG11/paths.html#PathDataBNF d = d.replace(/,/gm,' '); // get rid of all commas d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([^\s])/gm,'$1 $2'); // separate commands from points d = d.replace(/([^\s])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from points d = d.replace(/([0-9])([+\-])/gm,'$1 $2'); // separate digits when no comma d = d.replace(/(\.[0-9]*)(\.)/gm,'$1 $2'); // separate digits when no comma d = d.replace(/([Aa](\s+[0-9]+){3})\s+([01])\s*([01])/gm,'$1 $3 $4 '); // shorthand elliptical arc path syntax d = svg.compressSpaces(d); // compress multiple spaces d = svg.trim(d); this.PathParser = new (function(d) { this.tokens = d.split(' '); this.reset = function() { this.i = -1; this.command = ''; this.previousCommand = ''; this.start = new svg.Point(0, 0); this.control = new svg.Point(0, 0); this.current = new svg.Point(0, 0); this.points = []; this.angles = []; } this.isEnd = function() { return this.i >= this.tokens.length - 1; } this.isCommandOrEnd = function() { if (this.isEnd()) return true; return this.tokens[this.i + 1].match(/^[A-Za-z]$/) != null; } this.isRelativeCommand = function() { return this.command == this.command.toLowerCase(); } this.getToken = function() { this.i = this.i + 1; return this.tokens[this.i]; } this.getScalar = function() { return parseFloat(this.getToken()); } this.nextCommand = function() { this.previousCommand = this.command; this.command = this.getToken(); } this.getPoint = function() { var p = new svg.Point(this.getScalar(), this.getScalar()); return this.makeAbsolute(p); } this.getAsControlPoint = function() { var p = this.getPoint(); this.control = p; return p; } this.getAsCurrentPoint = function() { var p = this.getPoint(); this.current = p; return p; } this.getReflectedControlPoint = function() { if (this.previousCommand.toLowerCase() != 'c' && this.previousCommand.toLowerCase() != 's') { return this.current; } // reflect point var p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y); return p; } this.makeAbsolute = function(p) { if (this.isRelativeCommand()) { p.x = this.current.x + p.x; p.y = this.current.y + p.y; } return p; } this.addMarker = function(p, from, priorTo) { // if the last angle isn't filled in because we didn't have this point yet ... if (priorTo != null && this.angles.length > 0 && this.angles[this.angles.length-1] == null) { this.angles[this.angles.length-1] = this.points[this.points.length-1].angleTo(priorTo); } this.addMarkerAngle(p, from == null ? null : from.angleTo(p)); } this.addMarkerAngle = function(p, a) { this.points.push(p); this.angles.push(a); } this.getMarkerPoints = function() { return this.points; } this.getMarkerAngles = function() { for (var i=0; i<this.angles.length; i++) { if (this.angles[i] == null) { for (var j=i+1; j<this.angles.length; j++) { if (this.angles[j] != null) { this.angles[i] = this.angles[j]; break; } } } } return this.angles; } })(d); this.path = function(ctx) { var pp = this.PathParser; pp.reset(); var bb = new svg.BoundingBox(); if (ctx != null) ctx.beginPath(); while (!pp.isEnd()) { pp.nextCommand(); switch (pp.command.toUpperCase()) { case 'M': var p = pp.getAsCurrentPoint(); pp.addMarker(p); bb.addPoint(p.x, p.y); if (ctx != null) ctx.moveTo(p.x, p.y); pp.start = pp.current; while (!pp.isCommandOrEnd()) { var p = pp.getAsCurrentPoint(); pp.addMarker(p, pp.start); bb.addPoint(p.x, p.y); if (ctx != null) ctx.lineTo(p.x, p.y); } break; case 'L': while (!pp.isCommandOrEnd()) { var c = pp.current; var p = pp.getAsCurrentPoint(); pp.addMarker(p, c); bb.addPoint(p.x, p.y); if (ctx != null) ctx.lineTo(p.x, p.y); } break; case 'H': while (!pp.isCommandOrEnd()) { var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y); pp.addMarker(newP, pp.current); pp.current = newP; bb.addPoint(pp.current.x, pp.current.y); if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y); } break; case 'V': while (!pp.isCommandOrEnd()) { var newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar()); pp.addMarker(newP, pp.current); pp.current = newP; bb.addPoint(pp.current.x, pp.current.y); if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y); } break; case 'C': while (!pp.isCommandOrEnd()) { var curr = pp.current; var p1 = pp.getPoint(); var cntrl = pp.getAsControlPoint(); var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl, p1); bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); } break; case 'S': while (!pp.isCommandOrEnd()) { var curr = pp.current; var p1 = pp.getReflectedControlPoint(); var cntrl = pp.getAsControlPoint(); var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl, p1); bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); } break; case 'Q': while (!pp.isCommandOrEnd()) { var curr = pp.current; var cntrl = pp.getAsControlPoint(); var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl, cntrl); bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y); if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y); } break; case 'T': while (!pp.isCommandOrEnd()) { var curr = pp.current; var cntrl = pp.getReflectedControlPoint(); pp.control = cntrl; var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl, cntrl); bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y); if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y); } break; case 'A': while (!pp.isCommandOrEnd()) { var curr = pp.current; var rx = pp.getScalar(); var ry = pp.getScalar(); var xAxisRotation = pp.getScalar() * (Math.PI / 180.0); var largeArcFlag = pp.getScalar(); var sweepFlag = pp.getScalar(); var cp = pp.getAsCurrentPoint(); // Conversion from endpoint to center parameterization // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes // x1', y1' var currp = new svg.Point( Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0, -Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0 ); // adjust radii var l = Math.pow(currp.x,2)/Math.pow(rx,2)+Math.pow(currp.y,2)/Math.pow(ry,2); if (l > 1) { rx *= Math.sqrt(l); ry *= Math.sqrt(l); } // cx', cy' var s = (largeArcFlag == sweepFlag ? -1 : 1) * Math.sqrt( ((Math.pow(rx,2)*Math.pow(ry,2))-(Math.pow(rx,2)*Math.pow(currp.y,2))-(Math.pow(ry,2)*Math.pow(currp.x,2))) / (Math.pow(rx,2)*Math.pow(currp.y,2)+Math.pow(ry,2)*Math.pow(currp.x,2)) ); if (isNaN(s)) s = 0; var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx); // cx, cy var centp = new svg.Point( (curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y, (curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y ); // vector magnitude var m = function(v) { return Math.sqrt(Math.pow(v[0],2) + Math.pow(v[1],2)); } // ratio between two vectors var r = function(u, v) { return (u[0]*v[0]+u[1]*v[1]) / (m(u)*m(v)) } // angle between two vectors var a = function(u, v) { return (u[0]*v[1] < u[1]*v[0] ? -1 : 1) * Math.acos(r(u,v)); } // initial angle var a1 = a([1,0], [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry]); // angle delta var u = [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry]; var v = [(-currp.x-cpp.x)/rx,(-currp.y-cpp.y)/ry]; var ad = a(u, v); if (r(u,v) <= -1) ad = Math.PI; if (r(u,v) >= 1) ad = 0; if (sweepFlag == 0 && ad > 0) ad = ad - 2 * Math.PI; if (sweepFlag == 1 && ad < 0) ad = ad + 2 * Math.PI; // for markers var halfWay = new svg.Point( centp.x - rx * Math.cos((a1 + ad) / 2), centp.y - ry * Math.sin((a1 + ad) / 2) ); pp.addMarkerAngle(halfWay, (a1 + ad) / 2 + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2); pp.addMarkerAngle(cp, ad + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2); bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better if (ctx != null) { var r = rx > ry ? rx : ry; var sx = rx > ry ? 1 : rx / ry; var sy = rx > ry ? ry / rx : 1; ctx.translate(centp.x, centp.y); ctx.rotate(xAxisRotation); ctx.scale(sx, sy); ctx.arc(0, 0, r, a1, a1 + ad, 1 - sweepFlag); ctx.scale(1/sx, 1/sy); ctx.rotate(-xAxisRotation); ctx.translate(-centp.x, -centp.y); } } break; case 'Z': if (ctx != null) ctx.closePath(); pp.current = pp.start; } } return bb; } this.getMarkers = function() { var points = this.PathParser.getMarkerPoints(); var angles = this.PathParser.getMarkerAngles(); var markers = []; for (var i=0; i<points.length; i++) { markers.push([points[i], angles[i]]); } return markers; } } svg.Element.path.prototype = new svg.Element.PathElementBase; // pattern element svg.Element.pattern = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.createPattern = function(ctx, element) { // render me using a temporary svg element var tempSvg = new svg.Element.svg(); tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value); tempSvg.attributes['x'] = new svg.Property('x', this.attribute('x').value); tempSvg.attributes['y'] = new svg.Property('y', this.attribute('y').value); tempSvg.attributes['width'] = new svg.Property('width', this.attribute('width').value); tempSvg.attributes['height'] = new svg.Property('height', this.attribute('height').value); tempSvg.children = this.children; var c = document.createElement('canvas'); c.width = this.attribute('width').Length.toPixels('x'); c.height = this.attribute('height').Length.toPixels('y'); tempSvg.render(c.getContext('2d')); return ctx.createPattern(c, 'repeat'); } } svg.Element.pattern.prototype = new svg.Element.ElementBase; // marker element svg.Element.marker = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.baseRender = this.render; this.render = function(ctx, point, angle) { ctx.translate(point.x, point.y); if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(angle); if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth); ctx.save(); // render me using a temporary svg element var tempSvg = new svg.Element.svg(); tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value); tempSvg.attributes['refX'] = new svg.Property('refX', this.attribute('refX').value); tempSvg.attributes['refY'] = new svg.Property('refY', this.attribute('refY').value); tempSvg.attributes['width'] = new svg.Property('width', this.attribute('markerWidth').value); tempSvg.attributes['height'] = new svg.Property('height', this.attribute('markerHeight').value); tempSvg.attributes['fill'] = new svg.Property('fill', this.attribute('fill').valueOrDefault('black')); tempSvg.attributes['stroke'] = new svg.Property('stroke', this.attribute('stroke').valueOrDefault('none')); tempSvg.children = this.children; tempSvg.render(ctx); ctx.restore(); if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(1/ctx.lineWidth, 1/ctx.lineWidth); if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(-angle); ctx.translate(-point.x, -point.y); } } svg.Element.marker.prototype = new svg.Element.ElementBase; // definitions element svg.Element.defs = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.render = function(ctx) { // NOOP } } svg.Element.defs.prototype = new svg.Element.ElementBase; // base for gradients svg.Element.GradientBase = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.gradientUnits = this.attribute('gradientUnits').valueOrDefault('objectBoundingBox'); this.stops = []; for (var i=0; i<this.children.length; i++) { var child = this.children[i]; this.stops.push(child); } this.getGradient = function() { // OVERRIDE ME! } this.createGradient = function(ctx, element) { var stopsContainer = this; if (this.attribute('xlink:href').hasValue()) { stopsContainer = this.attribute('xlink:href').Definition.getDefinition(); } var g = this.getGradient(ctx, element); for (var i=0; i<stopsContainer.stops.length; i++) { g.addColorStop(stopsContainer.stops[i].offset, stopsContainer.stops[i].color); } if (this.attribute('gradientTransform').hasValue()) { // render as transformed pattern on temporary canvas var rootView = svg.ViewPort.viewPorts[0]; var rect = new svg.Element.rect(); rect.attributes['x'] = new svg.Property('x', -svg.MAX_VIRTUAL_PIXELS/3.0); rect.attributes['y'] = new svg.Property('y', -svg.MAX_VIRTUAL_PIXELS/3.0); rect.attributes['width'] = new svg.Property('width', svg.MAX_VIRTUAL_PIXELS); rect.attributes['height'] = new svg.Property('height', svg.MAX_VIRTUAL_PIXELS); var group = new svg.Element.g(); group.attributes['transform'] = new svg.Property('transform', this.attribute('gradientTransform').value); group.children = [ rect ]; var tempSvg = new svg.Element.svg(); tempSvg.attributes['x'] = new svg.Property('x', 0); tempSvg.attributes['y'] = new svg.Property('y', 0); tempSvg.attributes['width'] = new svg.Property('width', rootView.width); tempSvg.attributes['height'] = new svg.Property('height', rootView.height); tempSvg.children = [ group ]; var c = document.createElement('canvas'); c.width = rootView.width; c.height = rootView.height; var tempCtx = c.getContext('2d'); tempCtx.fillStyle = g; tempSvg.render(tempCtx); return tempCtx.createPattern(c, 'no-repeat'); } return g; } } svg.Element.GradientBase.prototype = new svg.Element.ElementBase; // linear gradient element svg.Element.linearGradient = function(node) { this.base = svg.Element.GradientBase; this.base(node); this.getGradient = function(ctx, element) { var bb = element.getBoundingBox(); var x1 = (this.gradientUnits == 'objectBoundingBox' ? bb.x() + bb.width() * this.attribute('x1').numValue() : this.attribute('x1').Length.toPixels('x')); var y1 = (this.gradientUnits == 'objectBoundingBox' ? bb.y() + bb.height() * this.attribute('y1').numValue() : this.attribute('y1').Length.toPixels('y')); var x2 = (this.gradientUnits == 'objectBoundingBox' ? bb.x() + bb.width() * this.attribute('x2').numValue() : this.attribute('x2').Length.toPixels('x')); var y2 = (this.gradientUnits == 'objectBoundingBox' ? bb.y() + bb.height() * this.attribute('y2').numValue() : this.attribute('y2').Length.toPixels('y')); return ctx.createLinearGradient(x1, y1, x2, y2); } } svg.Element.linearGradient.prototype = new svg.Element.GradientBase; // radial gradient element svg.Element.radialGradient = function(node) { this.base = svg.Element.GradientBase; this.base(node); this.getGradient = function(ctx, element) { var bb = element.getBoundingBox(); var cx = (this.gradientUnits == 'objectBoundingBox' ? bb.x() + bb.width() * this.attribute('cx').numValue() : this.attribute('cx').Length.toPixels('x')); var cy = (this.gradientUnits == 'objectBoundingBox' ? bb.y() + bb.height() * this.attribute('cy').numValue() : this.attribute('cy').Length.toPixels('y')); var fx = cx; var fy = cy; if (this.attribute('fx').hasValue()) { fx = (this.gradientUnits == 'objectBoundingBox' ? bb.x() + bb.width() * this.attribute('fx').numValue() : this.attribute('fx').Length.toPixels('x')); } if (this.attribute('fy').hasValue()) { fy = (this.gradientUnits == 'objectBoundingBox' ? bb.y() + bb.height() * this.attribute('fy').numValue() : this.attribute('fy').Length.toPixels('y')); } var r = (this.gradientUnits == 'objectBoundingBox' ? (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue() : this.attribute('r').Length.toPixels()); return ctx.createRadialGradient(fx, fy, 0, cx, cy, r); } } svg.Element.radialGradient.prototype = new svg.Element.GradientBase; // gradient stop element svg.Element.stop = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.offset = this.attribute('offset').numValue(); var stopColor = this.style('stop-color'); if (this.style('stop-opacity').hasValue()) stopColor = stopColor.Color.addOpacity(this.style('stop-opacity').value); this.color = stopColor.value; } svg.Element.stop.prototype = new svg.Element.ElementBase; // animation base element svg.Element.AnimateBase = function(node) { this.base = svg.Element.ElementBase; this.base(node); svg.Animations.push(this); this.duration = 0.0; this.begin = this.attribute('begin').Time.toMilliseconds(); this.maxDuration = this.begin + this.attribute('dur').Time.toMilliseconds(); this.getProperty = function() { var attributeType = this.attribute('attributeType').value; var attributeName = this.attribute('attributeName').value; if (attributeType == 'CSS') { return this.parent.style(attributeName, true); } return this.parent.attribute(attributeName, true); }; this.initialValue = null; this.removed = false; this.calcValue = function() { // OVERRIDE ME! return ''; } this.update = function(delta) { // set initial value if (this.initialValue == null) { this.initialValue = this.getProperty().value; } // if we're past the end time if (this.duration > this.maxDuration) { // loop for indefinitely repeating animations if (this.attribute('repeatCount').value == 'indefinite') { this.duration = 0.0 } else if (this.attribute('fill').valueOrDefault('remove') == 'remove' && !this.removed) { this.removed = true; this.getProperty().value = this.initialValue; return true; } else { return false; // no updates made } } this.duration = this.duration + delta; // if we're past the begin time var updated = false; if (this.begin < this.duration) { var newValue = this.calcValue(); // tween if (this.attribute('type').hasValue()) { // for transform, etc. var type = this.attribute('type').value; newValue = type + '(' + newValue + ')'; } this.getProperty().value = newValue; updated = true; } return updated; } // fraction of duration we've covered this.progress = function() { return ((this.duration - this.begin) / (this.maxDuration - this.begin)); } } svg.Element.AnimateBase.prototype = new svg.Element.ElementBase; // animate element svg.Element.animate = function(node) { this.base = svg.Element.AnimateBase; this.base(node); this.calcValue = function() { var from = this.attribute('from').numValue(); var to = this.attribute('to').numValue(); // tween value linearly return from + (to - from) * this.progress(); }; } svg.Element.animate.prototype = new svg.Element.AnimateBase; // animate color element svg.Element.animateColor = function(node) { this.base = svg.Element.AnimateBase; this.base(node); this.calcValue = function() { var from = new RGBColor(this.attribute('from').value); var to = new RGBColor(this.attribute('to').value); if (from.ok && to.ok) { // tween color linearly var r = from.r + (to.r - from.r) * this.progress(); var g = from.g + (to.g - from.g) * this.progress(); var b = from.b + (to.b - from.b) * this.progress(); return 'rgb('+parseInt(r,10)+','+parseInt(g,10)+','+parseInt(b,10)+')'; } return this.attribute('from').value; }; } svg.Element.animateColor.prototype = new svg.Element.AnimateBase; // animate transform element svg.Element.animateTransform = function(node) { this.base = svg.Element.animate; this.base(node); } svg.Element.animateTransform.prototype = new svg.Element.animate; // font element svg.Element.font = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.horizAdvX = this.attribute('horiz-adv-x').numValue(); this.isRTL = false; this.isArabic = false; this.fontFace = null; this.missingGlyph = null; this.glyphs = []; for (var i=0; i<this.children.length; i++) { var child = this.children[i]; if (child.type == 'font-face') { this.fontFace = child; if (child.style('font-family').hasValue()) { svg.Definitions[child.style('font-family').value] = this; } } else if (child.type == 'missing-glyph') this.missingGlyph = child; else if (child.type == 'glyph') { if (child.arabicForm != '') { this.isRTL = true; this.isArabic = true; if (typeof(this.glyphs[child.unicode]) == 'undefined') this.glyphs[child.unicode] = []; this.glyphs[child.unicode][child.arabicForm] = child; } else { this.glyphs[child.unicode] = child; } } } } svg.Element.font.prototype = new svg.Element.ElementBase; // font-face element svg.Element.fontface = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.ascent = this.attribute('ascent').value; this.descent = this.attribute('descent').value; this.unitsPerEm = this.attribute('units-per-em').numValue(); } svg.Element.fontface.prototype = new svg.Element.ElementBase; // missing-glyph element svg.Element.missingglyph = function(node) { this.base = svg.Element.path; this.base(node); this.horizAdvX = 0; } svg.Element.missingglyph.prototype = new svg.Element.path; // glyph element svg.Element.glyph = function(node) { this.base = svg.Element.path; this.base(node); this.horizAdvX = this.attribute('horiz-adv-x').numValue(); this.unicode = this.attribute('unicode').value; this.arabicForm = this.attribute('arabic-form').value; } svg.Element.glyph.prototype = new svg.Element.path; // text element svg.Element.text = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); if (node != null) { // add children this.children = []; for (var i=0; i<node.childNodes.length; i++) { var childNode = node.childNodes[i]; if (childNode.nodeType == 1) { // capture tspan and tref nodes this.addChild(childNode, true); } else if (childNode.nodeType == 3) { // capture text this.addChild(new svg.Element.tspan(childNode), false); } } } this.baseSetContext = this.setContext; this.setContext = function(ctx) { this.baseSetContext(ctx); if (this.style('dominant-baseline').hasValue()) ctx.textBaseline = this.style('dominant-baseline').value; if (this.style('alignment-baseline').hasValue()) ctx.textBaseline = this.style('alignment-baseline').value; } this.renderChildren = function(ctx) { var textAnchor = this.style('text-anchor').valueOrDefault('start'); var x = this.attribute('x').Length.toPixels('x'); var y = this.attribute('y').Length.toPixels('y'); for (var i=0; i<this.children.length; i++) { var child = this.children[i]; if (child.attribute('x').hasValue()) { child.x = child.attribute('x').Length.toPixels('x'); } else { if (child.attribute('dx').hasValue()) x += child.attribute('dx').Length.toPixels('x'); child.x = x; } var childLength = child.measureText(ctx); if (textAnchor != 'start' && (i==0 || child.attribute('x').hasValue())) { // new group? // loop through rest of children var groupLength = childLength; for (var j=i+1; j<this.children.length; j++) { var childInGroup = this.children[j]; if (childInGroup.attribute('x').hasValue()) break; // new group groupLength += childInGroup.measureText(ctx); } child.x -= (textAnchor == 'end' ? groupLength : groupLength / 2.0); } x = child.x + childLength; if (child.attribute('y').hasValue()) { child.y = child.attribute('y').Length.toPixels('y'); } else { if (child.attribute('dy').hasValue()) y += child.attribute('dy').Length.toPixels('y'); child.y = y; } y = child.y; child.render(ctx); } } } svg.Element.text.prototype = new svg.Element.RenderedElementBase; // text base svg.Element.TextElementBase = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.getGlyph = function(font, text, i) { var c = text[i]; var glyph = null; if (font.isArabic) { var arabicForm = 'isolated'; if ((i==0 || text[i-1]==' ') && i<text.length-2 && text[i+1]!=' ') arabicForm = 'terminal'; if (i>0 && text[i-1]!=' ' && i<text.length-2 && text[i+1]!=' ') arabicForm = 'medial'; if (i>0 && text[i-1]!=' ' && (i == text.length-1 || text[i+1]==' ')) arabicForm = 'initial'; if (typeof(font.glyphs[c]) != 'undefined') { glyph = font.glyphs[c][arabicForm]; if (glyph == null && font.glyphs[c].type == 'glyph') glyph = font.glyphs[c]; } } else { glyph = font.glyphs[c]; } if (glyph == null) glyph = font.missingGlyph; return glyph; } this.renderChildren = function(ctx) { var customFont = this.parent.style('font-family').Definition.getDefinition(); if (customFont != null) { var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize); var fontStyle = this.parent.style('font-style').valueOrDefault(svg.Font.Parse(svg.ctx.font).fontStyle); var text = this.getText(); if (customFont.isRTL) text = text.split("").reverse().join(""); var dx = svg.ToNumberArray(this.parent.attribute('dx').value); for (var i=0; i<text.length; i++) { var glyph = this.getGlyph(customFont, text, i); var scale = fontSize / customFont.fontFace.unitsPerEm; ctx.translate(this.x, this.y); ctx.scale(scale, -scale); var lw = ctx.lineWidth; ctx.lineWidth = ctx.lineWidth * customFont.fontFace.unitsPerEm / fontSize; if (fontStyle == 'italic') ctx.transform(1, 0, .4, 1, 0, 0); glyph.render(ctx); if (fontStyle == 'italic') ctx.transform(1, 0, -.4, 1, 0, 0); ctx.lineWidth = lw; ctx.scale(1/scale, -1/scale); ctx.translate(-this.x, -this.y); this.x += fontSize * (glyph.horizAdvX || customFont.horizAdvX) / customFont.fontFace.unitsPerEm; if (typeof(dx[i]) != 'undefined' && !isNaN(dx[i])) { this.x += dx[i]; } } return; } if (ctx.strokeStyle != '') ctx.strokeText(svg.compressSpaces(this.getText()), this.x, this.y); if (ctx.fillStyle != '') ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y); } this.getText = function() { // OVERRIDE ME } this.measureText = function(ctx) { var customFont = this.parent.style('font-family').Definition.getDefinition(); if (customFont != null) { var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize); var measure = 0; var text = this.getText(); if (customFont.isRTL) text = text.split("").reverse().join(""); var dx = svg.ToNumberArray(this.parent.attribute('dx').value); for (var i=0; i<text.length; i++) { var glyph = this.getGlyph(customFont, text, i); measure += (glyph.horizAdvX || customFont.horizAdvX) * fontSize / customFont.fontFace.unitsPerEm; if (typeof(dx[i]) != 'undefined' && !isNaN(dx[i])) { measure += dx[i]; } } return measure; } var textToMeasure = svg.compressSpaces(this.getText()); if (!ctx.measureText) return textToMeasure.length * 10; ctx.save(); this.setContext(ctx); var width = ctx.measureText(textToMeasure).width; ctx.restore(); return width; } } svg.Element.TextElementBase.prototype = new svg.Element.RenderedElementBase; // tspan svg.Element.tspan = function(node) { this.base = svg.Element.TextElementBase; this.base(node); this.text = node.nodeType == 3 ? node.nodeValue : // text node.childNodes.length > 0 ? node.childNodes[0].nodeValue : // element node.text; this.getText = function() { return this.text; } } svg.Element.tspan.prototype = new svg.Element.TextElementBase; // tref svg.Element.tref = function(node) { this.base = svg.Element.TextElementBase; this.base(node); this.getText = function() { var element = this.attribute('xlink:href').Definition.getDefinition(); if (element != null) return element.children[0].getText(); } } svg.Element.tref.prototype = new svg.Element.TextElementBase; // a element svg.Element.a = function(node) { this.base = svg.Element.TextElementBase; this.base(node); this.hasText = true; for (var i=0; i<node.childNodes.length; i++) { if (node.childNodes[i].nodeType != 3) this.hasText = false; } // this might contain text this.text = this.hasText ? node.childNodes[0].nodeValue : ''; this.getText = function() { return this.text; } this.baseRenderChildren = this.renderChildren; this.renderChildren = function(ctx) { if (this.hasText) { // render as text element this.baseRenderChildren(ctx); var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize); svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.Length.toPixels('y'), this.x + this.measureText(ctx), this.y)); } else { // render as temporary group var g = new svg.Element.g(); g.children = this.children; g.parent = this; g.render(ctx); } } this.onclick = function() { window.open(this.attribute('xlink:href').value); } this.onmousemove = function() { svg.ctx.canvas.style.cursor = 'pointer'; } } svg.Element.a.prototype = new svg.Element.TextElementBase; // image element svg.Element.image = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); svg.Images.push(this); this.img = document.createElement('img'); this.loaded = false; var that = this; this.img.onload = function() { that.loaded = true; } this.img.src = this.attribute('xlink:href').value; this.renderChildren = function(ctx) { var x = this.attribute('x').Length.toPixels('x'); var y = this.attribute('y').Length.toPixels('y'); var width = this.attribute('width').Length.toPixels('x'); var height = this.attribute('height').Length.toPixels('y'); if (width == 0 || height == 0) return; ctx.save(); ctx.translate(x, y); svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, width, this.img.width, height, this.img.height, 0, 0); ctx.drawImage(this.img, 0, 0); ctx.restore(); } } svg.Element.image.prototype = new svg.Element.RenderedElementBase; // group element svg.Element.g = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.getBoundingBox = function() { var bb = new svg.BoundingBox(); for (var i=0; i<this.children.length; i++) { bb.addBoundingBox(this.children[i].getBoundingBox()); } return bb; }; } svg.Element.g.prototype = new svg.Element.RenderedElementBase; // symbol element svg.Element.symbol = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.baseSetContext = this.setContext; this.setContext = function(ctx) { this.baseSetContext(ctx); // viewbox if (this.attribute('viewBox').hasValue()) { var viewBox = svg.ToNumberArray(this.attribute('viewBox').value); var minX = viewBox[0]; var minY = viewBox[1]; width = viewBox[2]; height = viewBox[3]; svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, this.attribute('width').Length.toPixels('x'), width, this.attribute('height').Length.toPixels('y'), height, minX, minY); svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]); } } } svg.Element.symbol.prototype = new svg.Element.RenderedElementBase; // style element svg.Element.style = function(node) { this.base = svg.Element.ElementBase; this.base(node); // text, or spaces then CDATA var css = node.childNodes[0].nodeValue + (node.childNodes.length > 1 ? node.childNodes[1].nodeValue : ''); css = css.replace(/(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(^[\s]*\/\/.*)/gm, ''); // remove comments css = svg.compressSpaces(css); // replace whitespace var cssDefs = css.split('}'); for (var i=0; i<cssDefs.length; i++) { if (svg.trim(cssDefs[i]) != '') { var cssDef = cssDefs[i].split('{'); var cssClasses = cssDef[0].split(','); var cssProps = cssDef[1].split(';'); for (var j=0; j<cssClasses.length; j++) { var cssClass = svg.trim(cssClasses[j]); if (cssClass != '') { var props = {}; for (var k=0; k<cssProps.length; k++) { var prop = cssProps[k].indexOf(':'); var name = cssProps[k].substr(0, prop); var value = cssProps[k].substr(prop + 1, cssProps[k].length - prop); if (name != null && value != null) { props[svg.trim(name)] = new svg.Property(svg.trim(name), svg.trim(value)); } } svg.Styles[cssClass] = props; if (cssClass == '@font-face') { var fontFamily = props['font-family'].value.replace(/"/g,''); var srcs = props['src'].value.split(','); for (var s=0; s<srcs.length; s++) { if (srcs[s].indexOf('format("svg")') > 0) { var urlStart = srcs[s].indexOf('url'); var urlEnd = srcs[s].indexOf(')', urlStart); var url = srcs[s].substr(urlStart + 5, urlEnd - urlStart - 6); var doc = svg.parseXml(svg.ajax(url)); var fonts = doc.getElementsByTagName('font'); for (var f=0; f<fonts.length; f++) { var font = svg.CreateElement(fonts[f]); svg.Definitions[fontFamily] = font; } } } } } } } } } svg.Element.style.prototype = new svg.Element.ElementBase; // use element svg.Element.use = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.baseSetContext = this.setContext; this.setContext = function(ctx) { this.baseSetContext(ctx); if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').Length.toPixels('x'), 0); if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').Length.toPixels('y')); } this.getDefinition = function() { var element = this.attribute('xlink:href').Definition.getDefinition(); if (this.attribute('width').hasValue()) element.attribute('width', true).value = this.attribute('width').value; if (this.attribute('height').hasValue()) element.attribute('height', true).value = this.attribute('height').value; return element; } this.path = function(ctx) { var element = this.getDefinition(); if (element != null) element.path(ctx); } this.renderChildren = function(ctx) { var element = this.getDefinition(); if (element != null) element.render(ctx); } } svg.Element.use.prototype = new svg.Element.RenderedElementBase; // mask element svg.Element.mask = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.apply = function(ctx, element) { // render as temp svg var x = this.attribute('x').Length.toPixels('x'); var y = this.attribute('y').Length.toPixels('y'); var width = this.attribute('width').Length.toPixels('x'); var height = this.attribute('height').Length.toPixels('y'); // temporarily remove mask to avoid recursion var mask = element.attribute('mask').value; element.attribute('mask').value = ''; var cMask = document.createElement('canvas'); cMask.width = x + width; cMask.height = y + height; var maskCtx = cMask.getContext('2d'); this.renderChildren(maskCtx); var c = document.createElement('canvas'); c.width = x + width; c.height = y + height; var tempCtx = c.getContext('2d'); element.render(tempCtx); tempCtx.globalCompositeOperation = 'destination-in'; tempCtx.fillStyle = maskCtx.createPattern(cMask, 'no-repeat'); tempCtx.fillRect(0, 0, x + width, y + height); ctx.fillStyle = tempCtx.createPattern(c, 'no-repeat'); ctx.fillRect(0, 0, x + width, y + height); // reassign mask element.attribute('mask').value = mask; } this.render = function(ctx) { // NO RENDER } } svg.Element.mask.prototype = new svg.Element.ElementBase; // clip element svg.Element.clipPath = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.apply = function(ctx) { for (var i=0; i<this.children.length; i++) { if (this.children[i].path) { this.children[i].path(ctx); ctx.clip(); } } } this.render = function(ctx) { // NO RENDER } } svg.Element.clipPath.prototype = new svg.Element.ElementBase; // filters svg.Element.filter = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.apply = function(ctx, element) { // render as temp svg var bb = element.getBoundingBox(); var x = this.attribute('x').Length.toPixels('x'); var y = this.attribute('y').Length.toPixels('y'); if (x == 0 || y == 0) { x = bb.x1; y = bb.y1; } var width = this.attribute('width').Length.toPixels('x'); var height = this.attribute('height').Length.toPixels('y'); if (width == 0 || height == 0) { width = bb.width(); height = bb.height(); } // temporarily remove filter to avoid recursion var filter = element.style('filter').value; element.style('filter').value = ''; // max filter distance var extraPercent = .20; var px = extraPercent * width; var py = extraPercent * height; var c = document.createElement('canvas'); c.width = width + 2*px; c.height = height + 2*py; var tempCtx = c.getContext('2d'); tempCtx.translate(-x + px, -y + py); element.render(tempCtx); // apply filters for (var i=0; i<this.children.length; i++) { this.children[i].apply(tempCtx, 0, 0, width + 2*px, height + 2*py); } // render on me ctx.drawImage(c, 0, 0, width + 2*px, height + 2*py, x - px, y - py, width + 2*px, height + 2*py); // reassign filter element.style('filter', true).value = filter; } this.render = function(ctx) { // NO RENDER } } svg.Element.filter.prototype = new svg.Element.ElementBase; svg.Element.feGaussianBlur = function(node) { this.base = svg.Element.ElementBase; this.base(node); function make_fgauss(sigma) { sigma = Math.max(sigma, 0.01); var len = Math.ceil(sigma * 4.0) + 1; mask = []; for (var i = 0; i < len; i++) { mask[i] = Math.exp(-0.5 * (i / sigma) * (i / sigma)); } return mask; } function normalize(mask) { var sum = 0; for (var i = 1; i < mask.length; i++) { sum += Math.abs(mask[i]); } sum = 2 * sum + Math.abs(mask[0]); for (var i = 0; i < mask.length; i++) { mask[i] /= sum; } return mask; } function convolve_even(src, dst, mask, width, height) { for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var a = imGet(src, x, y, width, height, 3)/255; for (var rgba = 0; rgba < 4; rgba++) { var sum = mask[0] * (a==0?255:imGet(src, x, y, width, height, rgba)) * (a==0||rgba==3?1:a); for (var i = 1; i < mask.length; i++) { var a1 = imGet(src, Math.max(x-i,0), y, width, height, 3)/255; var a2 = imGet(src, Math.min(x+i, width-1), y, width, height, 3)/255; sum += mask[i] * ((a1==0?255:imGet(src, Math.max(x-i,0), y, width, height, rgba)) * (a1==0||rgba==3?1:a1) + (a2==0?255:imGet(src, Math.min(x+i, width-1), y, width, height, rgba)) * (a2==0||rgba==3?1:a2)); } imSet(dst, y, x, height, width, rgba, sum); } } } } function imGet(img, x, y, width, height, rgba) { return img[y*width*4 + x*4 + rgba]; } function imSet(img, x, y, width, height, rgba, val) { img[y*width*4 + x*4 + rgba] = val; } function blur(ctx, width, height, sigma) { var srcData = ctx.getImageData(0, 0, width, height); var mask = make_fgauss(sigma); mask = normalize(mask); tmp = []; convolve_even(srcData.data, tmp, mask, width, height); convolve_even(tmp, srcData.data, mask, height, width); ctx.clearRect(0, 0, width, height); ctx.putImageData(srcData, 0, 0); } this.apply = function(ctx, x, y, width, height) { // assuming x==0 && y==0 for now blur(ctx, width, height, this.attribute('stdDeviation').numValue()); } } svg.Element.filter.prototype = new svg.Element.feGaussianBlur; // title element, do nothing svg.Element.title = function(node) { } svg.Element.title.prototype = new svg.Element.ElementBase; // desc element, do nothing svg.Element.desc = function(node) { } svg.Element.desc.prototype = new svg.Element.ElementBase; svg.Element.MISSING = function(node) { console.log('ERROR: Element \'' + node.nodeName + '\' not yet implemented.'); } svg.Element.MISSING.prototype = new svg.Element.ElementBase; // element factory svg.CreateElement = function(node) { var className = node.nodeName.replace(/^[^:]+:/,''); // remove namespace className = className.replace(/\-/g,''); // remove dashes var e = null; if (typeof(svg.Element[className]) != 'undefined') { e = new svg.Element[className](node); } else { e = new svg.Element.MISSING(node); } e.type = node.nodeName; return e; } // load from url svg.load = function(ctx, url) { svg.loadXml(ctx, svg.ajax(url)); } // load from xml svg.loadXml = function(ctx, xml) { svg.loadXmlDoc(ctx, svg.parseXml(xml)); } svg.loadXmlDoc = function(ctx, dom) { svg.init(ctx); var mapXY = function(p) { var e = ctx.canvas; while (e) { p.x -= e.offsetLeft; p.y -= e.offsetTop; e = e.offsetParent; } if (window.scrollX) p.x += window.scrollX; if (window.scrollY) p.y += window.scrollY; return p; } // bind mouse if (svg.opts['ignoreMouse'] != true) { ctx.canvas.onclick = function(e) { var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY)); svg.Mouse.onclick(p.x, p.y); }; ctx.canvas.onmousemove = function(e) { var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY)); svg.Mouse.onmousemove(p.x, p.y); }; } var e = svg.CreateElement(dom.documentElement); e.root = true; // render loop var isFirstRender = true; var draw = function() { svg.ViewPort.Clear(); if (ctx.canvas.parentNode) svg.ViewPort.SetCurrent(ctx.canvas.parentNode.clientWidth, ctx.canvas.parentNode.clientHeight); if (svg.opts['ignoreDimensions'] != true) { // set canvas size if (e.style('width').hasValue()) { ctx.canvas.width = e.style('width').Length.toPixels('x'); ctx.canvas.style.width = ctx.canvas.width + 'px'; } if (e.style('height').hasValue()) { ctx.canvas.height = e.style('height').Length.toPixels('y'); ctx.canvas.style.height = ctx.canvas.height + 'px'; } } var cWidth = ctx.canvas.clientWidth || ctx.canvas.width; var cHeight = ctx.canvas.clientHeight || ctx.canvas.height; svg.ViewPort.SetCurrent(cWidth, cHeight); if (svg.opts != null && svg.opts['offsetX'] != null) e.attribute('x', true).value = svg.opts['offsetX']; if (svg.opts != null && svg.opts['offsetY'] != null) e.attribute('y', true).value = svg.opts['offsetY']; if (svg.opts != null && svg.opts['scaleWidth'] != null && svg.opts['scaleHeight'] != null) { var xRatio = 1, yRatio = 1; if (e.attribute('width').hasValue()) xRatio = e.attribute('width').Length.toPixels('x') / svg.opts['scaleWidth']; if (e.attribute('height').hasValue()) yRatio = e.attribute('height').Length.toPixels('y') / svg.opts['scaleHeight']; e.attribute('width', true).value = svg.opts['scaleWidth']; e.attribute('height', true).value = svg.opts['scaleHeight']; e.attribute('viewBox', true).value = '0 0 ' + (cWidth * xRatio) + ' ' + (cHeight * yRatio); e.attribute('preserveAspectRatio', true).value = 'none'; } // clear and render if (svg.opts['ignoreClear'] != true) { ctx.clearRect(0, 0, cWidth, cHeight); } e.render(ctx); if (isFirstRender) { isFirstRender = false; if (svg.opts != null && typeof(svg.opts['renderCallback']) == 'function') svg.opts['renderCallback'](); } } var waitingForImages = true; if (svg.ImagesLoaded()) { waitingForImages = false; draw(); } svg.intervalID = setInterval(function() { var needUpdate = false; if (waitingForImages && svg.ImagesLoaded()) { waitingForImages = false; needUpdate = true; } // need update from mouse events? if (svg.opts['ignoreMouse'] != true) { needUpdate = needUpdate | svg.Mouse.hasEvents(); } // need update from animations? if (svg.opts['ignoreAnimation'] != true) { for (var i=0; i<svg.Animations.length; i++) { needUpdate = needUpdate | svg.Animations[i].update(1000 / svg.FRAMERATE); } } // need update from redraw? if (svg.opts != null && typeof(svg.opts['forceRedraw']) == 'function') { if (svg.opts['forceRedraw']() == true) needUpdate = true; } // render if needed if (needUpdate) { draw(); svg.Mouse.runEvents(); // run and clear our events } }, 1000 / svg.FRAMERATE); } svg.stop = function() { if (svg.intervalID) { clearInterval(svg.intervalID); } } svg.Mouse = new (function() { this.events = []; this.hasEvents = function() { return this.events.length != 0; } this.onclick = function(x, y) { this.events.push({ type: 'onclick', x: x, y: y, run: function(e) { if (e.onclick) e.onclick(); } }); } this.onmousemove = function(x, y) { this.events.push({ type: 'onmousemove', x: x, y: y, run: function(e) { if (e.onmousemove) e.onmousemove(); } }); } this.eventElements = []; this.checkPath = function(element, ctx) { for (var i=0; i<this.events.length; i++) { var e = this.events[i]; if (ctx.isPointInPath && ctx.isPointInPath(e.x, e.y)) this.eventElements[i] = element; } } this.checkBoundingBox = function(element, bb) { for (var i=0; i<this.events.length; i++) { var e = this.events[i]; if (bb.isPointInBox(e.x, e.y)) this.eventElements[i] = element; } } this.runEvents = function() { svg.ctx.canvas.style.cursor = ''; for (var i=0; i<this.events.length; i++) { var e = this.events[i]; var element = this.eventElements[i]; while (element) { e.run(element); element = element.parent; } } // done running, clear this.events = []; this.eventElements = []; } }); return svg; } })(); if (CanvasRenderingContext2D) { CanvasRenderingContext2D.prototype.drawSvg = function(s, dx, dy, dw, dh) { canvg(this.canvas, s, { ignoreMouse: true, ignoreAnimation: true, ignoreDimensions: true, ignoreClear: true, offsetX: dx, offsetY: dy, scaleWidth: dw, scaleHeight: dh }); } }/** * @license Highcharts JS v2.3.5 (2012-12-19) * CanVGRenderer Extension module * * (c) 2011-2012 Torstein Hønsi, Erik Olsson * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts */ (function (Highcharts) { // encapsulate var UNDEFINED, DIV = 'div', ABSOLUTE = 'absolute', RELATIVE = 'relative', HIDDEN = 'hidden', VISIBLE = 'visible', PX = 'px', css = Highcharts.css, CanVGRenderer = Highcharts.CanVGRenderer, SVGRenderer = Highcharts.SVGRenderer, extend = Highcharts.extend, merge = Highcharts.merge, addEvent = Highcharts.addEvent, createElement = Highcharts.createElement, discardElement = Highcharts.discardElement; // Extend CanVG renderer on demand, inherit from SVGRenderer extend(CanVGRenderer.prototype, SVGRenderer.prototype); // Add additional functionality: extend(CanVGRenderer.prototype, { create: function (chart, container, chartWidth, chartHeight) { this.setContainer(container, chartWidth, chartHeight); this.configure(chart); }, setContainer: function (container, chartWidth, chartHeight) { var containerStyle = container.style, containerParent = container.parentNode, containerLeft = containerStyle.left, containerTop = containerStyle.top, containerOffsetWidth = container.offsetWidth, containerOffsetHeight = container.offsetHeight, canvas, initialHiddenStyle = { visibility: HIDDEN, position: ABSOLUTE }; this.init.apply(this, [container, chartWidth, chartHeight]); // add the canvas above it canvas = createElement('canvas', { width: containerOffsetWidth, height: containerOffsetHeight }, { position: RELATIVE, left: containerLeft, top: containerTop }, container); this.canvas = canvas; // Create the tooltip line and div, they are placed as siblings to // the container (and as direct childs to the div specified in the html page) this.ttLine = createElement(DIV, null, initialHiddenStyle, containerParent); this.ttDiv = createElement(DIV, null, initialHiddenStyle, containerParent); this.ttTimer = UNDEFINED; // Move away the svg node to a new div inside the container's parent so we can hide it. var hiddenSvg = createElement(DIV, { width: containerOffsetWidth, height: containerOffsetHeight }, { visibility: HIDDEN, left: containerLeft, top: containerTop }, containerParent); this.hiddenSvg = hiddenSvg; hiddenSvg.appendChild(this.box); }, /** * Configures the renderer with the chart. Attach a listener to the event tooltipRefresh. **/ configure: function (chart) { var renderer = this, options = chart.options.tooltip, borderWidth = options.borderWidth, tooltipDiv = renderer.ttDiv, tooltipDivStyle = options.style, tooltipLine = renderer.ttLine, padding = parseInt(tooltipDivStyle.padding, 10); // Add border styling from options to the style tooltipDivStyle = merge(tooltipDivStyle, { padding: padding + PX, 'background-color': options.backgroundColor, 'border-style': 'solid', 'border-width': borderWidth + PX, 'border-radius': options.borderRadius + PX }); // Optionally add shadow if (options.shadow) { tooltipDivStyle = merge(tooltipDivStyle, { 'box-shadow': '1px 1px 3px gray', // w3c '-webkit-box-shadow': '1px 1px 3px gray' // webkit }); } css(tooltipDiv, tooltipDivStyle); // Set simple style on the line css(tooltipLine, { 'border-left': '1px solid darkgray' }); // This event is triggered when a new tooltip should be shown addEvent(chart, 'tooltipRefresh', function (args) { var chartContainer = chart.container, offsetLeft = chartContainer.offsetLeft, offsetTop = chartContainer.offsetTop, position; // Set the content of the tooltip tooltipDiv.innerHTML = args.text; // Compute the best position for the tooltip based on the divs size and container size. position = chart.tooltip.getPosition(tooltipDiv.offsetWidth, tooltipDiv.offsetHeight, {plotX: args.x, plotY: args.y}); css(tooltipDiv, { visibility: VISIBLE, left: position.x + PX, top: position.y + PX, 'border-color': args.borderColor }); // Position the tooltip line css(tooltipLine, { visibility: VISIBLE, left: offsetLeft + args.x + PX, top: offsetTop + chart.plotTop + PX, height: chart.plotHeight + PX }); // This timeout hides the tooltip after 3 seconds // First clear any existing timer if (renderer.ttTimer !== UNDEFINED) { clearTimeout(renderer.ttTimer); } // Start a new timer that hides tooltip and line renderer.ttTimer = setTimeout(function () { css(tooltipDiv, { visibility: HIDDEN }); css(tooltipLine, { visibility: HIDDEN }); }, 3000); }); }, /** * Extend SVGRenderer.destroy to also destroy the elements added by CanVGRenderer. */ destroy: function () { var renderer = this; // Remove the canvas discardElement(renderer.canvas); // Kill the timer if (renderer.ttTimer !== UNDEFINED) { clearTimeout(renderer.ttTimer); } // Remove the divs for tooltip and line discardElement(renderer.ttLine); discardElement(renderer.ttDiv); discardElement(renderer.hiddenSvg); // Continue with base class return SVGRenderer.prototype.destroy.apply(renderer); }, /** * Take a color and return it if it's a string, do not make it a gradient even if it is a * gradient. Currently canvg cannot render gradients (turns out black), * see: http://code.google.com/p/canvg/issues/detail?id=104 * * @param {Object} color The color or config object */ color: function (color, elem, prop) { if (color && color.linearGradient) { // Pick the end color and forward to base implementation color = color.stops[color.stops.length - 1][1]; } return SVGRenderer.prototype.color.call(this, color, elem, prop); }, /** * Draws the SVG on the canvas or adds a draw invokation to the deferred list. */ draw: function () { var renderer = this; window.canvg(renderer.canvas, renderer.hiddenSvg.innerHTML); } }); }(Highcharts));
JavaScript
/** * @license Data plugin for Highcharts v0.1 * * (c) 2012 Torstein Hønsi * * License: www.highcharts.com/license */ /* * The Highcharts Data plugin is a utility to ease parsing of input sources like * CSV, HTML tables or grid views into basic configuration options for use * directly in the Highcharts constructor. * * Demo: http://jsfiddle.net/highcharts/SnLFj/ * * --- OPTIONS --- * * - columns : Array<Array<Mixed>> * A two-dimensional array representing the input data on tabular form. This input can * be used when the data is already parsed, for example from a grid view component. * Each cell can be a string or number. If not switchRowsAndColumns is set, the columns * are interpreted as series. See also the rows option. * * - complete : Function(chartOptions) * The callback that is evaluated when the data is finished loading, optionally from an * external source, and parsed. The first argument passed is a finished chart options * object, containing series and an xAxis with categories if applicable. Thise options * can be extended with additional options and passed directly to the chart constructor. * * - csv : String * A comma delimited string to be parsed. Related options are startRow, endRow, startColumn * and endColumn to delimit what part of the table is used. The lineDelimiter and * itemDelimiter options define the CSV delimiter formats. * * - endColumn : Integer * In tabular input data, the first row (indexed by 0) to use. Defaults to the last * column containing data. * * - endRow : Integer * In tabular input data, the last row (indexed by 0) to use. Defaults to the last row * containing data. * * - googleSpreadsheetKey : String * A Google Spreadsheet key. See https://developers.google.com/gdata/samples/spreadsheet_sample * for general information on GS. * * - googleSpreadsheetKey : String * The Google Spreadsheet worksheet. The available id's can be read from * https://spreadsheets.google.com/feeds/worksheets/{key}/public/basic * * - itemDilimiter : String * Item or cell delimiter for parsing CSV. Defaults to ",". * * - lineDilimiter : String * Line delimiter for parsing CSV. Defaults to "\n". * * - parsed : Function * A callback function to access the parsed columns, the two-dimentional input data * array directly, before they are interpreted into series data and categories. * * - parseDate : Function * A callback function to parse string representations of dates into JavaScript timestamps. * Return an integer on success. * * - rows : Array<Array<Mixed>> * The same as the columns input option, but defining rows intead of columns. * * - startColumn : Integer * In tabular input data, the first column (indexed by 0) to use. * * - startRow : Integer * In tabular input data, the first row (indexed by 0) to use. * * - table : String|HTMLElement * A HTML table or the id of such to be parsed as input data. Related options ara startRow, * endRow, startColumn and endColumn to delimit what part of the table is used. */ /*global jQuery */ (function (Highcharts) { // Utilities var each = Highcharts.each; // The Data constructor var Data = function (options) { this.init(options); }; // Set the prototype properties Highcharts.extend(Data.prototype, { /** * Initialize the Data object with the given options */ init: function (options) { this.options = options; this.columns = options.columns || this.rowsToColumns(options.rows) || []; // No need to parse or interpret anything if (this.columns.length) { this.dataFound(); // Parse and interpret } else { // Parse a CSV string if options.csv is given this.parseCSV(); // Parse a HTML table if options.table is given this.parseTable(); // Parse a Google Spreadsheet this.parseGoogleSpreadsheet(); } }, dataFound: function () { // Interpret the values into right types this.parseTypes(); // Use first row for series names? this.findHeaderRow(); // Handle columns if a handleColumns callback is given this.parsed(); // Complete if a complete callback is given this.complete(); }, /** * Parse a CSV input string */ parseCSV: function () { var options = this.options, csv = options.csv, columns = this.columns, startRow = options.startRow || 0, endRow = options.endRow || Number.MAX_VALUE, startColumn = options.startColumn || 0, endColumn = options.endColumn || Number.MAX_VALUE, lines; if (csv) { lines = csv .replace(/\r\n/g, "\n") // Unix .replace(/\r/g, "\n") // Mac .split(options.lineDelimiter || "\n"); each(lines, function (line, rowNo) { if (rowNo >= startRow && rowNo <= endRow) { var items = line.split(options.itemDelimiter || ','); each(items, function (item, colNo) { if (colNo >= startColumn && colNo <= endColumn) { if (!columns[colNo - startColumn]) { columns[colNo - startColumn] = []; } columns[colNo - startColumn][rowNo - startRow] = item; } }); } }); this.dataFound(); } }, /** * Parse a HTML table */ parseTable: function () { var options = this.options, table = options.table, columns = this.columns, startRow = options.startRow || 0, endRow = options.endRow || Number.MAX_VALUE, startColumn = options.startColumn || 0, endColumn = options.endColumn || Number.MAX_VALUE, colNo; if (table) { if (typeof table === 'string') { table = document.getElementById(table); } each(table.getElementsByTagName('tr'), function (tr, rowNo) { colNo = 0; if (rowNo >= startRow && rowNo <= endRow) { each(tr.childNodes, function (item) { if ((item.tagName === 'TD' || item.tagName === 'TH') && colNo >= startColumn && colNo <= endColumn) { if (!columns[colNo]) { columns[colNo] = []; } columns[colNo][rowNo - startRow] = item.innerHTML; colNo += 1; } }); } }); this.dataFound(); // continue } }, /** * TODO: * - switchRowsAndColumns * - startRow, endRow etc. */ parseGoogleSpreadsheet: function () { var self = this, options = this.options, googleSpreadsheetKey = options.googleSpreadsheetKey, columns = this.columns; if (googleSpreadsheetKey) { jQuery.getJSON('https://spreadsheets.google.com/feeds/cells/' + googleSpreadsheetKey + '/' + (options.googleSpreadsheetWorksheet || 'od6') + '/public/values?alt=json-in-script&callback=?', function (json) { // Prepare the data from the spreadsheat var cells = json.feed.entry, cell, cellCount = cells.length, colCount = 0, rowCount = 0, i; // First, find the total number of columns and rows that // are actually filled with data for (i = 0; i < cellCount; i++) { cell = cells[i]; colCount = Math.max(colCount, cell.gs$cell.col); rowCount = Math.max(rowCount, cell.gs$cell.row); } // Set up arrays containing the column data for (i = 0; i < colCount; i++) { columns[i] = new Array(rowCount); } // Loop over the cells and assign the value to the right // place in the column arrays for (i = 0; i < cellCount; i++) { cell = cells[i]; columns[cell.gs$cell.col - 1][cell.gs$cell.row - 1] = cell.content.$t; } self.dataFound(); }); } }, /** * Find the header row. For now, we just check whether the first row contains * numbers or strings. Later we could loop down and find the first row with * numbers. */ findHeaderRow: function () { var headerRow = 0; each(this.columns, function (column) { if (typeof column[0] !== 'string') { headerRow = null; } }); this.headerRow = 0; }, /** * Trim a string from whitespace */ trim: function (str) { //return typeof str === 'number' ? str : str.replace(/^\s+|\s+$/g, ''); // fails with spreadsheet return typeof str === 'string' ? str.replace(/^\s+|\s+$/g, '') : str; }, /** * Parse numeric cells in to number types and date types in to true dates. * @param {Object} columns */ parseTypes: function () { var columns = this.columns, col = columns.length, row, val, floatVal, trimVal, dateVal; while (col--) { row = columns[col].length; while (row--) { val = columns[col][row]; floatVal = parseFloat(val); trimVal = this.trim(val); /*jslint eqeq: true*/ if (trimVal == floatVal) { // is numeric /*jslint eqeq: false*/ columns[col][row] = floatVal; // If the number is greater than milliseconds in a year, assume datetime if (floatVal > 365 * 24 * 3600 * 1000) { columns[col].isDatetime = true; } else { columns[col].isNumeric = true; } } else { // string, continue to determine if it is a date string or really a string dateVal = this.parseDate(val); if (col === 0 && typeof dateVal === 'number' && !isNaN(dateVal)) { // is date columns[col][row] = dateVal; columns[col].isDatetime = true; } else { // string columns[col][row] = trimVal; } } } } }, //* dateFormats: { 'YYYY-mm-dd': { regex: '^([0-9]{4})-([0-9]{2})-([0-9]{2})$', parser: function (match) { return Date.UTC(+match[1], match[2] - 1, +match[3]); } } }, // */ /** * Parse a date and return it as a number. Overridable through options.parseDate. */ parseDate: function (val) { var parseDate = this.options.parseDate, ret, key, format, match; if (parseDate) { ret = parseDate; } if (typeof val === 'string') { for (key in this.dateFormats) { format = this.dateFormats[key]; match = val.match(format.regex); if (match) { ret = format.parser(match); } } } return ret; }, /** * Reorganize rows into columns */ rowsToColumns: function (rows) { var row, rowsLength, col, colsLength, columns; if (rows) { columns = []; rowsLength = rows.length; for (row = 0; row < rowsLength; row++) { colsLength = rows[row].length; for (col = 0; col < colsLength; col++) { if (!columns[col]) { columns[col] = []; } columns[col][row] = rows[row][col]; } } } return columns; }, /** * A hook for working directly on the parsed columns */ parsed: function () { if (this.options.parsed) { this.options.parsed.call(this, this.columns); } }, /** * If a complete callback function is provided in the options, interpret the * columns into a Highcharts options object. */ complete: function () { var columns = this.columns, hasXData, categories, firstCol, type, options = this.options, series, data, name, i, j; if (options.complete) { // Use first column for X data or categories? if (columns.length > 1) { firstCol = columns.shift(); if (this.headerRow === 0) { firstCol.shift(); // remove the first cell } // Use the first column for categories or X values hasXData = firstCol.isNumeric || firstCol.isDatetime; if (!hasXData) { // means type is neither datetime nor linear categories = firstCol; } if (firstCol.isDatetime) { type = 'datetime'; } } // Use the next columns for series series = []; for (i = 0; i < columns.length; i++) { if (this.headerRow === 0) { name = columns[i].shift(); } data = []; for (j = 0; j < columns[i].length; j++) { data[j] = columns[i][j] !== undefined ? (hasXData ? [firstCol[j], columns[i][j]] : columns[i][j] ) : null; } series[i] = { name: name, data: data }; } // Do the callback options.complete({ xAxis: { categories: categories, type: type }, series: series }); } } }); // Register the Data prototype and data function on Highcharts Highcharts.Data = Data; Highcharts.data = function (options) { return new Data(options); }; // Extend Chart.init so that the Chart constructor accepts a new configuration // option group, data. Highcharts.wrap(Highcharts.Chart.prototype, 'init', function (proceed, userOptions, callback) { var chart = this; if (userOptions && userOptions.data) { Highcharts.data(Highcharts.extend(userOptions.data, { complete: function (dataOptions) { var datasets = []; // Don't merge the data arrays themselves each(dataOptions.series, function (series, i) { datasets[i] = series.data; series.data = null; }); // Do the merge userOptions = Highcharts.merge(dataOptions, userOptions); // Re-insert the data each(datasets, function (data, i) { userOptions.series[i].data = data; }); proceed.call(chart, userOptions, callback); } })); } else { proceed.call(chart, userOptions, callback); } }); }(Highcharts));
JavaScript
/** * @license Highcharts JS v2.3.5 (2012-12-19) * Exporting module * * (c) 2010-2011 Torstein Hønsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, document, window, Math, setTimeout */ (function (Highcharts) { // encapsulate // create shortcuts var Chart = Highcharts.Chart, addEvent = Highcharts.addEvent, removeEvent = Highcharts.removeEvent, createElement = Highcharts.createElement, discardElement = Highcharts.discardElement, css = Highcharts.css, merge = Highcharts.merge, each = Highcharts.each, extend = Highcharts.extend, math = Math, mathMax = math.max, doc = document, win = window, isTouchDevice = Highcharts.isTouchDevice, M = 'M', L = 'L', DIV = 'div', HIDDEN = 'hidden', NONE = 'none', PREFIX = 'highcharts-', ABSOLUTE = 'absolute', PX = 'px', UNDEFINED, symbols = Highcharts.Renderer.prototype.symbols, defaultOptions = Highcharts.getOptions(); // Add language extend(defaultOptions.lang, { downloadPNG: 'Download PNG image', downloadJPEG: 'Download JPEG image', downloadPDF: 'Download PDF document', downloadSVG: 'Download SVG vector image', exportButtonTitle: 'Export to raster or vector image', printButtonTitle: 'Print the chart' }); // Buttons and menus are collected in a separate config option set called 'navigation'. // This can be extended later to add control buttons like zoom and pan right click menus. defaultOptions.navigation = { menuStyle: { border: '1px solid #A0A0A0', background: '#FFFFFF' }, menuItemStyle: { padding: '0 5px', background: NONE, color: '#303030', fontSize: isTouchDevice ? '14px' : '11px' }, menuItemHoverStyle: { background: '#4572A5', color: '#FFFFFF' }, buttonOptions: { align: 'right', backgroundColor: { linearGradient: [0, 0, 0, 20], stops: [ [0.4, '#F7F7F7'], [0.6, '#E3E3E3'] ] }, borderColor: '#B0B0B0', borderRadius: 3, borderWidth: 1, //enabled: true, height: 20, hoverBorderColor: '#909090', hoverSymbolFill: '#81A7CF', hoverSymbolStroke: '#4572A5', symbolFill: '#E0E0E0', //symbolSize: 12, symbolStroke: '#A0A0A0', //symbolStrokeWidth: 1, symbolX: 11.5, symbolY: 10.5, verticalAlign: 'top', width: 24, y: 10 } }; // Add the export related options defaultOptions.exporting = { //enabled: true, //filename: 'chart', type: 'image/png', url: 'http://export.highcharts.com/', width: 800, buttons: { exportButton: { //enabled: true, symbol: 'exportIcon', x: -10, symbolFill: '#A8BF77', hoverSymbolFill: '#768F3E', _id: 'exportButton', _titleKey: 'exportButtonTitle', menuItems: [{ textKey: 'downloadPNG', onclick: function () { this.exportChart(); } }, { textKey: 'downloadJPEG', onclick: function () { this.exportChart({ type: 'image/jpeg' }); } }, { textKey: 'downloadPDF', onclick: function () { this.exportChart({ type: 'application/pdf' }); } }, { textKey: 'downloadSVG', onclick: function () { this.exportChart({ type: 'image/svg+xml' }); } } // Enable this block to add "View SVG" to the dropdown menu /* ,{ text: 'View SVG', onclick: function () { var svg = this.getSVG() .replace(/</g, '\n&lt;') .replace(/>/g, '&gt;'); doc.body.innerHTML = '<pre>' + svg + '</pre>'; } } // */ ] }, printButton: { //enabled: true, symbol: 'printIcon', x: -36, symbolFill: '#B5C9DF', hoverSymbolFill: '#779ABF', _id: 'printButton', _titleKey: 'printButtonTitle', onclick: function () { this.print(); } } } }; // Add the Highcharts.post utility Highcharts.post = function (url, data) { var name, form; // create the form form = createElement('form', { method: 'post', action: url, enctype: 'multipart/form-data' }, { display: NONE }, doc.body); // add the data for (name in data) { createElement('input', { type: HIDDEN, name: name, value: data[name] }, null, form); } // submit form.submit(); // clean up discardElement(form); }; extend(Chart.prototype, { /** * Return an SVG representation of the chart * * @param additionalOptions {Object} Additional chart options for the generated SVG representation */ getSVG: function (additionalOptions) { var chart = this, chartCopy, sandbox, svg, seriesOptions, options = merge(chart.options, additionalOptions); // copy the options and add extra options // IE compatibility hack for generating SVG content that it doesn't really understand if (!doc.createElementNS) { /*jslint unparam: true*//* allow unused parameter ns in function below */ doc.createElementNS = function (ns, tagName) { return doc.createElement(tagName); }; /*jslint unparam: false*/ } // create a sandbox where a new chart will be generated sandbox = createElement(DIV, null, { position: ABSOLUTE, top: '-9999em', width: chart.chartWidth + PX, height: chart.chartHeight + PX }, doc.body); // override some options extend(options.chart, { renderTo: sandbox, forExport: true }); options.exporting.enabled = false; // hide buttons in print options.chart.plotBackgroundImage = null; // the converter doesn't handle images // prepare for replicating the chart options.series = []; each(chart.series, function (serie) { seriesOptions = merge(serie.options, { animation: false, // turn off animation showCheckbox: false, visible: serie.visible }); if (!seriesOptions.isInternal) { // used for the navigator series that has its own option set options.series.push(seriesOptions); } }); // generate the chart copy chartCopy = new Highcharts.Chart(options); // reflect axis extremes in the export each(['xAxis', 'yAxis'], function (axisType) { each(chart[axisType], function (axis, i) { var axisCopy = chartCopy[axisType][i], extremes = axis.getExtremes(), userMin = extremes.userMin, userMax = extremes.userMax; if (userMin !== UNDEFINED || userMax !== UNDEFINED) { axisCopy.setExtremes(userMin, userMax, true, false); } }); }); // get the SVG from the container's innerHTML svg = chartCopy.container.innerHTML; // free up memory options = null; chartCopy.destroy(); discardElement(sandbox); // sanitize svg = svg .replace(/zIndex="[^"]+"/g, '') .replace(/isShadow="[^"]+"/g, '') .replace(/symbolName="[^"]+"/g, '') .replace(/jQuery[0-9]+="[^"]+"/g, '') .replace(/isTracker="[^"]+"/g, '') .replace(/url\([^#]+#/g, 'url(#') .replace(/<svg /, '<svg xmlns:xlink="http://www.w3.org/1999/xlink" ') .replace(/ href=/g, ' xlink:href=') .replace(/\n/, ' ') .replace(/<\/svg>.*?$/, '</svg>') // any HTML added to the container after the SVG (#894) /* This fails in IE < 8 .replace(/([0-9]+)\.([0-9]+)/g, function(s1, s2, s3) { // round off to save weight return s2 +'.'+ s3[0]; })*/ // Replace HTML entities, issue #347 .replace(/&nbsp;/g, '\u00A0') // no-break space .replace(/&shy;/g, '\u00AD') // soft hyphen // IE specific .replace(/<IMG /g, '<image ') .replace(/height=([^" ]+)/g, 'height="$1"') .replace(/width=([^" ]+)/g, 'width="$1"') .replace(/hc-svg-href="([^"]+)">/g, 'xlink:href="$1"/>') .replace(/id=([^" >]+)/g, 'id="$1"') .replace(/class=([^" ]+)/g, 'class="$1"') .replace(/ transform /g, ' ') .replace(/:(path|rect)/g, '$1') .replace(/style="([^"]+)"/g, function (s) { return s.toLowerCase(); }); // IE9 beta bugs with innerHTML. Test again with final IE9. svg = svg.replace(/(url\(#highcharts-[0-9]+)&quot;/g, '$1') .replace(/&quot;/g, "'"); if (svg.match(/ xmlns="/g).length === 2) { svg = svg.replace(/xmlns="[^"]+"/, ''); } return svg; }, /** * Submit the SVG representation of the chart to the server * @param {Object} options Exporting options. Possible members are url, type and width. * @param {Object} chartOptions Additional chart options for the SVG representation of the chart */ exportChart: function (options, chartOptions) { var exportingOptions = this.options.exporting, svg = this.getSVG(merge(exportingOptions.chartOptions, chartOptions)); // merge the options options = merge(exportingOptions, options); // do the post Highcharts.post(options.url, { filename: options.filename || 'chart', type: options.type, width: options.width, scale: options.scale || 2, svg: svg }); }, /** * Print the chart */ print: function () { var chart = this, container = chart.container, origDisplay = [], origParent = container.parentNode, body = doc.body, childNodes = body.childNodes; if (chart.isPrinting) { // block the button while in printing mode return; } chart.isPrinting = true; // hide all body content each(childNodes, function (node, i) { if (node.nodeType === 1) { origDisplay[i] = node.style.display; node.style.display = NONE; } }); // pull out the chart body.appendChild(container); // print win.print(); // allow the browser to prepare before reverting setTimeout(function () { // put the chart back in origParent.appendChild(container); // restore all body content each(childNodes, function (node, i) { if (node.nodeType === 1) { node.style.display = origDisplay[i]; } }); chart.isPrinting = false; }, 1000); }, /** * Display a popup menu for choosing the export type * * @param {String} name An identifier for the menu * @param {Array} items A collection with text and onclicks for the items * @param {Number} x The x position of the opener button * @param {Number} y The y position of the opener button * @param {Number} width The width of the opener button * @param {Number} height The height of the opener button */ contextMenu: function (name, items, x, y, width, height) { var chart = this, navOptions = chart.options.navigation, menuItemStyle = navOptions.menuItemStyle, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, cacheName = 'cache-' + name, menu = chart[cacheName], menuPadding = mathMax(width, height), // for mouse leave detection boxShadow = '3px 3px 10px #888', innerMenu, hide, hideTimer, menuStyle; // create the menu only the first time if (!menu) { // create a HTML element above the SVG chart[cacheName] = menu = createElement(DIV, { className: PREFIX + name }, { position: ABSOLUTE, zIndex: 1000, padding: menuPadding + PX }, chart.container); innerMenu = createElement(DIV, null, extend({ MozBoxShadow: boxShadow, WebkitBoxShadow: boxShadow, boxShadow: boxShadow }, navOptions.menuStyle), menu); // hide on mouse out hide = function () { css(menu, { display: NONE }); }; // Hide the menu some time after mouse leave (#1357) addEvent(menu, 'mouseleave', function () { hideTimer = setTimeout(hide, 500); }); addEvent(menu, 'mouseenter', function () { clearTimeout(hideTimer); }); // create the items each(items, function (item) { if (item) { var div = createElement(DIV, { onmouseover: function () { css(this, navOptions.menuItemHoverStyle); }, onmouseout: function () { css(this, menuItemStyle); }, innerHTML: item.text || chart.options.lang[item.textKey] }, extend({ cursor: 'pointer' }, menuItemStyle), innerMenu); div.onclick = function () { hide(); item.onclick.apply(chart, arguments); }; // Keep references to menu divs to be able to destroy them chart.exportDivElements.push(div); } }); // Keep references to menu and innerMenu div to be able to destroy them chart.exportDivElements.push(innerMenu, menu); chart.exportMenuWidth = menu.offsetWidth; chart.exportMenuHeight = menu.offsetHeight; } menuStyle = { display: 'block' }; // if outside right, right align it if (x + chart.exportMenuWidth > chartWidth) { menuStyle.right = (chartWidth - x - width - menuPadding) + PX; } else { menuStyle.left = (x - menuPadding) + PX; } // if outside bottom, bottom align it if (y + height + chart.exportMenuHeight > chartHeight) { menuStyle.bottom = (chartHeight - y - menuPadding) + PX; } else { menuStyle.top = (y + height - menuPadding) + PX; } css(menu, menuStyle); }, /** * Add the export button to the chart */ addButton: function (options) { var chart = this, renderer = chart.renderer, btnOptions = merge(chart.options.navigation.buttonOptions, options), onclick = btnOptions.onclick, menuItems = btnOptions.menuItems, buttonWidth = btnOptions.width, buttonHeight = btnOptions.height, box, symbol, button, menuKey, borderWidth = btnOptions.borderWidth, boxAttr = { stroke: btnOptions.borderColor }, symbolAttr = { stroke: btnOptions.symbolStroke, fill: btnOptions.symbolFill }, symbolSize = btnOptions.symbolSize || 12; if (!chart.btnCount) { chart.btnCount = 0; } menuKey = chart.btnCount++; // Keeps references to the button elements if (!chart.exportDivElements) { chart.exportDivElements = []; chart.exportSVGElements = []; } if (btnOptions.enabled === false) { return; } // element to capture the click function revert() { symbol.attr(symbolAttr); box.attr(boxAttr); } // the box border box = renderer.rect( 0, 0, buttonWidth, buttonHeight, btnOptions.borderRadius, borderWidth ) //.translate(buttonLeft, buttonTop) // to allow gradients .align(btnOptions, true) .attr(extend({ fill: btnOptions.backgroundColor, 'stroke-width': borderWidth, zIndex: 19 }, boxAttr)).add(); // the invisible element to track the clicks button = renderer.rect( 0, 0, buttonWidth, buttonHeight, 0 ) .align(btnOptions) .attr({ id: btnOptions._id, fill: 'rgba(255, 255, 255, 0.001)', title: chart.options.lang[btnOptions._titleKey], zIndex: 21 }).css({ cursor: 'pointer' }) .on('mouseover', function () { symbol.attr({ stroke: btnOptions.hoverSymbolStroke, fill: btnOptions.hoverSymbolFill }); box.attr({ stroke: btnOptions.hoverBorderColor }); }) .on('mouseout', revert) .on('click', revert) .add(); // add the click event if (menuItems) { onclick = function () { revert(); var bBox = button.getBBox(); chart.contextMenu('menu' + menuKey, menuItems, bBox.x, bBox.y, buttonWidth, buttonHeight); }; } /*addEvent(button.element, 'click', function() { onclick.apply(chart, arguments); });*/ button.on('click', function () { onclick.apply(chart, arguments); }); // the icon symbol = renderer.symbol( btnOptions.symbol, btnOptions.symbolX - (symbolSize / 2), btnOptions.symbolY - (symbolSize / 2), symbolSize, symbolSize ) .align(btnOptions, true) .attr(extend(symbolAttr, { 'stroke-width': btnOptions.symbolStrokeWidth || 1, zIndex: 20 })).add(); // Keep references to the renderer element so to be able to destroy them later. chart.exportSVGElements.push(box, button, symbol); }, /** * Destroy the buttons. */ destroyExport: function () { var i, chart = this, elem; // Destroy the extra buttons added for (i = 0; i < chart.exportSVGElements.length; i++) { elem = chart.exportSVGElements[i]; // Destroy and null the svg/vml elements elem.onclick = elem.ontouchstart = null; chart.exportSVGElements[i] = elem.destroy(); } // Destroy the divs for the menu for (i = 0; i < chart.exportDivElements.length; i++) { elem = chart.exportDivElements[i]; // Remove the event handler removeEvent(elem, 'mouseleave'); // Remove inline events chart.exportDivElements[i] = elem.onmouseout = elem.onmouseover = elem.ontouchstart = elem.onclick = null; // Destroy the div by moving to garbage bin discardElement(elem); } } }); /** * Crisp for 1px stroke width, which is default. In the future, consider a smarter, * global function. */ function crisp(arr) { var i = arr.length; while (i--) { if (typeof arr[i] === 'number') { arr[i] = Math.round(arr[i]) - 0.5; } } return arr; } // Create the export icon symbols.exportIcon = function (x, y, width, height) { return crisp([ M, // the disk x, y + width, L, x + width, y + height, x + width, y + height * 0.8, x, y + height * 0.8, 'Z', M, // the arrow x + width * 0.5, y + height * 0.8, L, x + width * 0.8, y + height * 0.4, x + width * 0.4, y + height * 0.4, x + width * 0.4, y, x + width * 0.6, y, x + width * 0.6, y + height * 0.4, x + width * 0.2, y + height * 0.4, 'Z' ]); }; // Create the print icon symbols.printIcon = function (x, y, width, height) { return crisp([ M, // the printer x, y + height * 0.7, L, x + width, y + height * 0.7, x + width, y + height * 0.4, x, y + height * 0.4, 'Z', M, // the upper sheet x + width * 0.2, y + height * 0.4, L, x + width * 0.2, y, x + width * 0.8, y, x + width * 0.8, y + height * 0.4, 'Z', M, // the lower sheet x + width * 0.2, y + height * 0.7, L, x, y + height, x + width, y + height, x + width * 0.8, y + height * 0.7, 'Z' ]); }; // Add the buttons on chart load Chart.prototype.callbacks.push(function (chart) { var n, exportingOptions = chart.options.exporting, buttons = exportingOptions.buttons; if (exportingOptions.enabled !== false) { for (n in buttons) { chart.addButton(buttons[n]); } // Destroy the export elements at chart destroy addEvent(chart, 'destroy', chart.destroyExport); } }); }(Highcharts));
JavaScript
/** * Dark blue theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#DDDF0D", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee", "#ff0066", "#eeaaee", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee"], chart: { backgroundColor: { linearGradient: [0, 0, 250, 500], stops: [ [0, 'rgb(48, 96, 48)'], [1, 'rgb(0, 0, 0)'] ] }, borderColor: '#000000', borderWidth: 2, className: 'dark-container', plotBackgroundColor: 'rgba(255, 255, 255, .1)', plotBorderColor: '#CCCCCC', plotBorderWidth: 1 }, title: { style: { color: '#C0C0C0', font: 'bold 16px "Trebuchet MS", Verdana, sans-serif' } }, subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, xAxis: { gridLineColor: '#333333', gridLineWidth: 1, labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', tickColor: '#A0A0A0', title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, yAxis: { gridLineColor: '#333333', labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', minorTickInterval: null, tickColor: '#A0A0A0', tickWidth: 1, title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, tooltip: { backgroundColor: 'rgba(0, 0, 0, 0.75)', style: { color: '#F0F0F0' } }, toolbar: { itemStyle: { color: 'silver' } }, plotOptions: { line: { dataLabels: { color: '#CCC' }, marker: { lineColor: '#333' } }, spline: { marker: { lineColor: '#333' } }, scatter: { marker: { lineColor: '#333' } }, candlestick: { lineColor: 'white' } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: '#A0A0A0' }, itemHoverStyle: { color: '#FFF' }, itemHiddenStyle: { color: '#444' } }, credits: { style: { color: '#666' } }, labels: { style: { color: '#CCC' } }, navigation: { buttonOptions: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#606060'], [0.6, '#333333'] ] }, borderColor: '#000000', symbolStroke: '#C0C0C0', hoverSymbolStroke: '#FFFFFF' } }, exporting: { buttons: { exportButton: { symbolFill: '#55BE3B' }, printButton: { symbolFill: '#7797BE' } } }, // scroll charts rangeSelector: { buttonTheme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, stroke: '#000000', style: { color: '#CCC', fontWeight: 'bold' }, states: { hover: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#BBB'], [0.6, '#888'] ] }, stroke: '#000000', style: { color: 'white' } }, select: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.1, '#000'], [0.3, '#333'] ] }, stroke: '#000000', style: { color: 'yellow' } } } }, inputStyle: { backgroundColor: '#333', color: 'silver' }, labelStyle: { color: 'silver' } }, navigator: { handles: { backgroundColor: '#666', borderColor: '#AAA' }, outlineColor: '#CCC', maskFill: 'rgba(16, 16, 16, 0.5)', series: { color: '#7798BF', lineColor: '#A6C7ED' } }, scrollbar: { barBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, barBorderColor: '#CCC', buttonArrowColor: '#CCC', buttonBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, buttonBorderColor: '#CCC', rifleColor: '#FFF', trackBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, '#000'], [1, '#333'] ] }, trackBorderColor: '#666' }, // special colors for some of the legendBackgroundColor: 'rgba(0, 0, 0, 0.5)', legendBackgroundColorSolid: 'rgb(35, 35, 70)', dataLabelsColor: '#444', textColor: '#C0C0C0', maskColor: 'rgba(255,255,255,0.3)' }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Skies theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#514F78", "#42A07B", "#9B5E4A", "#72727F", "#1F949A", "#82914E", "#86777F", "#42A07B"], chart: { className: 'skies', borderWidth: 0, plotShadow: true, plotBackgroundImage: '/demo/gfx/skies.jpg', plotBackgroundColor: { linearGradient: [0, 0, 250, 500], stops: [ [0, 'rgba(255, 255, 255, 1)'], [1, 'rgba(255, 255, 255, 0)'] ] }, plotBorderWidth: 1 }, title: { style: { color: '#3E576F', font: '16px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, subtitle: { style: { color: '#6D869F', font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, xAxis: { gridLineWidth: 0, lineColor: '#C0D0E0', tickColor: '#C0D0E0', labels: { style: { color: '#666', fontWeight: 'bold' } }, title: { style: { color: '#666', font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, yAxis: { alternateGridColor: 'rgba(255, 255, 255, .5)', lineColor: '#C0D0E0', tickColor: '#C0D0E0', tickWidth: 1, labels: { style: { color: '#666', fontWeight: 'bold' } }, title: { style: { color: '#666', font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: '#3E576F' }, itemHoverStyle: { color: 'black' }, itemHiddenStyle: { color: 'silver' } }, labels: { style: { color: '#3E576F' } } }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Dark blue theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#DDDF0D", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee", "#ff0066", "#eeaaee", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee"], chart: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 }, stops: [ [0, 'rgb(48, 48, 96)'], [1, 'rgb(0, 0, 0)'] ] }, borderColor: '#000000', borderWidth: 2, className: 'dark-container', plotBackgroundColor: 'rgba(255, 255, 255, .1)', plotBorderColor: '#CCCCCC', plotBorderWidth: 1 }, title: { style: { color: '#C0C0C0', font: 'bold 16px "Trebuchet MS", Verdana, sans-serif' } }, subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, xAxis: { gridLineColor: '#333333', gridLineWidth: 1, labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', tickColor: '#A0A0A0', title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, yAxis: { gridLineColor: '#333333', labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', minorTickInterval: null, tickColor: '#A0A0A0', tickWidth: 1, title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, tooltip: { backgroundColor: 'rgba(0, 0, 0, 0.75)', style: { color: '#F0F0F0' } }, toolbar: { itemStyle: { color: 'silver' } }, plotOptions: { line: { dataLabels: { color: '#CCC' }, marker: { lineColor: '#333' } }, spline: { marker: { lineColor: '#333' } }, scatter: { marker: { lineColor: '#333' } }, candlestick: { lineColor: 'white' } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: '#A0A0A0' }, itemHoverStyle: { color: '#FFF' }, itemHiddenStyle: { color: '#444' } }, credits: { style: { color: '#666' } }, labels: { style: { color: '#CCC' } }, navigation: { buttonOptions: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#606060'], [0.6, '#333333'] ] }, borderColor: '#000000', symbolStroke: '#C0C0C0', hoverSymbolStroke: '#FFFFFF' } }, exporting: { buttons: { exportButton: { symbolFill: '#55BE3B' }, printButton: { symbolFill: '#7797BE' } } }, // scroll charts rangeSelector: { buttonTheme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, stroke: '#000000', style: { color: '#CCC', fontWeight: 'bold' }, states: { hover: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#BBB'], [0.6, '#888'] ] }, stroke: '#000000', style: { color: 'white' } }, select: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.1, '#000'], [0.3, '#333'] ] }, stroke: '#000000', style: { color: 'yellow' } } } }, inputStyle: { backgroundColor: '#333', color: 'silver' }, labelStyle: { color: 'silver' } }, navigator: { handles: { backgroundColor: '#666', borderColor: '#AAA' }, outlineColor: '#CCC', maskFill: 'rgba(16, 16, 16, 0.5)', series: { color: '#7798BF', lineColor: '#A6C7ED' } }, scrollbar: { barBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, barBorderColor: '#CCC', buttonArrowColor: '#CCC', buttonBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, buttonBorderColor: '#CCC', rifleColor: '#FFF', trackBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, '#000'], [1, '#333'] ] }, trackBorderColor: '#666' }, // special colors for some of the legendBackgroundColor: 'rgba(0, 0, 0, 0.5)', legendBackgroundColorSolid: 'rgb(35, 35, 70)', dataLabelsColor: '#444', textColor: '#C0C0C0', maskColor: 'rgba(255,255,255,0.3)' }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Grid theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'], chart: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 }, stops: [ [0, 'rgb(255, 255, 255)'], [1, 'rgb(240, 240, 255)'] ] }, borderWidth: 2, plotBackgroundColor: 'rgba(255, 255, 255, .9)', plotShadow: true, plotBorderWidth: 1 }, title: { style: { color: '#000', font: 'bold 16px "Trebuchet MS", Verdana, sans-serif' } }, subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, xAxis: { gridLineWidth: 1, lineColor: '#000', tickColor: '#000', labels: { style: { color: '#000', font: '11px Trebuchet MS, Verdana, sans-serif' } }, title: { style: { color: '#333', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, yAxis: { minorTickInterval: 'auto', lineColor: '#000', lineWidth: 1, tickWidth: 1, tickColor: '#000', labels: { style: { color: '#000', font: '11px Trebuchet MS, Verdana, sans-serif' } }, title: { style: { color: '#333', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: 'black' }, itemHoverStyle: { color: '#039' }, itemHiddenStyle: { color: 'gray' } }, labels: { style: { color: '#99b' } } }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Gray theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#DDDF0D", "#7798BF", "#55BF3B", "#DF5353", "#aaeeee", "#ff0066", "#eeaaee", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee"], chart: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, 'rgb(96, 96, 96)'], [1, 'rgb(16, 16, 16)'] ] }, borderWidth: 0, borderRadius: 15, plotBackgroundColor: null, plotShadow: false, plotBorderWidth: 0 }, title: { style: { color: '#FFF', font: '16px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, subtitle: { style: { color: '#DDD', font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, xAxis: { gridLineWidth: 0, lineColor: '#999', tickColor: '#999', labels: { style: { color: '#999', fontWeight: 'bold' } }, title: { style: { color: '#AAA', font: 'bold 12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, yAxis: { alternateGridColor: null, minorTickInterval: null, gridLineColor: 'rgba(255, 255, 255, .1)', lineWidth: 0, tickWidth: 0, labels: { style: { color: '#999', fontWeight: 'bold' } }, title: { style: { color: '#AAA', font: 'bold 12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, legend: { itemStyle: { color: '#CCC' }, itemHoverStyle: { color: '#FFF' }, itemHiddenStyle: { color: '#333' } }, labels: { style: { color: '#CCC' } }, tooltip: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, 'rgba(96, 96, 96, .8)'], [1, 'rgba(16, 16, 16, .8)'] ] }, borderWidth: 0, style: { color: '#FFF' } }, plotOptions: { line: { dataLabels: { color: '#CCC' }, marker: { lineColor: '#333' } }, spline: { marker: { lineColor: '#333' } }, scatter: { marker: { lineColor: '#333' } }, candlestick: { lineColor: 'white' } }, toolbar: { itemStyle: { color: '#CCC' } }, navigation: { buttonOptions: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#606060'], [0.6, '#333333'] ] }, borderColor: '#000000', symbolStroke: '#C0C0C0', hoverSymbolStroke: '#FFFFFF' } }, exporting: { buttons: { exportButton: { symbolFill: '#55BE3B' }, printButton: { symbolFill: '#7797BE' } } }, // scroll charts rangeSelector: { buttonTheme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, stroke: '#000000', style: { color: '#CCC', fontWeight: 'bold' }, states: { hover: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#BBB'], [0.6, '#888'] ] }, stroke: '#000000', style: { color: 'white' } }, select: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.1, '#000'], [0.3, '#333'] ] }, stroke: '#000000', style: { color: 'yellow' } } } }, inputStyle: { backgroundColor: '#333', color: 'silver' }, labelStyle: { color: 'silver' } }, navigator: { handles: { backgroundColor: '#666', borderColor: '#AAA' }, outlineColor: '#CCC', maskFill: 'rgba(16, 16, 16, 0.5)', series: { color: '#7798BF', lineColor: '#A6C7ED' } }, scrollbar: { barBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, barBorderColor: '#CCC', buttonArrowColor: '#CCC', buttonBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, buttonBorderColor: '#CCC', rifleColor: '#FFF', trackBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, '#000'], [1, '#333'] ] }, trackBorderColor: '#666' }, // special colors for some of the demo examples legendBackgroundColor: 'rgba(48, 48, 48, 0.8)', legendBackgroundColorSolid: 'rgb(70, 70, 70)', dataLabelsColor: '#444', textColor: '#E0E0E0', maskColor: 'rgba(255,255,255,0.3)' }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highcharts JS v2.3.5 (2012-12-19) * * (c) 2009-2011 Torstein Hønsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console */ (function (Highcharts, UNDEFINED) { var each = Highcharts.each, extend = Highcharts.extend, merge = Highcharts.merge, map = Highcharts.map, pick = Highcharts.pick, pInt = Highcharts.pInt, defaultPlotOptions = Highcharts.getOptions().plotOptions, seriesTypes = Highcharts.seriesTypes, extendClass = Highcharts.extendClass, splat = Highcharts.splat, wrap = Highcharts.wrap, Axis = Highcharts.Axis, Tick = Highcharts.Tick, Series = Highcharts.Series, colProto = seriesTypes.column.prototype, noop = function () {};/** * The Pane object allows options that are common to a set of X and Y axes. * * In the future, this can be extended to basic Highcharts and Highstock. */ function Pane(options, chart, firstAxis) { this.init.call(this, options, chart, firstAxis); } // Extend the Pane prototype extend(Pane.prototype, { /** * Initiate the Pane object */ init: function (options, chart, firstAxis) { var pane = this, backgroundOption, defaultOptions = pane.defaultOptions; pane.chart = chart; // Set options if (chart.angular) { // gauges defaultOptions.background = {}; // gets extended by this.defaultBackgroundOptions } pane.options = options = merge(defaultOptions, options); backgroundOption = options.background; // To avoid having weighty logic to place, update and remove the backgrounds, // push them to the first axis' plot bands and borrow the existing logic there. if (backgroundOption) { each([].concat(splat(backgroundOption)).reverse(), function (config) { var backgroundColor = config.backgroundColor; // if defined, replace the old one (specific for gradients) config = merge(pane.defaultBackgroundOptions, config); if (backgroundColor) { config.backgroundColor = backgroundColor; } config.color = config.backgroundColor; // due to naming in plotBands firstAxis.options.plotBands.unshift(config); }); } }, /** * The default options object */ defaultOptions: { // background: {conditional}, center: ['50%', '50%'], size: '85%', startAngle: 0 //endAngle: startAngle + 360 }, /** * The default background options */ defaultBackgroundOptions: { shape: 'circle', borderWidth: 1, borderColor: 'silver', backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, '#FFF'], [1, '#DDD'] ] }, from: Number.MIN_VALUE, // corrected to axis min innerRadius: 0, to: Number.MAX_VALUE, // corrected to axis max outerRadius: '105%' } }); var axisProto = Axis.prototype, tickProto = Tick.prototype; /** * Augmented methods for the x axis in order to hide it completely, used for the X axis in gauges */ var hiddenAxisMixin = { getOffset: noop, redraw: function () { this.isDirty = false; // prevent setting Y axis dirty }, render: function () { this.isDirty = false; // prevent setting Y axis dirty }, setScale: noop, setCategories: noop, setTitle: noop }; /** * Augmented methods for the value axis */ /*jslint unparam: true*/ var radialAxisMixin = { isRadial: true, /** * The default options extend defaultYAxisOptions */ defaultRadialGaugeOptions: { labels: { align: 'center', x: 0, y: null // auto }, minorGridLineWidth: 0, minorTickInterval: 'auto', minorTickLength: 10, minorTickPosition: 'inside', minorTickWidth: 1, plotBands: [], tickLength: 10, tickPosition: 'inside', tickWidth: 2, title: { rotation: 0 }, zIndex: 2 // behind dials, points in the series group }, // Circular axis around the perimeter of a polar chart defaultRadialXOptions: { gridLineWidth: 1, // spokes labels: { align: null, // auto distance: 15, x: 0, y: null // auto }, maxPadding: 0, minPadding: 0, plotBands: [], showLastLabel: false, tickLength: 0 }, // Radial axis, like a spoke in a polar chart defaultRadialYOptions: { gridLineInterpolation: 'circle', labels: { align: 'right', x: -3, y: -2 }, plotBands: [], showLastLabel: false, title: { x: 4, text: null, rotation: 90 } }, /** * Merge and set options */ setOptions: function (userOptions) { this.options = merge( this.defaultOptions, this.defaultRadialOptions, userOptions ); }, /** * Wrap the getOffset method to return zero offset for title or labels in a radial * axis */ getOffset: function () { // Call the Axis prototype method (the method we're in now is on the instance) axisProto.getOffset.call(this); // Title or label offsets are not counted this.chart.axisOffset[this.side] = 0; // Set the center array this.center = this.pane.center = seriesTypes.pie.prototype.getCenter.call(this.pane); }, /** * Get the path for the axis line. This method is also referenced in the getPlotLinePath * method. */ getLinePath: function (lineWidth, radius) { var center = this.center; radius = pick(radius, center[2] / 2 - this.offset); return this.chart.renderer.symbols.arc( this.left + center[0], this.top + center[1], radius, radius, { start: this.startAngleRad, end: this.endAngleRad, open: true, innerR: 0 } ); }, /** * Override setAxisTranslation by setting the translation to the difference * in rotation. This allows the translate method to return angle for * any given value. */ setAxisTranslation: function () { // Call uber method axisProto.setAxisTranslation.call(this); // Set transA and minPixelPadding if (this.center) { // it's not defined the first time if (this.isCircular) { this.transA = (this.endAngleRad - this.startAngleRad) / ((this.max - this.min) || 1); } else { this.transA = (this.center[2] / 2) / ((this.max - this.min) || 1); } if (this.isXAxis) { this.minPixelPadding = this.transA * this.minPointOffset + (this.reversed ? (this.endAngleRad - this.startAngleRad) / 4 : 0); // ??? } } }, /** * In case of auto connect, add one closestPointRange to the max value right before * tickPositions are computed, so that ticks will extend passed the real max. */ beforeSetTickPositions: function () { if (this.autoConnect) { this.max += (this.categories && 1) || this.pointRange || this.closestPointRange; // #1197 } }, /** * Override the setAxisSize method to use the arc's circumference as length. This * allows tickPixelInterval to apply to pixel lengths along the perimeter */ setAxisSize: function () { axisProto.setAxisSize.call(this); if (this.center) { // it's not defined the first time this.len = this.width = this.height = this.isCircular ? this.center[2] * (this.endAngleRad - this.startAngleRad) / 2 : this.center[2] / 2; } }, /** * Returns the x, y coordinate of a point given by a value and a pixel distance * from center */ getPosition: function (value, length) { if (!this.isCircular) { length = this.translate(value); value = this.min; } return this.postTranslate( this.translate(value), pick(length, this.center[2] / 2) - this.offset ); }, /** * Translate from intermediate plotX (angle), plotY (axis.len - radius) to final chart coordinates. */ postTranslate: function (angle, radius) { var chart = this.chart, center = this.center; angle = this.startAngleRad + angle; return { x: chart.plotLeft + center[0] + Math.cos(angle) * radius, y: chart.plotTop + center[1] + Math.sin(angle) * radius }; }, /** * Find the path for plot bands along the radial axis */ getPlotBandPath: function (from, to, options) { var center = this.center, startAngleRad = this.startAngleRad, fullRadius = center[2] / 2, radii = [ pick(options.outerRadius, '100%'), options.innerRadius, pick(options.thickness, 10) ], percentRegex = /%$/, start, end, open, isCircular = this.isCircular, // X axis in a polar chart ret; // Polygonal plot bands if (this.options.gridLineInterpolation === 'polygon') { ret = this.getPlotLinePath(from).concat(this.getPlotLinePath(to, true)); // Circular grid bands } else { // Plot bands on Y axis (radial axis) - inner and outer radius depend on to and from if (!isCircular) { radii[0] = this.translate(from); radii[1] = this.translate(to); } // Convert percentages to pixel values radii = map(radii, function (radius) { if (percentRegex.test(radius)) { radius = (pInt(radius, 10) * fullRadius) / 100; } return radius; }); // Handle full circle if (options.shape === 'circle' || !isCircular) { start = -Math.PI / 2; end = Math.PI * 1.5; open = true; } else { start = startAngleRad + this.translate(from); end = startAngleRad + this.translate(to); } ret = this.chart.renderer.symbols.arc( this.left + center[0], this.top + center[1], radii[0], radii[0], { start: start, end: end, innerR: pick(radii[1], radii[0] - radii[2]), open: open } ); } return ret; }, /** * Find the path for plot lines perpendicular to the radial axis. */ getPlotLinePath: function (value, reverse) { var axis = this, center = axis.center, chart = axis.chart, end = axis.getPosition(value), xAxis, xy, tickPositions, ret; // Spokes if (axis.isCircular) { ret = ['M', center[0] + chart.plotLeft, center[1] + chart.plotTop, 'L', end.x, end.y]; // Concentric circles } else if (axis.options.gridLineInterpolation === 'circle') { value = axis.translate(value); if (value) { // a value of 0 is in the center ret = axis.getLinePath(0, value); } // Concentric polygons } else { xAxis = chart.xAxis[0]; ret = []; value = axis.translate(value); tickPositions = xAxis.tickPositions; if (xAxis.autoConnect) { tickPositions = tickPositions.concat([tickPositions[0]]); } // Reverse the positions for concatenation of polygonal plot bands if (reverse) { tickPositions = [].concat(tickPositions).reverse(); } each(tickPositions, function (pos, i) { xy = xAxis.getPosition(pos, value); ret.push(i ? 'L' : 'M', xy.x, xy.y); }); } return ret; }, /** * Find the position for the axis title, by default inside the gauge */ getTitlePosition: function () { var center = this.center, chart = this.chart, titleOptions = this.options.title; return { x: chart.plotLeft + center[0] + (titleOptions.x || 0), y: chart.plotTop + center[1] - ({ high: 0.5, middle: 0.25, low: 0 }[titleOptions.align] * center[2]) + (titleOptions.y || 0) }; } }; /*jslint unparam: false*/ /** * Override axisProto.init to mix in special axis instance functions and function overrides */ wrap(axisProto, 'init', function (proceed, chart, userOptions) { var axis = this, angular = chart.angular, polar = chart.polar, isX = userOptions.isX, isHidden = angular && isX, isCircular, startAngleRad, endAngleRad, options, chartOptions = chart.options, paneIndex = userOptions.pane || 0, pane, paneOptions; // Before prototype.init if (angular) { extend(this, isHidden ? hiddenAxisMixin : radialAxisMixin); isCircular = !isX; if (isCircular) { this.defaultRadialOptions = this.defaultRadialGaugeOptions; } } else if (polar) { //extend(this, userOptions.isX ? radialAxisMixin : radialAxisMixin); extend(this, radialAxisMixin); isCircular = isX; this.defaultRadialOptions = isX ? this.defaultRadialXOptions : merge(this.defaultYAxisOptions, this.defaultRadialYOptions); } // Run prototype.init proceed.call(this, chart, userOptions); if (!isHidden && (angular || polar)) { options = this.options; // Create the pane and set the pane options. if (!chart.panes) { chart.panes = []; } this.pane = chart.panes[paneIndex] = pane = new Pane( splat(chartOptions.pane)[paneIndex], chart, axis ); paneOptions = pane.options; // Disable certain features on angular and polar axes chart.inverted = false; chartOptions.chart.zoomType = null; // Start and end angle options are // given in degrees relative to top, while internal computations are // in radians relative to right (like SVG). this.startAngleRad = startAngleRad = (paneOptions.startAngle - 90) * Math.PI / 180; this.endAngleRad = endAngleRad = (pick(paneOptions.endAngle, paneOptions.startAngle + 360) - 90) * Math.PI / 180; this.offset = options.offset || 0; this.isCircular = isCircular; // Automatically connect grid lines? if (isCircular && userOptions.max === UNDEFINED && endAngleRad - startAngleRad === 2 * Math.PI) { this.autoConnect = true; } } }); /** * Add special cases within the Tick class' methods for radial axes. */ wrap(tickProto, 'getPosition', function (proceed, horiz, pos, tickmarkOffset, old) { var axis = this.axis; return axis.getPosition ? axis.getPosition(pos) : proceed.call(this, horiz, pos, tickmarkOffset, old); }); /** * Wrap the getLabelPosition function to find the center position of the label * based on the distance option */ wrap(tickProto, 'getLabelPosition', function (proceed, x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, optionsY = labelOptions.y, ret, align = labelOptions.align, angle = (axis.translate(this.pos) + axis.startAngleRad + Math.PI / 2) / Math.PI * 180; if (axis.isRadial) { ret = axis.getPosition(this.pos, (axis.center[2] / 2) + pick(labelOptions.distance, -25)); // Automatically rotated if (labelOptions.rotation === 'auto') { label.attr({ rotation: angle }); // Vertically centered } else if (optionsY === null) { optionsY = pInt(label.styles.lineHeight) * 0.9 - label.getBBox().height / 2; } // Automatic alignment if (align === null) { if (axis.isCircular) { if (angle > 20 && angle < 160) { align = 'left'; // right hemisphere } else if (angle > 200 && angle < 340) { align = 'right'; // left hemisphere } else { align = 'center'; // top or bottom } } else { align = 'center'; } label.attr({ align: align }); } ret.x += labelOptions.x; ret.y += optionsY; } else { ret = proceed.call(this, x, y, label, horiz, labelOptions, tickmarkOffset, index, step); } return ret; }); /** * Wrap the getMarkPath function to return the path of the radial marker */ wrap(tickProto, 'getMarkPath', function (proceed, x, y, tickLength, tickWidth, horiz, renderer) { var axis = this.axis, endPoint, ret; if (axis.isRadial) { endPoint = axis.getPosition(this.pos, axis.center[2] / 2 + tickLength); ret = [ 'M', x, y, 'L', endPoint.x, endPoint.y ]; } else { ret = proceed.call(this, x, y, tickLength, tickWidth, horiz, renderer); } return ret; });/* * The AreaRangeSeries class * */ /** * Extend the default options with map options */ defaultPlotOptions.arearange = merge(defaultPlotOptions.area, { lineWidth: 1, marker: null, threshold: null, tooltip: { pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.low}</b> - <b>{point.high}</b><br/>' }, trackByArea: true, dataLabels: { verticalAlign: null, xLow: 0, xHigh: 0, yLow: 0, yHigh: 0 }, shadow: false }); /** * Extend the point object */ var RangePoint = Highcharts.extendClass(Highcharts.Point, { /** * Apply the options containing the x and low/high data and possible some extra properties. * This is called on point init or from point.update. Extends base Point by adding * multiple y-like values. * * @param {Object} options */ applyOptions: function (options, x) { var point = this, series = point.series, pointArrayMap = series.pointArrayMap, i = 0, j = 0, valueCount = pointArrayMap.length; // object input if (typeof options === 'object' && typeof options.length !== 'number') { // copy options directly to point extend(point, options); point.options = options; } else if (options.length) { // array // with leading x value if (options.length > valueCount) { if (typeof options[0] === 'string') { point.name = options[0]; } else if (typeof options[0] === 'number') { point.x = options[0]; } i++; } while (j < valueCount) { point[pointArrayMap[j++]] = options[i++]; } } // Handle null and make low alias y /*if (point.high === null) { point.low = null; }*/ point.y = point[series.pointValKey]; // If no x is set by now, get auto incremented value. All points must have an // x value, however the y value can be null to create a gap in the series if (point.x === UNDEFINED && series) { point.x = x === UNDEFINED ? series.autoIncrement() : x; } return point; }, /** * Return a plain array for speedy calculation */ toYData: function () { return [this.low, this.high]; } }); /** * Add the series type */ seriesTypes.arearange = Highcharts.extendClass(seriesTypes.area, { type: 'arearange', pointArrayMap: ['low', 'high'], pointClass: RangePoint, pointValKey: 'low', /** * Translate data points from raw values x and y to plotX and plotY */ translate: function () { var series = this, yAxis = series.yAxis; seriesTypes.area.prototype.translate.apply(series); // Set plotLow and plotHigh each(series.points, function (point) { if (point.y !== null) { point.plotLow = point.plotY; point.plotHigh = yAxis.translate(point.high, 0, 1, 0, 1); } }); }, /** * Extend the line series' getSegmentPath method by applying the segment * path to both lower and higher values of the range */ getSegmentPath: function (segment) { var highSegment = [], i = segment.length, baseGetSegmentPath = Series.prototype.getSegmentPath, point, linePath, lowerPath, options = this.options, step = options.step, higherPath; // Make a segment with plotX and plotY for the top values while (i--) { point = segment[i]; highSegment.push({ plotX: point.plotX, plotY: point.plotHigh }); } // Get the paths lowerPath = baseGetSegmentPath.call(this, segment); if (step) { if (step === true) { step = 'left'; } options.step = { left: 'right', center: 'center', right: 'left' }[step]; // swap for reading in getSegmentPath } higherPath = baseGetSegmentPath.call(this, highSegment); options.step = step; // Create a line on both top and bottom of the range linePath = [].concat(lowerPath, higherPath); // For the area path, we need to change the 'move' statement into 'lineTo' or 'curveTo' higherPath[0] = 'L'; // this probably doesn't work for spline this.areaPath = this.areaPath.concat(lowerPath, higherPath); return linePath; }, /** * Extend the basic drawDataLabels method by running it for both lower and higher * values. */ drawDataLabels: function () { var data = this.data, length = data.length, i, originalDataLabels = [], seriesProto = Series.prototype, dataLabelOptions = this.options.dataLabels, point, inverted = this.chart.inverted; if (dataLabelOptions.enabled || this._hasPointLabels) { // Step 1: set preliminary values for plotY and dataLabel and draw the upper labels i = length; while (i--) { point = data[i]; // Set preliminary values point.y = point.high; point.plotY = point.plotHigh; // Store original data labels and set preliminary label objects to be picked up // in the uber method originalDataLabels[i] = point.dataLabel; point.dataLabel = point.dataLabelUpper; // Set the default offset point.below = false; if (inverted) { dataLabelOptions.align = 'left'; dataLabelOptions.x = dataLabelOptions.xHigh; } else { dataLabelOptions.y = dataLabelOptions.yHigh; } } seriesProto.drawDataLabels.apply(this, arguments); // #1209 // Step 2: reorganize and handle data labels for the lower values i = length; while (i--) { point = data[i]; // Move the generated labels from step 1, and reassign the original data labels point.dataLabelUpper = point.dataLabel; point.dataLabel = originalDataLabels[i]; // Reset values point.y = point.low; point.plotY = point.plotLow; // Set the default offset point.below = true; if (inverted) { dataLabelOptions.align = 'right'; dataLabelOptions.x = dataLabelOptions.xLow; } else { dataLabelOptions.y = dataLabelOptions.yLow; } } seriesProto.drawDataLabels.apply(this, arguments); } }, alignDataLabel: seriesTypes.column.prototype.alignDataLabel, getSymbol: seriesTypes.column.prototype.getSymbol, drawPoints: noop });/** * The AreaSplineRangeSeries class */ defaultPlotOptions.areasplinerange = merge(defaultPlotOptions.arearange); /** * AreaSplineRangeSeries object */ seriesTypes.areasplinerange = extendClass(seriesTypes.arearange, { type: 'areasplinerange', getPointSpline: seriesTypes.spline.prototype.getPointSpline });/** * The ColumnRangeSeries class */ defaultPlotOptions.columnrange = merge(defaultPlotOptions.column, defaultPlotOptions.arearange, { lineWidth: 1, pointRange: null }); /** * ColumnRangeSeries object */ seriesTypes.columnrange = extendClass(seriesTypes.arearange, { type: 'columnrange', /** * Translate data points from raw values x and y to plotX and plotY */ translate: function () { var series = this, yAxis = series.yAxis, plotHigh; colProto.translate.apply(series); // Set plotLow and plotHigh each(series.points, function (point) { var shapeArgs = point.shapeArgs; point.plotHigh = plotHigh = yAxis.translate(point.high, 0, 1, 0, 1); point.plotLow = point.plotY; // adjust shape shapeArgs.y = plotHigh; shapeArgs.height = point.plotY - plotHigh; point.trackerArgs = shapeArgs; }); }, drawGraph: noop, pointAttrToOptions: colProto.pointAttrToOptions, drawPoints: colProto.drawPoints, drawTracker: colProto.drawTracker, animate: colProto.animate });/* * The GaugeSeries class */ /** * Extend the default options */ defaultPlotOptions.gauge = merge(defaultPlotOptions.line, { dataLabels: { enabled: true, y: 15, borderWidth: 1, borderColor: 'silver', borderRadius: 3, style: { fontWeight: 'bold' }, verticalAlign: 'top', zIndex: 2 }, dial: { // radius: '80%', // backgroundColor: 'black', // borderColor: 'silver', // borderWidth: 0, // baseWidth: 3, // topWidth: 1, // baseLength: '70%' // of radius // rearLength: '10%' }, pivot: { //radius: 5, //borderWidth: 0 //borderColor: 'silver', //backgroundColor: 'black' }, tooltip: { headerFormat: '' }, showInLegend: false }); /** * Extend the point object */ var GaugePoint = Highcharts.extendClass(Highcharts.Point, { /** * Don't do any hover colors or anything */ setState: function (state) { this.state = state; } }); /** * Add the series type */ var GaugeSeries = { type: 'gauge', pointClass: GaugePoint, // chart.angular will be set to true when a gauge series is present, and this will // be used on the axes angular: true, /* * * Extend the bindAxes method by adding radial features to the axes * / _bindAxes: function () { Series.prototype.bindAxes.call(this); extend(this.xAxis, gaugeXAxisMixin); extend(this.yAxis, radialAxisMixin); this.yAxis.onBind(); },*/ /** * Calculate paths etc */ translate: function () { var series = this, yAxis = series.yAxis, center = yAxis.center; series.generatePoints(); each(series.points, function (point) { var dialOptions = merge(series.options.dial, point.dial), radius = (pInt(pick(dialOptions.radius, 80)) * center[2]) / 200, baseLength = (pInt(pick(dialOptions.baseLength, 70)) * radius) / 100, rearLength = (pInt(pick(dialOptions.rearLength, 10)) * radius) / 100, baseWidth = dialOptions.baseWidth || 3, topWidth = dialOptions.topWidth || 1; point.shapeType = 'path'; point.shapeArgs = { d: dialOptions.path || [ 'M', -rearLength, -baseWidth / 2, 'L', baseLength, -baseWidth / 2, radius, -topWidth / 2, radius, topWidth / 2, baseLength, baseWidth / 2, -rearLength, baseWidth / 2, 'z' ], translateX: center[0], translateY: center[1], rotation: (yAxis.startAngleRad + yAxis.translate(point.y, null, null, null, true)) * 180 / Math.PI }; // Positions for data label point.plotX = center[0]; point.plotY = center[1]; }); }, /** * Draw the points where each point is one needle */ drawPoints: function () { var series = this, center = series.yAxis.center, pivot = series.pivot, options = series.options, pivotOptions = options.pivot, renderer = series.chart.renderer; each(series.points, function (point) { var graphic = point.graphic, shapeArgs = point.shapeArgs, d = shapeArgs.d, dialOptions = merge(options.dial, point.dial); // #1233 if (graphic) { graphic.animate(shapeArgs); shapeArgs.d = d; // animate alters it } else { point.graphic = renderer[point.shapeType](shapeArgs) .attr({ stroke: dialOptions.borderColor || 'none', 'stroke-width': dialOptions.borderWidth || 0, fill: dialOptions.backgroundColor || 'black', rotation: shapeArgs.rotation // required by VML when animation is false }) .add(series.group); } }); // Add or move the pivot if (pivot) { pivot.animate({ // #1235 translateX: center[0], translateY: center[1] }); } else { series.pivot = renderer.circle(0, 0, pick(pivotOptions.radius, 5)) .attr({ 'stroke-width': pivotOptions.borderWidth || 0, stroke: pivotOptions.borderColor || 'silver', fill: pivotOptions.backgroundColor || 'black' }) .translate(center[0], center[1]) .add(series.group); } }, /** * Animate the arrow up from startAngle */ animate: function () { var series = this; each(series.points, function (point) { var graphic = point.graphic; if (graphic) { // start value graphic.attr({ rotation: series.yAxis.startAngleRad * 180 / Math.PI }); // animate graphic.animate({ rotation: point.shapeArgs.rotation }, series.options.animation); } }); // delete this function to allow it only once series.animate = null; }, render: function () { this.group = this.plotGroup( 'group', 'series', this.visible ? 'visible' : 'hidden', this.options.zIndex, this.chart.seriesGroup ); seriesTypes.pie.prototype.render.call(this); this.group.clip(this.chart.clipRect); }, setData: seriesTypes.pie.prototype.setData, drawTracker: seriesTypes.column.prototype.drawTracker }; seriesTypes.gauge = Highcharts.extendClass(seriesTypes.line, GaugeSeries);/** * Extensions for polar charts. Additionally, much of the geometry required for polar charts is * gathered in RadialAxes.js. * */ var seriesProto = Series.prototype, mouseTrackerProto = Highcharts.MouseTracker.prototype; /** * Translate a point's plotX and plotY from the internal angle and radius measures to * true plotX, plotY coordinates */ seriesProto.toXY = function (point) { var xy, chart = this.chart, plotX = point.plotX, plotY = point.plotY; // Save rectangular plotX, plotY for later computation point.rectPlotX = plotX; point.rectPlotY = plotY; // Record the angle in degrees for use in tooltip point.deg = plotX / Math.PI * 180; // Find the polar plotX and plotY xy = this.xAxis.postTranslate(point.plotX, this.yAxis.len - plotY); point.plotX = point.polarPlotX = xy.x - chart.plotLeft; point.plotY = point.polarPlotY = xy.y - chart.plotTop; }; /** * Add some special init logic to areas and areasplines */ function initArea(proceed, chart, options) { proceed.call(this, chart, options); if (this.chart.polar) { /** * Overridden method to close a segment path. While in a cartesian plane the area * goes down to the threshold, in the polar chart it goes to the center. */ this.closeSegment = function (path) { var center = this.xAxis.center; path.push( 'L', center[0], center[1] ); }; // Instead of complicated logic to draw an area around the inner area in a stack, // just draw it behind this.closedStacks = true; } } wrap(seriesTypes.area.prototype, 'init', initArea); wrap(seriesTypes.areaspline.prototype, 'init', initArea); /** * Overridden method for calculating a spline from one point to the next */ wrap(seriesTypes.spline.prototype, 'getPointSpline', function (proceed, segment, point, i) { var ret, smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc; denom = smoothing + 1, plotX, plotY, lastPoint, nextPoint, lastX, lastY, nextX, nextY, leftContX, leftContY, rightContX, rightContY, distanceLeftControlPoint, distanceRightControlPoint, leftContAngle, rightContAngle, jointAngle; if (this.chart.polar) { plotX = point.plotX; plotY = point.plotY; lastPoint = segment[i - 1]; nextPoint = segment[i + 1]; // Connect ends if (this.connectEnds) { if (!lastPoint) { lastPoint = segment[segment.length - 2]; // not the last but the second last, because the segment is already connected } if (!nextPoint) { nextPoint = segment[1]; } } // find control points if (lastPoint && nextPoint) { lastX = lastPoint.plotX; lastY = lastPoint.plotY; nextX = nextPoint.plotX; nextY = nextPoint.plotY; leftContX = (smoothing * plotX + lastX) / denom; leftContY = (smoothing * plotY + lastY) / denom; rightContX = (smoothing * plotX + nextX) / denom; rightContY = (smoothing * plotY + nextY) / denom; distanceLeftControlPoint = Math.sqrt(Math.pow(leftContX - plotX, 2) + Math.pow(leftContY - plotY, 2)); distanceRightControlPoint = Math.sqrt(Math.pow(rightContX - plotX, 2) + Math.pow(rightContY - plotY, 2)); leftContAngle = Math.atan2(leftContY - plotY, leftContX - plotX); rightContAngle = Math.atan2(rightContY - plotY, rightContX - plotX); jointAngle = (Math.PI / 2) + ((leftContAngle + rightContAngle) / 2); // Ensure the right direction, jointAngle should be in the same quadrant as leftContAngle if (Math.abs(leftContAngle - jointAngle) > Math.PI / 2) { jointAngle -= Math.PI; } // Find the corrected control points for a spline straight through the point leftContX = plotX + Math.cos(jointAngle) * distanceLeftControlPoint; leftContY = plotY + Math.sin(jointAngle) * distanceLeftControlPoint; rightContX = plotX + Math.cos(Math.PI + jointAngle) * distanceRightControlPoint; rightContY = plotY + Math.sin(Math.PI + jointAngle) * distanceRightControlPoint; // Record for drawing in next point point.rightContX = rightContX; point.rightContY = rightContY; } // moveTo or lineTo if (!i) { ret = ['M', plotX, plotY]; } else { // curve from last point to this ret = [ 'C', lastPoint.rightContX || lastPoint.plotX, lastPoint.rightContY || lastPoint.plotY, leftContX || plotX, leftContY || plotY, plotX, plotY ]; lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later } } else { ret = proceed.call(this, segment, point, i); } return ret; }); /** * Extend translate. The plotX and plotY values are computed as if the polar chart were a * cartesian plane, where plotX denotes the angle in radians and (yAxis.len - plotY) is the pixel distance from * center. */ wrap(seriesProto, 'translate', function (proceed) { // Run uber method proceed.call(this); // Postprocess plot coordinates if (this.chart.polar && !this.preventPostTranslate) { var points = this.points, i = points.length; while (i--) { // Translate plotX, plotY from angle and radius to true plot coordinates this.toXY(points[i]); } } }); /** * Extend getSegmentPath to allow connecting ends across 0 to provide a closed circle in * line-like series. */ wrap(seriesProto, 'getSegmentPath', function (proceed, segment) { var points = this.points; // Connect the path if (this.chart.polar && this.options.connectEnds !== false && segment[segment.length - 1] === points[points.length - 1] && points[0].y !== null) { this.connectEnds = true; // re-used in splines segment = [].concat(segment, [points[0]]); } // Run uber method return proceed.call(this, segment); }); function polarAnimate(proceed, init) { var chart = this.chart, animation = this.options.animation, group = this.group, markerGroup = this.markerGroup, center = this.xAxis.center, plotLeft = chart.plotLeft, plotTop = chart.plotTop, attribs; // Specific animation for polar charts if (chart.polar) { // Enable animation on polar charts only in SVG. In VML, the scaling is different, plus animation // would be so slow it would't matter. if (chart.renderer.isSVG) { if (animation === true) { animation = {}; } // Initialize the animation if (init) { // Create an SVG specific attribute setter for scaleX and scaleY group.attrSetters.scaleX = group.attrSetters.scaleY = function (value, key) { this[key] = value; if (this.scaleX !== UNDEFINED && this.scaleY !== UNDEFINED) { this.element.setAttribute('transform', 'translate(' + this.translateX + ',' + this.translateY + ') scale(' + this.scaleX + ',' + this.scaleY + ')'); } return false; }; // Scale down the group and place it in the center attribs = { translateX: center[0] + plotLeft, translateY: center[1] + plotTop, scaleX: 0, scaleY: 0 }; group.attr(attribs); if (markerGroup) { markerGroup.attrSetters = group.attrSetters; markerGroup.attr(attribs); } // Run the animation } else { attribs = { translateX: plotLeft, translateY: plotTop, scaleX: 1, scaleY: 1 }; group.animate(attribs, animation); if (markerGroup) { markerGroup.animate(attribs, animation); } // Delete this function to allow it only once this.animate = null; } } // For non-polar charts, revert to the basic animation } else { proceed.call(this, init); } } // Define the animate method for both regular series and column series and their derivatives wrap(seriesProto, 'animate', polarAnimate); wrap(colProto, 'animate', polarAnimate); /** * Throw in a couple of properties to let setTooltipPoints know we're indexing the points * in degrees (0-360), not plot pixel width. */ wrap(seriesProto, 'setTooltipPoints', function (proceed, renew) { if (this.chart.polar) { extend(this.xAxis, { tooltipLen: 360, // degrees are the resolution unit of the tooltipPoints array tooltipPosName: 'deg' }); } // Run uber method return proceed.call(this, renew); }); /** * Extend the column prototype's translate method */ wrap(colProto, 'translate', function (proceed) { var xAxis = this.xAxis, len = this.yAxis.len, center = xAxis.center, startAngleRad = xAxis.startAngleRad, renderer = this.chart.renderer, start, points, point, i; this.preventPostTranslate = true; // Run uber method proceed.call(this); // Postprocess plot coordinates if (xAxis.isRadial) { points = this.points; i = points.length; while (i--) { point = points[i]; start = point.barX + startAngleRad; point.shapeType = 'path'; point.shapeArgs = { d: renderer.symbols.arc( center[0], center[1], len - point.plotY, null, { start: start, end: start + point.pointWidth, innerR: len - pick(point.yBottom, len) } ) }; this.toXY(point); // provide correct plotX, plotY for tooltip } } }); /** * Align column data labels outside the columns. #1199. */ wrap(colProto, 'alignDataLabel', function (proceed, point, dataLabel, options, alignTo, isNew) { if (this.chart.polar) { var angle = point.rectPlotX / Math.PI * 180, align, verticalAlign; // Align nicely outside the perimeter of the columns if (options.align === null) { if (angle > 20 && angle < 160) { align = 'left'; // right hemisphere } else if (angle > 200 && angle < 340) { align = 'right'; // left hemisphere } else { align = 'center'; // top or bottom } options.align = align; } if (options.verticalAlign === null) { if (angle < 45 || angle > 315) { verticalAlign = 'bottom'; // top part } else if (angle > 135 && angle < 225) { verticalAlign = 'top'; // bottom part } else { verticalAlign = 'middle'; // left or right } options.verticalAlign = verticalAlign; } seriesProto.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew); } else { proceed.call(this, point, dataLabel, options, alignTo, isNew); } }); /** * Extend the mouse tracker to return the tooltip position index in terms of * degrees rather than pixels */ wrap(mouseTrackerProto, 'getIndex', function (proceed, e) { var ret, chart = this.chart, center, x, y; if (chart.polar) { center = chart.xAxis[0].center; x = e.chartX - center[0] - chart.plotLeft; y = e.chartY - center[1] - chart.plotTop; ret = 180 - Math.round(Math.atan2(x, y) / Math.PI * 180); } else { // Run uber method ret = proceed.call(this, e); } return ret; }); /** * Extend getMouseCoordinates to prepare for polar axis values */ wrap(mouseTrackerProto, 'getMouseCoordinates', function (proceed, e) { var chart = this.chart, ret = { xAxis: [], yAxis: [] }; if (chart.polar) { each(chart.axes, function (axis) { var isXAxis = axis.isXAxis, center = axis.center, x = e.chartX - center[0] - chart.plotLeft, y = e.chartY - center[1] - chart.plotTop; ret[isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.translate( isXAxis ? Math.PI - Math.atan2(x, y) : // angle Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)), // distance from center true ) }); }); } else { ret = proceed.call(this, e); } return ret; }); }(Highcharts));
JavaScript
/** * @license Highcharts JS v2.3.3 (2012-11-02) * * (c) 2009-2011 Gert Vaartjes * * License: www.highcharts.com/license */ /*global window, require, phantom, console, $, document, Image, Highcharts, clearTimeout, options */ (function () { "use strict"; var config = { /* define locations of mandatory javascript files */ HIGHCHARTS: 'highstock.js', HIGHCHARTS_MORE: 'highcharts-more', JQUERY: 'jquery-1.8.2.min.js' }, /* Internal */ page = require('webpage').create(), fs = require('fs'), system = require('system'), args, HC = {}, pick, mapArguments, scaleAndClipPage, input, constr, callback, width, callbackStr, optionsStr, output, outputExtension, pdfOutput, svg, svgFile, svgElem, timer; HC.imagesLoaded = 'Highcharts.imagesLoaded:7a7dfcb5df73aaa51e67c9f38c5b07cb'; window.imagesLoaded = false; page.onConsoleMessage = function (msg) { console.log(msg); /* * Ugly hack, but only way to get messages out of the 'page.evaluate()' * sandbox. If any, please contribute with improvements on this! */ if (msg === HC.imagesLoaded) { window.imagesLoaded = true; } }; page.onAlert = function (msg) { console.log(msg); }; pick = function () { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i += 1) { arg = args[i]; if (arg !== undefined && arg !== null && arg !== 'null' && arg != '0') { return arg; } } }; mapArguments = function () { var map = {}, i; for (i = 0; i < system.args.length; i += 1) { if (system.args[i].charAt(0) === '-') { map[system.args[i].substr(1, i.length)] = system.args[i + 1]; } } return map; }; /* scale and clip the page */ scaleAndClipPage = function (svg, pdf) { /* param: svg: The scg configuration object param: pdf: boolean, if true set papersize */ var zoom = 1, pageWidth = pick(args.width, svg.width), clipwidth, clipheight; if (parseInt(pageWidth, 10) == pageWidth) { zoom = pageWidth / svg.width; } /* set this line when scale factor has a higher precedence scale has precedence : page.zoomFactor = args.scale ? zoom * args.scale : zoom;*/ /* args.width has a higher precedence over scaling, to not break backover compatibility */ page.zoomFactor = args.scale && args.width == undefined ? zoom * args.scale : zoom; clipwidth = svg.width * page.zoomFactor; clipheight = svg.height * page.zoomFactor; /* define the clip-rectangle */ page.clipRect = { top: 0, left: 0, width: clipwidth, height: clipheight }; /* for pdf we need a bit more paperspace in some cases for example (w:600,h:400), I don't know why.*/ if (pdf) { page.paperSize = { width: clipwidth, height: clipheight + 2}; } }; /* get the arguments from the commandline and map them */ args = mapArguments(); if (args.length < 1) { console.log('Usage: highcharts-convert.js -infile URL -outfile filename -scale 2.5 -width 300 -constr Chart -callback callback.js'); console.log('Commandline parameter width is used for scaling, not for creating the chart'); phantom.exit(1); } else { input = args.infile; output = pick(args.outfile, "chart.png"); constr = pick(args.constr, 'Chart'); callback = args.callback; width = args.width; outputExtension = output.split('.').pop(); pdfOutput = outputExtension === 'pdf'; /* Decide to generate the page from javascript or to load from svg file. */ if (input.split('.').pop() === 'json') { // We have a json file, -> go headless! // load necessary libraries page.injectJs(config.JQUERY); page.injectJs(config.HIGHCHARTS); page.injectJs(config.HIGHCHARTS_MORE); // load options from file if (input !== undefined) { optionsStr = fs.read(input); } else { console.log('No options file specified!'); phantom.exit(); } // load callback from file if (callback !== undefined) { callbackStr = fs.read(callback); } // load chart in page and return svg height and width svg = page.evaluate(function (width, constr, optionsStr, callbackStr, pdfOutput) { var imagesLoadedMsg = 'Highcharts.imagesLoaded:7a7dfcb5df73aaa51e67c9f38c5b07cb', $container, chart, nodes, nodeIter, elem, opacity; // dynamic script insertion function loadScript(varStr, codeStr) { var $script = $('<script>').attr('type', 'text/javascript'); $script.html('var ' + varStr + ' = ' + codeStr); document.getElementsByTagName("head")[0].appendChild($script[0]); } // are all images loaded in time? function logCounter(counter) { counter -= 1; if (counter < 1) { console.log(imagesLoadedMsg); } } function loadImages() { // are images loaded? var $images = $('svg image'), counter, i, img; if ($images.length > 0) { counter = $images.length; for (i = 0; i < $images.length; i += 1) { img = new Image(); img.onload = logCounter(counter); /* force loading of images by setting the src attr.*/ img.src = $images[i].getAttribute('href'); } } else { // no images set property to all images // loaded console.log(imagesLoadedMsg); } } if (optionsStr !== 'undefined') { loadScript('options', optionsStr); } if (callbackStr !== 'undefined') { loadScript('callback', callbackStr); } $(document.body).css('margin', '0px'); $container = $('<div>').appendTo(document.body); $container.attr('id', 'container'); // disable animations Highcharts.SVGRenderer.prototype.Element.prototype.animate = Highcharts.SVGRenderer.prototype.Element.prototype.attr; if (!options.chart) { options.chart = {}; } options.chart.renderTo = $container[0]; // check if witdh is set. Order of precedence: // args.width, options.chart.width and 600px // OLD. options.chart.width = width || options.chart.width || 600; // Notice we don't use commandline parameter width here. Commandline parameter width is used for scaling. options.chart.width = (options.exporting && options.exporting.sourceWidth) || options.chart.width || 600; options.chart.height = (options.exporting && options.exporting.sourceHeight) || options.chart.height || 400; chart = new Highcharts[constr](options, callback); // ensure images are all loaded loadImages(); if (pdfOutput) { /* * remove stroke-opacity paths, Qt shows * them as fully opaque in the PDF */ nodes = document.querySelectorAll('*[stroke-opacity]'); for (nodeIter = 0; nodeIter < nodes.length; nodeIter += 1) { elem = nodes[nodeIter]; opacity = elem.getAttribute('stroke-opacity'); elem.removeAttribute('stroke-opacity'); elem.setAttribute('opacity', opacity); } } return { html: $container[0].firstChild.innerHTML, width: chart.chartWidth, height: chart.chartHeight }; }, width, constr, optionsStr, callbackStr, pdfOutput); try { // save the SVG to output or convert to other formats if (outputExtension === 'svg') { svgFile = fs.open(output, "w"); // set in xlink namespace for images. svgFile.write(svg.html.replace(/<svg /, '<svg xmlns:xlink="http://www.w3.org/1999/xlink" ').replace(/ href=/g, ' xlink:href=')); svgFile.close(); phantom.exit(); } else { // check every 50 ms if all images are loaded window.setInterval(function () { if (!window.imagesLoaded) { console.log('loading images...'); } else { console.log('done loading images'); scaleAndClipPage(svg, pdfOutput); page.render(output); clearTimeout(timer); phantom.exit(); } }, 50); // we have a 1.5 second timeframe.. timer = window.setTimeout(function () { phantom.exit(); }, 1500); } } catch (e) { console.log(e); } } else { /* render page directly from svg file */ page.open(input, function (status) { var nodeIter, opacity, elem, svg; if (status !== 'success') { console.log('Unable to load the address!'); phantom.exit(); } else { svg = page.evaluate(function (pdfOutput) { if (pdfOutput) { /* * remove stroke-opacity paths, Qt shows them as * fully opaque in the PDF, replace attributes with * opacity */ var nodes = document.querySelectorAll('*[stroke-opacity]'); for (nodeIter = 0; nodeIter < nodes.length; nodeIter += 1) { elem = nodes[nodeIter]; opacity = elem.getAttribute('stroke-opacity'); elem.removeAttribute('stroke-opacity'); elem.setAttribute('opacity', opacity); } } svgElem = document.getElementsByTagName('svg')[0]; return { width: svgElem.getAttribute("width"), height: svgElem.getAttribute("height") }; }, pdfOutput); scaleAndClipPage(svg, pdfOutput); page.render(output); phantom.exit(); } }); } } }());
JavaScript
/********************************************************************* clase Marcador * un marcador es la representacion grafica de un componente en el * mapa de google ********************************************************************/ function hidmarcador(puntoCentral, nombre, rutaBase, tipoPuntoMonitoreo) { var puntoCentral = puntoCentral; var nombre = nombre; var rutaBase = rutaBase; var tipoPuntoMonitoreo = tipoPuntoMonitoreo; this.CrearMarcador = function (puntoCentral1, nombre1) { var marker = new google.maps.Marker({ position: puntoCentral1, title:nombre1, draggable:true }); return marker; }; this.AgregarMarcador = function () { //si ya fue seleccionado la grafica de algun tipo de componente if(document.getElementById("marcador").value != "") { var ruta = ExtraerValor("marcador"); var componenteunico = ExtraerValor("marcadorunico"); var marker = this.CrearMarcador(puntoCentral, nombre); var componente = this.CrearComponente(ruta, componenteunico, marker); //si el valor de la ruta existe se asigna la imagen correspondiente al marcador if(this.ExisteRuta(ruta)) { ruta = rutaBase + ruta + ".jpg"; marker.setIcon(ruta); } //vericamos si es un componente nodo o arista if(this.EsComponenteSingular(componenteunico)) { marker = this.AgregarCamposMarcador(componente, marker); marker = this.AgregarListaEventos(marker); markersArray.push(marker); } } }; this.AgregarEventosMarcador = function (componente) { //se crea un marcador con los datos contenidos en el componente var myLatlng = new google.maps.LatLng(componente.latitud,componente.longitud); var marker = this.CrearMarcador(myLatlng, 'Componente'); marker.ide = componente.ide; marker.setIcon(rutaBase + componente.tipo + ".jpg"); //verificamos que sea un componente nodo if(this.EsComponenteSingular(componente.tipouni)) { marker.posicionactual = puntoCentral; marker.latitud = componente.latitud; marker.longitud = componente.longitud; //Agregamos eventos al marcador para click, doble click, etc. this.AgregarEventoMarcador(marker,'click',function(){ AgregarLinea(marker); }); this.AgregarEventoMarcador(marker,'dblclick',function(){ EliminarMarcador(marker); }); this.AgregarEventoMarcador(marker,'rightclick',function(){ VentanaMarcador(marker); }); this.AgregarEventoMarcador(marker,'dragend',function(){ ActualizarMarcador(marker); }); this.AgregarEventoMarcador(marker,'drag',function(){ ActualizarPolylinesMarcador(marker); }); //agregamos el marcador creado a la lista de marcadores markersArray.push(marker); } }; this.AgregarEventoMarcador = function (marcador, evento, funcion) { google.maps.event.addDomListener(marcador, evento, funcion); }; this.AgregarListaEventos = function (marcador) { this.AgregarEventoMarcador(marcador,'click',function(){ AgregarLinea(marcador); }); this.AgregarEventoMarcador(marcador,'dblclick',function(){ EliminarMarcador(marcador); }); this.AgregarEventoMarcador(marcador,'rightclick',function(){ VentanaMarcador(marcador); }); this.AgregarEventoMarcador(marcador,'dragend',function(){ ActualizarMarcador(marcador); }); this.AgregarEventoMarcador(marcador,'drag',function(){ ActualizarPolylinesMarcador(marcador); }); return marcador; } this.AgregarLinea = AgregarLinea; this.VentanaMarcador = VentanaMarcador; this.EliminarMarcador = EliminarMarcador; this.ActualizarMarcador = ActualizarMarcador; this.ActualizarPolylinesMarcador = ActualizarPolylinesMarcador; this.CrearComponente = function(rutadeimagenes, componenteunico, marcador) { var componente = new hidcomponente(0, rutadeimagenes, componenteunico, marcador.getPosition().lat(), marcador.getPosition().lng(), marcador.title, tipoPuntoMonitoreo); componente.ideparcial = componente.hidcomp_nuevoIde(componentes,lineArray); return componente; }; this.ExisteRuta = function (ruta) { if(ruta) return true; else return false; } this.EsComponenteSingular = function (flagcomponenteunico) { if(flagcomponenteunico == "true") return true; else return false; } this.AgregarCamposMarcador = function (componente, marcador) { //agregamos campos correpondientes al componente que no posee el marcador componentes.push(componente); var posicionComp = componente.hidcomp_findByLatLng(componentes,marcador); marcador.posicionComp = posicionComp; marcador.posicionactual = puntoCentral; marcador.latitud = componente.latitud; marcador.longitud = componente.longitud; return marcador; } } function AgregarLinea(marker) { //Se debe verificar que se trata de un componente de varios elementos if( ExtraerValor("marcadorunico") == "false") { //se debe obtener el punto de origen y destino //se verifica que no se haya seleccionado el punto de origen, para elegirlo if(ExistenInicioFinLinea("inilinea","inilinea2")) { AsignarValor("inilinea",marker.posicionactual.lat()); AsignarValor("inilinea2",marker.posicionactual.lng()); marker = AlmacenarPosicionComponente(marker); AsignarValor("marcadorinicial",marker.posicionComp); } else { AgregarNombreLinea(marker); } } }; function ExistenInicioFinLinea(identificador1, identificador2) { //se debe verificar si existen el nodo de inicio y el de fin if(ExtraerValor(identificador1) == "" && ExtraerValor(identificador2) == "") return true; else return false; } function AlmacenarPosicionComponente(marcador) { //se debe obtener la posicion dentro del arreglo de componentes que corresponde al marcador var cmp = new hidcomponente(1,1,1,1); var posicionComp = cmp.hidcomp_findByLatLng(componentes,marcador); marcador.posicionComp = posicionComp; return marcador; } function CrearLinea(marcador, nombreComponente, tipoPuntoMonitoreo) { //cuando se trata del punto de destino se deben obtener los valores del punto de origen y junto con los //datos del punto de destino generar un arreglo con ambos datos para finalmente agregarlo al arreglo de //lineas var latitud1 = parseFloat(ExtraerValor("inilinea")); var longitud1 = parseFloat(ExtraerValor("inilinea2")); var tipo = ExtraerValor("marcador"); var linea = []; linea.push(latitud1); linea.push(longitud1); linea.push(marcador.posicionactual.lat()); linea.push(marcador.posicionactual.lng()); linea.push(tipo); linea.push(0); marcador = AlmacenarPosicionComponente(marcador); var ideinicial = ExtraerValor("marcadorinicial"); //ides de los nodos linea.push(componentes[ideinicial].ide); linea.push(componentes[marcador.posicionComp].ide); linea.push(nombreComponente); linea.push(tipoPuntoMonitoreo); return linea; } function VentanaMarcador(marker) { var contentString = '<div id="content"><a onclick="deleteOverlays()">OK</a></div>'; var infowindow = new google.maps.InfoWindow({ content: contentString }); infowindow.open(mapa,marker); }; function EliminarMarcador(marker) { //se debe encontrar el componente correspondiente al marcador y agregarlo a la lista de eliminados //se debe borrar el marcador(grafico) del mapa ActualizarListaEliminados(marker); marker.setMap(null); //se debe actualizar la lista de marcadores ActualizarListaMarcadores(marker); //eliminar lineas conectadas a un marcador EliminarLineasConectadasMarcador(marker); }; function ActualizarListaEliminados(marcador) { //se debe encontrar el componente correspondiente al marcador y agregarlo a la lista de eliminados var cmp = new hidcomponente(1,1,1,1); eliminadosArray.push(cmp.hidcomp_find(componentes,marcador)); } function ActualizarListaMarcadores(marcador) { //se debe actualizar la lista de marcadores var ListaMarcadoresTemporal = []; for (i in markersArray) { if(markersArray[i].getPosition().equals(marcador.getPosition()) == false) { //se crea una lista temporal de marcadores ListaMarcadoresTemporal.push(markersArray[i]); } } //se asigna la lista temporal de marcadores al arreglo original de marcadores markersArray.length = ListaMarcadoresTemporal.length; markersArray = ListaMarcadoresTemporal; } function EliminarLineasConectadasMarcador(marcador) { //eliminar lineas conectadas a un marcador var hidaritmp = new hidarista(1,1,1,1,''); var lista = hidaritmp.hidari_find(lineArray, marcador); for (var i = 0; i < lista.length; i++) { //lista contiene la posicion del arreglo de polilineas //y el valor 0 o 1 para indicar si es inicio o fin var posicion = lista[i]; EliminarLinea(posicion[0],poly[posicion[0]].idpoly); } } function ActualizarMarcador(marker) { //se debe encontrar el componente correspondiente al marcador var posicionComponente = ObtenerPosicionMarcadorModificado(marker); //se debe actualizar las propiedades del componente componentes[posicionComponente].latitud = marker.getPosition().lat(); componentes[posicionComponente].longitud = marker.getPosition().lng(); marker.posicionactual = marker.getPosition(); }; function ObtenerPosicionMarcadorModificado(marcador) { //se debe encontrar el componente correspondiente al marcador var idemarcador = marcador.ide; var posicionMarcador; if(isNaN(idemarcador) == true) { posicionMarcador = marcador.posicionComp; } else { var cmp = new hidcomponente(1,1,1,1); var identificadorMarcador = parseInt(idemarcador); posicionMarcador = cmp.hidcomp_findById(componentes,identificadorMarcador); } return posicionMarcador; } function ActualizarPolylinesMarcador(marker) { var lista = ObtenerLineasConectadasMarcador(marker); marker.posicionactual = marker.getPosition(); for (var i = 0; i < lista.length; i++) { //lista contiene la posicion del arreglo de polilineas //y el valor 0 o 1 para indicar si es inicio o fin ActualizarLineas(lista,i,marker); } }; function ObtenerLineasConectadasMarcador(marcador) { var hidaritmp = new hidarista(1,1,1,1,''); var listaLineas = hidaritmp.hidari_find(lineArray, marcador); return listaLineas; } function ActualizarLineas(lista, posicionLista, marcador) { //lista contiene la posicion del arreglo de polilineas //y el valor 0 o 1 para indicar si es inicio o fin var lineas = {"latitudorigen":0, "longitudorigen":1, "latitudfin":2, "longitudfin":3}; var posicion = lista[posicionLista]; var pathpolilinea = poly[posicion[0]].getPath(); if(EsInicio(posicion[1])) { //si es el nodo de inicio, se almacena temporalmente el nodo de fin, se extrae los 2 nodos // y se ingresa el nuevo nodo, y finalmente el nodo temporal var nodoFin = pathpolilinea.getAt(1); pathpolilinea.pop(); pathpolilinea.pop(); pathpolilinea.push(marcador.getPosition()); pathpolilinea.push(nodoFin); lineArray[posicion[0]][lineas.latitudorigen] = marcador.posicionactual.lat(); lineArray[posicion[0]][lineas.longitudorigen] = marcador.posicionactual.lng(); } else { //si es el nodo fin, simplemente se le extrae y se ingresa el nuevo pathpolilinea.pop(); pathpolilinea.push(marcador.getPosition()); lineArray[posicion[0]][lineas.latitudfin] = marcador.posicionactual.lat(); lineArray[posicion[0]][lineas.longitudfin] = marcador.posicionactual.lng(); } } function EsInicio(posicion) { if(posicion == 0) return true; else return false; } function AgregarNombreLinea(marker) { //construimos una ventana para el ingreso del nombre del componente arista var htmlBox = CrearVentanaModal("Nombre de Componente","300px","20px"); var input = CrearInputText("text","30","30"); var select = CrearComboSeleccion(); var br = CrearSaltoDeLinea(); var editBtn = CrearBoton("Agregar"); var container = CrearContenedorVentana(); container.appendChild(htmlBox); container.appendChild(input); container.appendChild(select); container.appendChild(br); container.appendChild(editBtn); //creamos una ventana de informacion con la ventana creada var infowindow = new google.maps.InfoWindow({ content: container, position: marker.posicionactual }); //asignamos el evento al boton de la ventana para 'click' google.maps.event.addDomListener(editBtn, "click", function() { input.readOnly = true; setTimeout(function () { infowindow.close(); }, 500); CrearContenidoLinea(marker, input.value, select.value); }); infowindow.open(mapa); } function CrearContenidoLinea(marker, nombreComponente, tipoPuntoMonitoreo) { var linea = CrearLinea(marker,nombreComponente, tipoPuntoMonitoreo); lineArray.push(linea); poly.push(null); AsignarValor("inilinea",""); AsignarValor("inilinea2",""); MostrarLineas(); }
JavaScript
var nodes = new Array();; var openNodes = new Array(); var icons = new Array(6); var targetopc = ""; // Loads all icons that are used in the tree function preloadIcons() { icons[0] = new Image(); icons[0].src = "../../../public/images/img/plus.gif"; icons[1] = new Image(); icons[1].src = "../../../public/images/img/plusbottom.gif"; icons[2] = new Image(); icons[2].src = "../../../public/images/img/minus.gif"; icons[3] = new Image(); icons[3].src = "../../../public/images/img/minusbottom.gif"; icons[4] = new Image(); icons[4].src = "../../../public/images/img/folder.gif"; icons[5] = new Image(); icons[5].src = "../../../public/images/img/folderopen.gif"; } // Create the tree function createTree(targetopcs,arrName, startNode, openNode) { nodes = arrName; targetopc = targetopcs; if (nodes.length > 0) { preloadIcons(); if (startNode == null) startNode = 0; if (openNode != 0 || openNode != null) setOpenNodes(openNode); if (startNode !=0) { var nodeValues = nodes[getArrayId(startNode)].split("|"); document.write("<a href=\"" + nodeValues[3] + "\" onmouseover=\"window.status='" + nodeValues[2] + "';return true;\" onmouseout=\"window.status=' ';return true;\" target=\""+targetopc+"\"><img src=\"../../../public/images/img/folderopen.gif\" align=\"absbottom\" alt=\"\" />" + nodeValues[2] + "</a><br />"); } else document.write("<img src=\"../../../public/images/img/base.gif\" align=\"absbottom\" alt=\"\" />Componentes<br />"); var recursedNodes = new Array(); addNode(startNode, recursedNodes); } } // Returns the position of a node in the array function getArrayId(node) { for (i=0; i<nodes.length; i++) { var nodeValues = nodes[i].split("|"); if (nodeValues[0]==node) return i; } } // Puts in array nodes that will be open function setOpenNodes(openNode) { for (i=0; i<nodes.length; i++) { var nodeValues = nodes[i].split("|"); if (nodeValues[0]==openNode) { openNodes.push(nodeValues[0]); setOpenNodes(nodeValues[1]); } } } // Checks if a node is open function isNodeOpen(node) { for (i=0; i<openNodes.length; i++) if (openNodes[i]==node) return true; return false; } // Checks if a node has any children function hasChildNode(parentNode) { for (i=0; i< nodes.length; i++) { var nodeValues = nodes[i].split("|"); if (nodeValues[1] == parentNode) return true; } return false; } // Checks if a node is the last sibling function lastSibling (node, parentNode) { var lastChild = 0; for (i=0; i< nodes.length; i++) { var nodeValues = nodes[i].split("|"); if (nodeValues[1] == parentNode) lastChild = nodeValues[0]; } if (lastChild==node) return true; return false; } // Adds a new node to the tree function addNode(parentNode, recursedNodes) { for (var i = 0; i < nodes.length; i++) { var nodeValues = nodes[i].split("|"); if (nodeValues[1] == parentNode) { var ls = lastSibling(nodeValues[0], nodeValues[1]); var hcn = hasChildNode(nodeValues[0]); var ino = isNodeOpen(nodeValues[0]); // Write out line & empty icons for (g=0; g<recursedNodes.length; g++) { if (recursedNodes[g] == 1) document.write("<img src=\"../../../public/images/img/line.gif\" align=\"absbottom\" alt=\"\" />"); else document.write("<img src=\"../../../public/images/img/empty.gif\" align=\"absbottom\" alt=\"\" />"); } // put in array line & empty icons if (ls) recursedNodes.push(0); else recursedNodes.push(1); // Write out join icons if (hcn) { if (ls) { document.write("<a href=\"javascript: oc(" + nodeValues[0] + ", 1);\"><img id=\"join" + nodeValues[0] + "\" src=\"../../../public/images/img/"); if (ino) document.write("minus"); else document.write("plus"); document.write("bottom.gif\" align=\"absbottom\" alt=\"Open/Close node\" /></a>"); } else { document.write("<a href=\"javascript: oc(" + nodeValues[0] + ", 0);\"><img id=\"join" + nodeValues[0] + "\" src=\"../../../public/images/img/"); if (ino) document.write("minus"); else document.write("plus"); document.write(".gif\" align=\"absbottom\" alt=\"Open/Close node\" /></a>"); } } else { if (ls) document.write("<img src=\"../../../public/images/img/joinbottom.gif\" align=\"absbottom\" alt=\"\" />"); else document.write("<img src=\"../../../public/images/img/join.gif\" align=\"absbottom\" alt=\"\" />"); } // Start link document.write("<a href=\"" + nodeValues[3] + "\" onmouseover=\"window.status='" + nodeValues[2] + "';return true;\" onmouseout=\"window.status=' ';return true;\" target=\""+targetopc+"\">"); // Write out folder & page icons if (hcn) { document.write("<img id=\"icon" + nodeValues[0] + "\" src=\"../../../public/images/img/folder") if (ino) document.write("open"); document.write(".gif\" align=\"absbottom\" alt=\"Folder\" />"); } else document.write("<img id=\"icon" + nodeValues[0] + "\" src=\"../../../public/images/img/page.gif\" align=\"absbottom\" alt=\"Page\" />"); // Write out node name document.write(nodeValues[2]); // End link document.write("</a><br />"); // If node has children write out divs and go deeper if (hcn) { document.write("<div id=\"div" + nodeValues[0] + "\""); if (!ino) document.write(" style=\"display: none;\""); document.write(">"); addNode(nodeValues[0], recursedNodes); document.write("</div>"); } // remove last line or empty icon recursedNodes.pop(); } } } // Opens or closes a node function oc(node, bottom) { var theDiv = document.getElementById("div" + node); var theJoin = document.getElementById("join" + node); var theIcon = document.getElementById("icon" + node); if (theDiv.style.display == 'none') { if (bottom==1) theJoin.src = icons[3].src; else theJoin.src = icons[2].src; theIcon.src = icons[5].src; theDiv.style.display = ''; } else { if (bottom==1) theJoin.src = icons[1].src; else theJoin.src = icons[0].src; theIcon.src = icons[4].src; theDiv.style.display = 'none'; } } // Push and pop not implemented in IE if(!Array.prototype.push) { function array_push() { for(var i=0;i<arguments.length;i++) this[this.length]=arguments[i]; return this.length; } Array.prototype.push = array_push; } if(!Array.prototype.pop) { function array_pop(){ lastElement = this[this.length-1]; this.length = Math.max(this.length-1,0); return lastElement; } Array.prototype.pop = array_pop; }
JavaScript
var arbolele = new Array(); var nodopadre; var xcom; var auxdir; function creararbolcom (targetopci) { //alert(targetopci); xcom=document.getElementsByTagName("p"); var xdir=document.getElementsByTagName("a"); for (var icomp=0;icomp<xcom.length-xdir.length;icomp++) { arbolele[icomp] = xcom[icomp+xdir.length].textContent; arbolele[icomp] = arbolele[icomp].replace(/(^\s*)|(\s*$)/g,""); } for (var idir=0;idir<xdir.length;idir++) { auxdir=xdir[idir].textContent; auxdir = auxdir.replace(/(^\s*)|(\s*$)/g,""); for (iarbolele=0;iarbolele<arbolele.length;iarbolele++) { if(arbolele[iarbolele].indexOf(auxdir)>-1 ) { //actualiza la direccion href del componente hidrico del arbol,con tipo de registro = 0 //indicando la seleccion de todas las variables medidas arbolele[iarbolele]=arbolele[iarbolele].replace("#",xdir[idir].getAttribute("href")+"&idtipmedicion=0"); //actualiza la direccion href de las variables del componente hidrico del arbol iabauxind = (iarbolele+1).toString().length; for (iarbeletm=0; iarbeletm<arbolele.length; iarbeletm++) { iabauxini = arbolele[iarbeletm].indexOf("|"); if (iabauxind == iabauxini) iabauxdesp = 1; else iabauxdesp = 2; if (arbolele[iarbeletm].substring(iabauxind+iabauxdesp,2*iabauxind+iabauxdesp)==(iarbolele+1).toString()) { arbolele[iarbeletm]=arbolele[iarbeletm].replace("#",xdir[idir].getAttribute("href")+"&idtipmedicion="); } } } } } var tope =xcom.length; for (var ix=0;ix<tope;ix++) { xcom=document.getElementsByTagName("p"); nodopadre=xcom[0].parentNode nodopadre.removeChild(xcom[0]); } return arbolele; }
JavaScript
function initialize() { //se debe crear un nuevo mapa de google maps var mimapa = new hidmapa(); mimapa.Inicializar(); }
JavaScript
var chart; var ModoPresentacion = "individual"; var tipomedicion = "0"; var tiporegistro = "0"; var metodogeneracion = "-1"; function ActualizarModoPresentacion() { var modoPresentacion = document.getElementById("modoPresentacion").value; } function genDataPrueba() { var arreglo2=[]; var arreglo=document.getElementById("registrosFechaValor").value; var arreglo12=arreglo.split(","); var tam=arreglo12.length-1; var indi=[]; for(var j=0;j<19;j++){ var interval= Math.floor(Math.random() * ((tam-2)-2 + 1)) + 2; //indi.push(interval); var as=arreglo12[interval].split("//"); var t=as[0].split("/"); t[1]=999999; //arreglo2.push(parseFloat(t[1])); var fin=""; fin=fin.concat(t[0],"/",t[1],"//",as[1]); arreglo12[interval]=fin; } // console.log(arreglo12); for(var i = 0; i < arreglo12.length; i++) { if(arreglo12[i]!=""){ var temp=arreglo12[i].split("//")[0].split("/")[1]; arreglo2.push(parseFloat(temp));} } /* for(var j=0;j<19;j++){ var interval= Math.floor(Math.random() * (tam-1 + 1)) + 1; indi.push(interval); arreglo2[interval]= NaN; } */ //alert(document.getElementsByName('idR').value); //$("#tabs-1 input").each(function(){ // alert($(this).val()); //}); $('#registrosPruebados').attr('value',arreglo12); $('#registrosPrueba').attr('value',arreglo2); plotear('registrosPruebados','contenedor'); //arreglo=arreglo.split("//"); // } function ActualizarGrafica(idRegistroTipoMedicion, idRegistroTipoRegistro, idRegistroMetodoGeneracion, idEntradaRegistrosFechaValor, idContenedor) { tipomedicion = document.getElementById(idRegistroTipoMedicion).value; tiporegistro = document.getElementById(idRegistroTipoRegistro).value; metodogeneracion = document.getElementById(idRegistroMetodoGeneracion).value; if(VerificarSeleccionTipos(tipomedicion, tiporegistro, metodogeneracion)) { if(ModoPresentacion == "individual") { chart.destroy(); plotear(idEntradaRegistrosFechaValor,idContenedor); } else { var serie = ObtenerSeries(); chart.addSeries(serie[0]); } } } function VerificarSeleccionTipos(tipoMedicion, tipoRegistro, metodoGeneracion) { if(tipoMedicion <= 0) { alert("Debe seleccionar el Tipo de Medicion"); return false; } if(tipoRegistro < 0) { alert("Debe seleccionar el Tipo de Registro"); return false; } if(metodoGeneracion < 0) { alert("Debe seleccionar el Metodo de Generacion"); return false; } return true; } function plotear(idEntradaRegistrosFechaValor, idContenedor) { //alert(idEntradaRegistrosFechaValor); //console.log(idEntradaRegistrosFechaValor); var serie = ObtenerSeries(idEntradaRegistrosFechaValor); console.log(serie); //alert(serie); var chart1 = CrearChart(serie, idContenedor); }; function CrearChart(serie, idContenedor) { var opciones = CrearOpciones(serie, idContenedor); chart = new Highcharts.Chart(opciones); return chart; }; function CrearOpciones(serie, idContenedor) { //alert(serie); var opciones = { chart: { renderTo: idContenedor, zoomType: 'x', type: 'spline', marginRight: 130, marginBottom: 25, spacingRight: 20 }, title: { text: 'Registros', x: -20 //center }, subtitle: { text: document.ontouchstart === undefined ? 'Haz click y arrastra en el area de ploteo para hacer zoom' : 'Drag your finger over the plot to zoom in', x: -20 }, xAxis: { type: 'datetime', //maxZoom: 10 x 24 x 60 x 60 x 1000, // fourteen days maxZoom: 1000, title: { text: null } }, yAxis: { title: { text: 'Valores' }, plotLines: [{ value: 0, width: 0.5, color: '#808080' }] }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -10, y: 100, borderWidth: 0 }, plotOptions: { spline:{ lineWidth : 1, states: { hover: { lineWidth: 3 } }, marker: { enable:false }, } }, series: serie }; return opciones; } function ObtenerSeries(idEntradaRegistrosFechaValor) { var dataRegistros = ObtenerDataSeries(idEntradaRegistrosFechaValor); var series2 = CrearSeries(dataRegistros); return series2; }; function CrearSeries(dataRegistros) { // alert("DATA: "+dataRegistros); var anho = 0; var j = 0; var k = 0; var data = []; var anhos = []; var series = []; for(var i = 0; i < dataRegistros.length; i++) { //dataRegistros[i] = [ [anionumerico, valor], [anio] ] if(parseInt(dataRegistros[i][1]) > anho) { if(anho != 0) { j++; } anho = parseInt(dataRegistros[i][1]); var dataTmp = []; data.push(dataTmp); anhos.push(anho); k = 0; } if(parseInt(dataRegistros[i][1]) == anho) { //data[j]=[anionumerico, valor] data[j].push(dataRegistros[i][0]); k++; } } for(var i = 0; i < data.length; i++) { var serie = CrearSerie(data[i],anhos[i]); series.push(serie); } // alert(series); return series; } function CrearSerie(data, nombre) { //TODO falta convertir entero a cadena var nombreSerie = "serie anio : " + parseInt(nombre).toString() + ""; var serie = { type: 'spline', name: nombreSerie, data: data }; return serie; } function ObtenerDataSeries(idEntradaRegistrosFechaValor) { var dataRegistros = []; var listaRegistros = ExtraerLista(idEntradaRegistrosFechaValor,","); for(var i = 0; i < listaRegistros.length; i++) { //OBTIENE ARREGLOS PARSEADOS POR FECHA VALOR if(listaRegistros[i] != "") { //se obtiene valor numero del año y el valor del registro //array [valoranio valor] var registro = ParsearRegistro(listaRegistros[i]); if(registro != null) { var anhoRegistro = ObtenerAnhoRegistro(listaRegistros[i]);//verificar como se llenan los anoyregistro var registroFecha = []; registroFecha.push(registro); registroFecha.push(anhoRegistro); dataRegistros.push(registroFecha); } } } //alert(dataRegistros); console.log('PROBANDO') console.log(dataRegistros); return dataRegistros; } function ParsearRegistro(registro) { var registroCompleto = []; // fecha-hora/valor // tipomedicion:tiporegistro:metodogeneracion registroCompleto = registro.split("//"); //registro: fecha-hora/valor var dataRegistro = []; dataRegistro = registroCompleto[0].split("/"); var tipos = []; tipos = registroCompleto[1].split(":"); var registro; if(esRegistroValido(tipos)) { var valorNumericoFechaRegistro = ValorNumericoFecha(dataRegistro[0]); var valorRegistro = parseFloat(dataRegistro[1]); if(valorRegistro == 999999) { valorRegistro = null; } registro = [valorNumericoFechaRegistro , valorRegistro]; } else { registro = null; } return registro; } function genHole(registro) { console.log("sigue en prueba"); } function esRegistroValido(tipos) { if(tipomedicion != 0 && tiporegistro != 0) { if(tipos[0] == tipomedicion && tipos[1] == tiporegistro && tipos[2] == metodogeneracion) { return true; } } else if(tipomedicion != 0 && tiporegistro == 0) { if(tipos[0] == tipomedicion && tipos[2] == metodogeneracion) { return true; } } else if(tipomedicion == 0 && tiporegistro != 0) { if(tipos[1] == tiporegistro && tipos[2] == metodogeneracion) { return true; } } else { if(tipos[2] == metodogeneracion) { return true; } } return false; } function ValorNumericoFecha(registroFecha) { var anho = parseInt(registroFecha.substring(0,4)); var mes; if(registroFecha.substring(5,6) == "0") { mes = parseInt(registroFecha.substring(6,7)); } else { mes = parseInt(registroFecha.substring(5,7)); } var dia; if(registroFecha.substring(8,9) == "0") { dia = parseInt(registroFecha.substring(9,10)); } else { dia = parseInt(registroFecha.substring(8,10)); } var hora = parseInt(registroFecha.substring(11,13)); var minuto = parseInt(registroFecha.substring(14,16)); var segundo = parseInt(registroFecha.substring(17,19)); var milisegundo = parseInt(registroFecha.substring(20)); //var fechaNumero = Date.UTC(anho, mes - 1 , dia, hora, minuto, segundo, milisegundo); //se debe utilizar un unico año(bisiesto) para todos los registros, para poder //visualizar las series de datos de todos los años en una sola grafica var fechaNumero = Date.UTC(2012, mes - 1 , dia, hora, minuto, segundo, milisegundo); console.log(fechaNumero); return fechaNumero; } function ObtenerAnhoRegistro(registro) { var registroCompleto = []; // fecha-hora/valor // tipomedicion:tiporegistro:metodogeneracion registroCompleto = registro.split("//"); //registro: fecha-hora/valor var dataRegistro = []; dataRegistro = registroCompleto[0].split("/"); var anho = dataRegistro[0].substring(0,4); return anho; } function ObtenerIdsRegistros(idDescripcionRegistros) { var descripcion = document.getElementById(idDescripcionRegistros).value; console.log(descripcion); descripcion = descripcion.substring(13, descripcion.length -2); document.getElementById(idDescripcionRegistros).value = descripcion; var lista = ExtraerLista(idDescripcionRegistros,"],"); document.getElementById(idDescripcionRegistros).value = lista; var lista2 = ExtraerLista(idDescripcionRegistros,", Hidregistro["); return lista2; }
JavaScript
/**************************************************************** Mapa de Google Maps - Se definen variables globales, utilizadas desde los diversos scripts para el manejo del mapa - Se construye la clase(clase ficticias ya que no son realmente clases ni objetos en javascript) para el mapa - Se definen metodos generales y metodos que seran asignados a los metodos de la clase hidmapa *las clases llevan el prefijo "hid" ***************************************************************/ //mapa de Google Maps var mapa; //booleano que indica si se esta modificando los limites del mapa var mapaModificado = false; //limites del mapa var valorMaximoLatitud = -34.397; var valorMinimoLatitud = -34.397; var valorMaximoLongitud = 150.644; var valorMinimoLongitud = 150.644; //bordes del mapa actual var strictBounds; //marcadores var markersArray = []; //arreglo de lineas(nodo inicio y nodo fin) var lineArray = []; //arreglo de componentes en el mapa var componentes = []; //arreglo de componentes eliminados var eliminadosArray = []; //arreglo de objetos polylines var poly = []; //tipos de punto de monitoreo var tipoPuntoMonitoreo = []; //Clase para la creacion de un mapa de google maps function hidmapa() { //metodos this.Inicializar = function () { this.DefinirComponentes(); this.Delimitar(); this.AgregarEventosMapa(); this.AgregarControlesMapa(); this.MostrarMarcadores(); this.MostrarLineas(); }; this.DefinirComponentes = function () { /*Debido a que los datos son cargados de la base de datos, estos son puestos previamente en entradas (inputs html) a partir de los cuales se obtienen los mismos*/ /* Se debe obtener la informacion de los componentes (nombres, latitudes, etc) */ var latcomponentes = ExtraerLista("idlatitudes",","); var lngcomponentes = ExtraerLista("idlongitudes",","); var nombcomponentes = ExtraerLista("idnombres",","); var tipospuntosmonitoreo = ExtraerLista("idtiposptomon",","); /* se debe obtener los tipos(indicando si son para objetos unicos o lineas)*/ var tipos = ExtraerLista("idtipos",","); var tiposuni = ExtraerLista("idtiposuni",","); /* se debe obtener los ids*/ var ids = ExtraerLista("idids",","); var aristas = ExtraerLista("idaristas",";"); /* ruta donde se ubican las imagenes de los componentes*/ var rutaBase = this.ObtenerRutaComponentes(); //Con la informacion se crean los objetos nodos y aristas var aristasArray = this.CrearComponentesNodo(ids,tipos,tiposuni,latcomponentes,lngcomponentes, aristas, rutaBase, nombcomponentes, tipospuntosmonitoreo); this.CrearComponentesArista(aristasArray); }; this.Delimitar = function() { /* Necesitamos obtener los limites del mapa */ var latitudminima = ExtraerValor("latiminima"); var latitudmaxima = ExtraerValor("latimaxima"); var longitudminima = ExtraerValor("longminima"); var longitudmaxima = ExtraerValor("longmaxima"); // Se debe asignar los limites obtenidos del mapa en variables globales this.AlmacenarLimites(longitudmaxima, latitudmaxima, longitudminima, latitudminima); // Se debe encontrar el centro del mapa para ubicarlo y con ella crear el mapa propiamente dicho var latlng = this.ObtenerPosicionCentralMapa(longitudmaxima, latitudmaxima, longitudminima, latitudminima); this.DefinirMapa(latlng); }; this.AgregarEventosMapa = function() { //Debemos de agregar funcionalidades al mapa cuando ocurran diversos eventos //Se debe controlar que al arrastrar el mapa no supere los bordes google.maps.event.addListener(mapa, 'dragend', this.ControlarBordes); //se debe cntrolar que el acercamiento al mapa no supere los limites del mapa, es decir que no se pueda alejar //la imagen y nos permita ver parte del mapa fuera de los bordes definidos google.maps.event.addListener(mapa, 'zoom_changed', ControlarZoom); //Se debe permitir agregar los marcadores dentro del mapa google.maps.event.addListener(mapa, 'click', function(event) { //se debe verificar si fue seleccionado un componente de la lista de componentes if(document.getElementById("marcador").value != "") { //se agrega una ventana de dialogo para ingresar los datos del componente AgregarNombre(event.latLng); } }); }; this.AgregarControlesMapa = function() { /* Se debe agregar dentro del mapa "div" para agregar botones dentro del mapa */ var homeControlDiv = document.createElement('DIV'); var controlesmapa = new hidcontrolmapa(homeControlDiv); controlesmapa.InicializarControles(); controlesmapa.controlDiv.index = 1; //se debe indicar la posicion dentro del mapa donde estaran los controladores mapa.controls[google.maps.ControlPosition.TOP_LEFT].push(controlesmapa.controlDiv); }; this.MostrarMarcadores = MostrarMarcadores; this.MostrarLineas = MostrarLineas; this.ControlarBordes = ControlarBordes; this.AgregarEventoLinea = AgregarEventoLinea; this.EliminarLinea = EliminarLinea; this.ObtenerRutaComponentes = function () { var rutaBase = '../../../../public/images/Componentes/'; return rutaBase; } this.CrearComponentesNodo = function (ids, tipos, tiposuni, latcomponentes, lngcomponentes,arist, rutaBase, nombcomponentes, tipospuntosmonitoreo) { var contador = 0; var aristasArray = []; /* se debe de crear objetos de tipo componentes con los datos que se cargan */ for (var i = 0; i < latcomponentes.length - 1; i++) { if(this.esNodo(tiposuni[i])) { //creamos y agregamos los componentes a la lista de componentes nodos var componente = this.CrearComponenteNodo(ids[i], tipos[i], tiposuni[i], latcomponentes[i], lngcomponentes[i], nombcomponentes[i], tipospuntosmonitoreo[i]); this.CrearMarcador(componente.latitud, componente.longitud, 'Componente', rutaBase, componente); } else { //definimos los componente de mas de un elementos var aristadiv = []; aristadiv = arist[contador].split(","); //creamos y agregamos los componentes a la lista de componentes arista var arista = this.CrearComponenteArista(aristadiv, tipos[i],nombcomponentes[i], tipospuntosmonitoreo[i]); aristasArray.push(arista); contador++; } } return aristasArray; } this.CrearComponenteNodo = function (ids, tipos, tiposuni, latcomponentes, lngcomponentes, nombcomponentes,tipopuntosmonitoreo) { //creamos un objeto componente (nodo) var componente = new hidcomponente(ids, tipos, tiposuni, latcomponentes, lngcomponentes, nombcomponentes, tipopuntosmonitoreo); //agregamos los componentes a la lista de componentes componentes.push(componente); return componente; } this.CrearComponentesArista = function (aristasArray) { //creamos un objeto componente temporal solo para utilizar sus metodos var cmp = new hidcomponente(1,1,1,1); for (var j = 0; j < aristasArray.length; j++) { //encontramos los nodos que pertenecen a una arista var posicion1 = cmp.hidcomp_findById(componentes,aristasArray[j].idnodoinicio); var posicion2 = cmp.hidcomp_findById(componentes,aristasArray[j].idnodofin); var nodoinicio = componentes[posicion1]; var nodofin = componentes[posicion2]; //almacenamos sus datos dentro de una lista y agregamos dicha lista al //arreglo de aristas var inifin = []; inifin.push(nodoinicio.latitud); inifin.push(nodoinicio.longitud); inifin.push(nodofin.latitud); inifin.push(nodofin.longitud); inifin.push(aristasArray[j].tipo); inifin.push(aristasArray[j].ide); inifin.push(nodoinicio.ide); inifin.push(nodofin.ide); inifin.push(aristasArray[j].nombrearista); inifin.push(aristasArray[j].tipoptomon); lineArray.push(inifin); } } this.CrearComponenteArista = function (aristadiv, tipo, nombrearista, tipospuntosmonitoreo) { var aristas = {"idnodoorigen":0, "idnodofin":1, "idarista":2}; var arista = new hidarista(aristadiv[aristas.idarista], tipo, aristadiv[aristas.idnodoorigen],aristadiv[aristas.idnodofin], nombrearista, tipospuntosmonitoreo); return arista; } this.CrearMarcador = function (latitud, longitud, nombre, rutaBase, componente) { //se debe agregar los eventos para cada marcador correspondiente a cada evento var posicion = new google.maps.LatLng(latitud,longitud); var nuevoMarcador = new hidmarcador(posicion, nombre, rutaBase, componente.tipoptomon); nuevoMarcador.AgregarEventosMarcador(componente); } this.esNodo = function (tipo) { //verificamos si el tipo componente obtenido es un nodo, es decir si en tipo unico es true if(tipo == "true") return true; else return false; } this.AlmacenarLimites = function (lonmax, latmax, lonmin, latmin) { valorMaximoLongitud = lonmax; valorMaximoLatitud = latmax; valorMinimoLongitud = lonmin; valorMinimoLatitud = latmin; } this.ObtenerPosicionCentralMapa = function (lonmax, latmax, lonmin, latmin) { /* Se debe encontrar el centro del mapa para ubicarlo */ var longitudpromedio = (parseFloat(lonmax) + parseFloat(lonmin))/2; var latitudpromedio = (parseFloat(latmax) + parseFloat(latmin))/2; //Se debe hacer el redondeo correspondiente longitudpromedio = longitudpromedio*Math.pow(10,14); latitudpromedio = latitudpromedio*Math.pow(10,14); longitudpromedio = Math.round(longitudpromedio); latitudpromedio = Math.round(latitudpromedio); longitudpromedio = longitudpromedio/Math.pow(10,14); latitudpromedio = latitudpromedio/Math.pow(10,14); //variable donde se almacenara el valor correspondiente al centro del mapa var latlng; /* Se debe verificar que los limites posean un valor */ if(lonmax != 0 && latmax != 0 && lonmin != 0 && latmin != 0) { latlng = new google.maps.LatLng(latitudpromedio, longitudpromedio); } else { //valor por defecto (deberian ser las coordenadas de Arequipa) latlng = new google.maps.LatLng(-34.397, 150.644); } return latlng; } this.DefinirMapa = function (latlng) { var myOptions = { zoom: 8, center: latlng, disableDefaultUI: true, mapTypeId: google.maps.MapTypeId.ROADMAP, disableDoubleClickZoom: true }; //creamos el mapa mapa = new google.maps.Map(document.getElementById("map_canvas"),myOptions); //asignamos los bordes del mapa a una variable global strictBounds = mapa.getBounds(); } } function ControlarBordes() { //se obtiene los valores de los bordes del nuevo mapa var nuevosBordes = mapa.getBounds(); var valorMaximoLongitudParcial = nuevosBordes.getNorthEast().lng(); var valorMaximoLatitudParcial = nuevosBordes.getNorthEast().lat(); var valorMinimoLongitudParcial = nuevosBordes.getSouthWest().lng(); var valorMinimoLatitudParcial = nuevosBordes.getSouthWest().lat(); //Verificar que el mapa no este en estado de modificacion if(mapaModificado != true) { //se debe de verificar que los bordes no sean los inicializados por defecto if(valorMaximoLatitud != 0 && valorMinimoLatitud != 0 && valorMaximoLongitud != 0 && valorMinimoLongitud != 0) { /* Comprobamos que los limites de la posicion actual del mapa * no superen los limites establecidos * */ if(valorMaximoLongitudParcial > valorMaximoLongitud) { var dif = (valorMaximoLongitudParcial - valorMaximoLongitud); valorMaximoLongitudParcial = valorMaximoLongitudParcial - dif; valorMinimoLongitudParcial = valorMinimoLongitudParcial - dif; } if(valorMinimoLongitudParcial < valorMinimoLongitud) { var dif = (valorMinimoLongitud - valorMinimoLongitudParcial); valorMinimoLongitudParcial = valorMinimoLongitudParcial + dif; valorMaximoLongitudParcial = valorMaximoLongitudParcial + dif; } if(valorMaximoLatitudParcial > valorMaximoLatitud) { var dif = (valorMaximoLatitudParcial - valorMaximoLatitud); valorMaximoLatitudParcial = valorMaximoLatitudParcial - dif; valorMinimoLatitudParcial = valorMinimoLatitudParcial - dif; } if(valorMinimoLatitudParcial < valorMinimoLatitud) { var dif = (valorMinimoLatitud - valorMinimoLatitudParcial); valorMinimoLatitudParcial = valorMinimoLatitudParcial + dif; valorMaximoLatitudParcial = valorMaximoLatitudParcial + dif; } //se debe calcular la nueva posicion del centro del mapa var lonpro; var latpro; lonpro = (valorMaximoLongitudParcial + valorMinimoLongitudParcial)/2; latpro = (valorMaximoLatitudParcial + valorMinimoLatitudParcial)/2; lonpro = lonpro*Math.pow(10,14); latpro = latpro*Math.pow(10,14); lonpro = Math.round(lonpro); latpro = Math.round(latpro); lonpro = lonpro/Math.pow(10,14); latpro = latpro/Math.pow(10,14); var punto = new google.maps.LatLng(latpro, lonpro); mapa.setCenter(punto); } } else { //se obtiene los valores de los componentes que estan mas hacia los bordes var cmp = new hidcomponente(1,1,1,1); if(cmp.hidcomp_numElem(componentes) > 0) { var valorMaximoLongitudComponente = cmp.hidcomp_lngmayor(componentes); var valorMaximoLatitudComponente = cmp.hidcomp_latmayor(componentes); var valorMinimoLongitudComponente = cmp.hidcomp_lngmenor(componentes); var valorMinimoLatitudComponente = cmp.hidcomp_latmenor(componentes); /* Se debe comprobar que los limites del mapa no dejen fuera los componentes */ if(valorMaximoLongitudParcial < valorMaximoLongitudComponente) { var dif = (valorMaximoLongitudComponente - valorMaximoLongitudParcial); valorMaximoLongitudParcial = valorMaximoLongitudParcial + dif; valorMinimoLongitudParcial = valorMinimoLongitudParcial + dif; } if(valorMinimoLongitudParcial > valorMinimoLongitudComponente) { var dif = (valorMinimoLongitudParcial - valorMinimoLongitudComponente); valorMinimoLongitudParcial = valorMinimoLongitudParcial - dif; valorMaximoLongitudParcial = valorMaximoLongitudParcial - dif; } if(valorMaximoLatitudParcial < valorMinimoLatitudComponente) { var dif = (valorMinimoLatitudComponente - valorMaximoLatitudParcial); valorMaximoLatitudParcial = valorMaximoLatitudParcial + dif; valorMinimoLatitudParcial = valorMinimoLatitudParcial + dif; } if(valorMinimoLatitudParcial > valorMaximoLatitudComponente) { var dif = (valorMinimoLatitudParcial - valorMaximoLatitudComponente); valorMinimoLatitudParcial = valorMinimoLatitudParcial - dif; valorMaximoLatitudParcial = valorMaximoLatitudParcial - dif; } document.getElementById("idcomponenteslat").value = valorMaximoLongitudComponente; document.getElementById("idcomponenteslong").value = valorMaximoLatitudComponente; document.getElementById("idtiposdecomponente").value = valorMinimoLongitudComponente; document.getElementById("ididecomponente").value = valorMinimoLatitudComponente; } //se debe calcular la nueva posicion del centro del mapa var lonpro; var latpro; lonpro = (valorMaximoLongitudParcial + valorMinimoLongitudParcial)/2; latpro = (valorMaximoLatitudParcial + valorMinimoLatitudParcial)/2; lonpro = lonpro*Math.pow(10,14); latpro = latpro*Math.pow(10,14); lonpro = Math.round(lonpro); latpro = Math.round(latpro); lonpro = lonpro/Math.pow(10,14); latpro = latpro/Math.pow(10,14); var punto = new google.maps.LatLng(latpro, lonpro); mapa.setCenter(punto); } }; function ControlarZoom() { if(mapa.getZoom() > 10) { mapa.setZoom(10); } if(mapa.getZoom() < 8) { mapa.setZoom(8); } ControlarBordes(); }; function MostrarMarcadores() { /* se debe recorrer el arreglo de marcadores y agregarlos al mapa (grafica)*/ if (markersArray) { for (i in markersArray) { markersArray[i].setMap(mapa); } } }; function MostrarLineas() { //se recorre el arreglo de lineas y se actualiza las posiciones for (i in lineArray) { CrearPolilinea(i,'#000000'); ActualizarPathPolilinea(i); AgregarEventoLinea(poly[i]); } }; function CrearPolilinea(posicion, color) { var polyOptions = { strokeColor: color, strokeOpacity: 1.0, strokeWeight: 3, clickable: true } if(poly[posicion] == null) { poly[posicion] = new google.maps.Polyline(polyOptions); poly[posicion].setMap(mapa); poly[posicion].posicion = posicion; } } function ActualizarPathPolilinea(posicion) { var pathpolilinea = poly[posicion].getPath(); //se debe de agregar los puntos de cada elemento del arreglo de lineas en una nueva polilinea //del mapa var linea = lineArray[posicion]; var latitudlongitud1 = new google.maps.LatLng(linea[0], linea[1]); var latitudlongitud2 = new google.maps.LatLng(linea[2], linea[3]); poly[posicion].idpoly = linea[5]; //quitamos los elementos y lo llenamos con los nuevos datos (laitudes y longitudes) pathpolilinea.clear(); pathpolilinea.push(latitudlongitud1); pathpolilinea.push(latitudlongitud2); //asignamos esa nueva posicion al path de la lineas poly[i].setPath(pathpolilinea); } function AgregarEventoLinea(polylinea) { //se debe agregar los eventos a cada polilinea google.maps.event.addListener(polylinea, 'dblclick', function() { EliminarLinea(polylinea.posicion, polylinea.idpoly); }); }; function EliminarLinea(posicion, idpoly) { //obtenemos el path de la linea a eliminar y eliminamos sus componentes var pathpolilinea = poly[posicion].getPath(); pathpolilinea.pop(); pathpolilinea.pop(); if(isNaN(idpoly) == false) { eliminadosArray.push(idpoly); } }; function imagenMarcador(rutaMarcador, componenteunico) { //asignamos la ruta de la imagen del componente y su indicador de si es un elemento o varios document.getElementById("marcador").value = rutaMarcador; document.getElementById("marcadorunico").value = componenteunico; if(componenteunico == "true") { document.getElementById("inilinea").value = ""; document.getElementById("inilinea2").value = ""; } }; //extraer los valores de una lista contenida dentro de una entrada //html (input), cuyos datos estan separados por algun delimitador function ExtraerLista(nombreLista, delimitador) { var lista = []; lista = document.getElementById(nombreLista).value.split(delimitador); //alert(lista); return lista; }; //extraer los valores de una entrada html function ExtraerValor(identificador) { var valor = document.getElementById(identificador).value; return valor; }; function AsignarValor(identificador, valor) { document.getElementById(identificador).value = valor; } function AgregarNombre(posicion) { //construimos una ventana para el ingreso del nombre del componente var htmlBox = CrearVentanaModal("Nombre de Componente","300px","20px"); var input = CrearInputText("text","30","30"); var select = CrearComboSeleccion(); var br = CrearSaltoDeLinea(); var editBtn = CrearBoton("Agregar"); var container = CrearContenedorVentana(); container.appendChild(htmlBox); container.appendChild(input); container.appendChild(select); container.appendChild(br); container.appendChild(editBtn); //creamos una ventana de informacion con la ventana creada var infowindow = new google.maps.InfoWindow({ content: container, position: posicion }); //asignamos el evento al boton de la ventana para 'click' google.maps.event.addDomListener(editBtn, "click", function() { input.readOnly = true; setTimeout(function () { infowindow.close(); }, 500); //CrearContenidoMarcador(posicion, input.value); CrearContenidoMarcador(posicion, input.value, select.value); }); //mostramos la ventana en el mapa infowindow.open(mapa); } function CrearVentanaModal(titulo, ancho, alto) { var htmlBox = document.createElement("div"); htmlBox.innerHTML = titulo; htmlBox.style.width = ancho; htmlBox.style.height = alto; return htmlBox; } function CrearInputText(tipo, tamaño, maximoTamaño) { var input = document.createElement("input"); input.type = tipo; input.size = tamaño; input.maxLength = maximoTamaño; return input; } function CrearSaltoDeLinea() { var br = document.createElement('br'); return br; } function CrearContenedorVentana() { var container = document.createElement("div"); container.style.position = "relative"; return container; } function CrearBoton(nombre) { var editBtn = document.createElement("button"); editBtn.style.width = "100px"; editBtn.style.height = "25px"; var buttonText = document.createTextNode(nombre); editBtn.appendChild(buttonText); return editBtn; } function CrearComboSeleccion() { var idsTipoPuntoMonitoreo = ExtraerLista("idsTipoPuntoMonitoreo",","); var nombresTipoPuntoMonitoreo = ExtraerLista("nomTipoPuntoMonitoreo",","); var select = document.createElement('select'); for (var i = 0; i < idsTipoPuntoMonitoreo.length - 1; i++) { var option = CrearOpcionesComboSeleccion(idsTipoPuntoMonitoreo[i], nombresTipoPuntoMonitoreo[i]); select.appendChild(option); } return select; } function CrearOpcionesComboSeleccion(id, nombre) { var option = document.createElement('option'); var t = document.createTextNode(nombre); option.appendChild(t); option.setAttribute("value",parseInt(id)); return option; } function CrearContenidoMarcador(posicion, nombreComponente, tipoPuntoMonitoreo) { //se crea una marcador y los agregamos a la lista de marcadores par aluego mostrarlo var hidmarcador1 = new hidmarcador(posicion,nombreComponente,'../../../../public/images/Componentes/', tipoPuntoMonitoreo); hidmarcador1.AgregarMarcador(); MostrarMarcadores(); }
JavaScript
function hidcontrolmapa(controlDiv) { this.controlDiv = controlDiv; this.InicializarControles = function () { this.CrearControl('Modificar Area','click', this.Modificar); this.CrearControl('Delimitar Area','click',this.Delimitar); this.CrearControl('Guardar','click', this.Guardar); }; this.CrearControl = function (nombrefuncion, evento, funcion) { // Set CSS styles for the DIV containing the control // Setting padding to 5 px will offset the control // from the edge of the map this.controlDiv.style.padding = '5px'; // Set CSS for the control border var controlUI = this.CrearUI('white', 'solid', '2px', 'pointer', 'center', 'Click aqui'); this.controlDiv.appendChild(controlUI); // Set CSS for the control interior var controlText = this.CrearTexto('Arial,sans-serif', '12px', '4px', '4px', nombrefuncion) controlUI.appendChild(controlText); this.AgregarEventoControl(controlUI, evento, funcion); }; this.CrearUI = function (fondo, estiloborde, anchoborde, cursor, alineaciontexto, titulo) { // Set CSS for the control border var controlUI = document.createElement('DIV'); controlUI.style.backgroundColor = fondo; controlUI.style.borderStyle = estiloborde; controlUI.style.borderWidth = anchoborde; controlUI.style.cursor = cursor; controlUI.style.textAlign = alineaciontexto; controlUI.title = titulo; return controlUI; }; this.CrearTexto = function (fuente, tamaño, paddingLeft, paddingRight,nombre) { // Set CSS for the control interior var controlText = document.createElement('DIV'); controlText.style.fontFamily = fuente; controlText.style.fontSize = tamaño; controlText.style.paddingLeft = paddingLeft; controlText.style.paddingRight = paddingRight; controlText.innerHTML = nombre; return controlText; }; this.AgregarEventoControl = function (controlUI, evento, funcion) { google.maps.event.addDomListener(controlUI, evento, funcion); }; this.Modificar = function () { mapaModificado = true; mapa.setOptions({zoomControl: true}); }; this.Delimitar = function () { strictBounds = mapa.getBounds(); //obtener los valores de los limites donde el mapa se encuentra valorMaximoLongitud = strictBounds.getNorthEast().lng(); valorMaximoLatitud = strictBounds.getNorthEast().lat(); valorMinimoLongitud = strictBounds.getSouthWest().lng(); valorMinimoLatitud = strictBounds.getSouthWest().lat(); //asignarlos a entradas de un formulario document.getElementById("longmaxima").value = valorMaximoLongitud; document.getElementById("latimaxima").value = valorMaximoLatitud; document.getElementById("longminima").value = valorMinimoLongitud; document.getElementById("latiminima").value = valorMinimoLatitud; //deshabilitamos las opciones de control del mapa mapa.setOptions({disableDefaultUI: true}); //indicamos que el estado de modificacion es falso ya que se esta delimitando el mapa mapaModificado = false; //Se debe enviar a guardar document.formLatiLong.submit(); }; this.Guardar = function () { //se almacena las listas de latitudes, longitudes, etc de los componentes en entradas html las cuales son //enviadas a traves de un formulario var cmp = new hidcomponente(1,1,1,1); document.getElementById("idcomponenteslat").value = cmp.hidcomp_latarray(componentes); document.getElementById("idcomponenteslong").value = cmp.hidcomp_lngarray(componentes); document.getElementById("idcomponentesnomb").value = cmp.hidcomp_nombarray(componentes); document.getElementById("idcomponentestipptomon").value = cmp.hidcomp_tipoptomonarray(componentes); document.getElementById("idtiposdecomponente").value = cmp.hidcomp_tiparray(componentes); document.getElementById("ididecomponente").value = cmp.hidcomp_idearray(componentes); document.getElementById("ideliminados").value = eliminadosArray; document.getElementById("lineas").value = lineArray; document.formCompLatiLong.submit(); }; }
JavaScript