1/**
2 * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
3 * For licensing, see LICENSE.html or http://ckeditor.com/license
4 */
5var ckgeditLinkTypeId,ckgeditAlignInputId;
6var ckgeditDwikiSaveDir= oDokuWiki_FCKEditorInstance.save_dir;
7var ckgeditImageReselectObj = { 'align': "", 'link':""};
8window.onbeforeunload = function() { };
9
10(function() {
11	var imageDialog = function( editor, dialogType ) {
12			// Load image preview.
13            oDokuWiki_FCKEditorInstance.Lang = editor.lang;
14			var IMAGE = 1,
15				LINK = 2,
16				PREVIEW = 4,
17				CLEANUP = 8,
18				regexGetSize = /^\s*(\d+)((px)|\%)?\s*$/i,
19				regexGetSizeOrEmpty = /(^\s*(\d+)((px)|\%)?\s*$)|^$/i,
20				pxLengthRegex = /^\d+px$/;
21
22			var onSizeChange = function() {
23					var value = this.getValue(),
24						// This = input element.
25						dialog = this.getDialog(),
26						aMatch = value.match( regexGetSize ); // Check value
27					if ( aMatch ) {
28						if ( aMatch[ 2 ] == '%' ) // % is allowed - > unlock ratio.
29						switchLockRatio( dialog, false ); // Unlock.
30						value = aMatch[ 1 ];
31					}
32
33					// Only if ratio is locked
34					if ( dialog.lockRatio ) {
35						var oImageOriginal = dialog.originalElement;
36						if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' ) {
37							if ( this.id == 'txtHeight' ) {
38								if ( value && value != '0' )
39									value = Math.round( oImageOriginal.$.width * ( value / oImageOriginal.$.height ) );
40								if ( !isNaN( value ) )
41									dialog.setValueOf( 'info', 'txtWidth', value );
42							} else //this.id = txtWidth.
43							{
44								if ( value && value != '0' )
45									value = Math.round( oImageOriginal.$.height * ( value / oImageOriginal.$.width ) );
46								if ( !isNaN( value ) )
47									dialog.setValueOf( 'info', 'txtHeight', value );
48							}
49						}
50					}
51					updatePreview( dialog );
52				};
53
54			var updatePreview = function( dialog ) {
55					//Don't load before onShow.
56					if ( !dialog.originalElement || !dialog.preview )
57						return 1;
58
59					// Read attributes and update imagePreview;
60					dialog.commitContent( PREVIEW, dialog.preview );
61					return 0;
62				};
63
64			// Custom commit dialog logic, where we're intended to give inline style
65			// field (txtdlgGenStyle) higher priority to avoid overwriting styles contribute
66			// by other fields.
67			function commitContent() {
68				var args = arguments;
69				var inlineStyleField = this.getContentElement( 'advanced', 'txtdlgGenStyle' );
70				inlineStyleField && inlineStyleField.commit.apply( inlineStyleField, args );
71
72				this.foreach( function( widget ) {
73					if ( widget.commit && widget.id != 'txtdlgGenStyle' )
74						widget.commit.apply( widget, args );
75				});
76			}
77
78			// Avoid recursions.
79			var incommit;
80
81			// Synchronous field values to other impacted fields is required, e.g. border
82			// size change should alter inline-style text as well.
83			function commitInternally( targetFields ) {
84				if ( incommit )
85					return;
86
87				incommit = 1;
88
89				var dialog = this.getDialog(),
90					element = dialog.imageElement;
91                 ckgeditAlignInputId =dialog.getContentElement('info',  'cmbAlign').getInputElement().$.id;
92                 ckgeditLinkTypeId =dialog.getContentElement('info',  'cmbLinkType').getInputElement().$.id;
93
94                 if(ckgeditImageReselectObj['align']) {
95                    var align_value = 0;
96                     switch (ckgeditImageReselectObj['align']) {
97                         case 'medialeft':
98                            align_value = 1;
99                            break;
100                         case 'mediaright':
101                            align_value = 2;
102                            break;
103                        case 'mediacenter':
104                            align_value = 3;
105                            break;
106                        case 'baseline':
107                            align_value = 4;
108                            break ;
109                     }
110                     var align_sel = document.getElementById(ckgeditAlignInputId);
111                     align_sel.options[align_value].selected = true;
112                     ckgeditImageReselectObj['align'] = "";
113                 }
114                 if(ckgeditImageReselectObj['link']) {
115                     var link_value = 0;
116                     switch(ckgeditImageReselectObj['link']) {
117                        case 'detail':
118                            link_value = 0;
119                            break;
120                        case 'direct':
121                            link_value = 1;
122                            break;
123                        case 'nolink':
124                            link_value = 2;
125                            break;
126                        case 'linkonly':
127                            link_value = 3;
128                            break;
129                     }
130                     var link_sel = document.getElementById(ckgeditLinkTypeId);
131                     link_sel.options[link_value].selected = true;
132                     ckgeditImageReselectObj['link'] = "";
133                 }
134                 oDokuWiki_FCKEditorInstance.isLocalDwikiBrowser=false;
135               //  oDokuWiki_FCKEditorInstance.isDwikiMediaFile = false;
136                 ckgeditImageReselectObj = { 'align': "", 'link':""};
137				if ( element ) {
138					// Commit this field and broadcast to target fields.
139					this.commit( IMAGE, element );
140
141					targetFields = [].concat( targetFields );
142					var length = targetFields.length,
143						field;
144					for ( var i = 0; i < length; i++ ) {
145						field = dialog.getContentElement.apply( dialog, targetFields[ i ].split( ':' ) );
146						// May cause recursion.
147						field && field.setup( IMAGE, element );
148					}
149				}
150
151				incommit = 0;
152			}
153
154			var switchLockRatio = function( dialog, value ) {
155					if ( !dialog.getContentElement( 'info', 'ratioLock' ) )
156						return null;
157
158					var oImageOriginal = dialog.originalElement;
159
160					// Dialog may already closed. (#5505)
161					if ( !oImageOriginal )
162						return null;
163
164					// Check image ratio and original image ratio, but respecting user's preference.
165					if ( value == 'check' ) {
166						if ( !dialog.userlockRatio && oImageOriginal.getCustomData( 'isReady' ) == 'true' ) {
167							var width = dialog.getValueOf( 'info', 'txtWidth' ),
168								height = dialog.getValueOf( 'info', 'txtHeight' ),
169								originalRatio = oImageOriginal.$.width * 1000 / oImageOriginal.$.height,
170								thisRatio = width * 1000 / height;
171							dialog.lockRatio = false; // Default: unlock ratio
172
173							if ( !width && !height )
174								dialog.lockRatio = true;
175							else if ( !isNaN( originalRatio ) && !isNaN( thisRatio ) ) {
176								if ( Math.round( originalRatio ) == Math.round( thisRatio ) )
177									dialog.lockRatio = true;
178							}
179						}
180					} else if ( value != undefined )
181						dialog.lockRatio = value;
182					else {
183						dialog.userlockRatio = 1;
184						dialog.lockRatio = !dialog.lockRatio;
185					}
186
187					var ratioButton = CKEDITOR.document.getById( btnLockSizesId );
188					if ( dialog.lockRatio )
189						ratioButton.removeClass( 'cke_btn_unlocked' );
190					else
191						ratioButton.addClass( 'cke_btn_unlocked' );
192
193					ratioButton.setAttribute( 'aria-checked', dialog.lockRatio );
194
195					// Ratio button hc presentation - WHITE SQUARE / BLACK SQUARE
196					if ( CKEDITOR.env.hc ) {
197						var icon = ratioButton.getChild( 0 );
198						icon.setHtml( dialog.lockRatio ? CKEDITOR.env.ie ? '\u25A0' : '\u25A3' : CKEDITOR.env.ie ? '\u25A1' : '\u25A2' );
199					}
200
201					return dialog.lockRatio;
202				};
203
204			var resetSize = function( dialog ) {
205					var oImageOriginal = dialog.originalElement;
206					if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' ) {
207						var widthField = dialog.getContentElement( 'info', 'txtWidth' ),
208							heightField = dialog.getContentElement( 'info', 'txtHeight' );
209						widthField && widthField.setValue( oImageOriginal.$.width );
210						heightField && heightField.setValue( oImageOriginal.$.height );
211					}
212					updatePreview( dialog );
213				};
214
215			var setupDimension = function( type, element ) {
216					if ( type != IMAGE )
217						return;
218					function checkDimension( size, defaultValue ) {
219						var aMatch = size.match( regexGetSize );
220						if ( aMatch ) {
221							if ( aMatch[ 2 ] == '%' ) // % is allowed.
222							{
223								aMatch[ 1 ] += '%';
224								switchLockRatio( dialog, false ); // Unlock ratio
225							}
226							return aMatch[ 1 ];
227						}
228						return defaultValue;
229					}
230
231					var dialog = this.getDialog(),
232						value = '',
233						dimension = this.id == 'txtWidth' ? 'width' : 'height',
234						size = element.getAttribute( dimension );
235					if ( size )
236						value = checkDimension( size, value );
237					value = checkDimension( element.getStyle( dimension ), value );
238
239					this.setValue( value );
240				};
241
242			var previewPreloader;
243
244			var onImgLoadEvent = function() {
245					// Image is ready.
246					var original = this.originalElement;
247					original.setCustomData( 'isReady', 'true' );
248					original.removeListener( 'load', onImgLoadEvent );
249					original.removeListener( 'error', onImgLoadErrorEvent );
250					original.removeListener( 'abort', onImgLoadErrorEvent );
251
252					// Hide loader
253					CKEDITOR.document.getById( imagePreviewLoaderId ).setStyle( 'display', 'none' );
254
255					// New image -> new domensions
256					if ( !this.dontResetSize )
257						resetSize( this );
258
259					if ( this.firstLoad )
260						CKEDITOR.tools.setTimeout( function() {
261						switchLockRatio( this, 'check' );
262					}, 0, this );
263
264					this.firstLoad = false;
265					this.dontResetSize = false;
266				};
267
268			var onImgLoadErrorEvent = function() {
269					// Error. Image is not loaded.
270					var original = this.originalElement;
271					original.removeListener( 'load', onImgLoadEvent );
272					original.removeListener( 'error', onImgLoadErrorEvent );
273					original.removeListener( 'abort', onImgLoadErrorEvent );
274
275					// Set Error image.
276					var noimage = CKEDITOR.getUrl( CKEDITOR.plugins.get( 'image' ).path + 'images/noimage.png' );
277
278					if ( this.preview )
279						this.preview.setAttribute( 'src', noimage );
280
281					// Hide loader
282					CKEDITOR.document.getById( imagePreviewLoaderId ).setStyle( 'display', 'none' );
283					switchLockRatio( this, false ); // Unlock.
284				};
285
286			var numbering = function( id ) {
287					return CKEDITOR.tools.getNextId() + '_' + id;
288				},
289				btnLockSizesId = numbering( 'btnLockSizes' ),
290				btnResetSizeId = numbering( 'btnResetSize' ),
291				imagePreviewLoaderId = numbering( 'ImagePreviewLoader' ),
292				previewLinkId = numbering( 'previewLink' ),
293				previewImageId = numbering( 'previewImage' );
294
295			return {
296				title: editor.lang.image[ dialogType == 'image' ? 'title' : 'titleButton' ],
297				minWidth: 420,
298				minHeight: 360,
299				onShow: function() {
300					this.imageElement = false;
301					this.linkElement = false;
302					// Default: create a new element.
303					this.imageEditMode = false;
304					this.linkEditMode = false;
305
306					this.lockRatio = true;
307					this.userlockRatio = 0;
308					this.dontResetSize = false;
309					this.firstLoad = true;
310					this.addLink = false;
311
312					var editor = this.getParentEditor(),
313						sel = editor.getSelection(),
314						element = sel && sel.getSelectedElement(),
315						link = element && editor.elementPath( element ).contains( 'a', 1 );
316                    var linkType;
317                    if(element && element['$']) {
318                         var className = element['$'].getAttribute('class');
319                         ckgeditImageReselectObj['align'] = className;
320                         linkType = element['$'].getAttribute('type');
321                         }
322
323				//Hide loader.
324					CKEDITOR.document.getById( imagePreviewLoaderId ).setStyle( 'display', 'none' );
325					// Create the preview before setup the dialog contents.
326					previewPreloader = new CKEDITOR.dom.element( 'img', editor.document );
327					this.preview = CKEDITOR.document.getById( previewImageId );
328
329					// Copy of the image
330					this.originalElement = editor.document.createElement( 'img' );
331					this.originalElement.setAttribute( 'alt', '' );
332					this.originalElement.setCustomData( 'isReady', 'false' );
333
334					if ( link ) {
335						this.linkElement = link;
336						this.linkEditMode = true;
337
338						// Look for Image element.
339						var linkChildren = link.getChildren();
340						if ( linkChildren.count() == 1 ) // 1 child.
341						{
342							var childTagName = linkChildren.getItem( 0 ).getName();
343							if ( childTagName == 'img' || childTagName == 'input' ) {
344								this.imageElement = linkChildren.getItem( 0 );
345								if ( this.imageElement.getName() == 'img' )
346									this.imageEditMode = 'img';
347								else if ( this.imageElement.getName() == 'input' )
348									this.imageEditMode = 'input';
349							}
350						}
351						// Fill out all fields.
352						if ( dialogType == 'image' )
353							this.setupContent( LINK, link );
354					}
355                    else {
356                        if(linkType) {
357                             ckgeditImageReselectObj['link'] = linkType;
358                         }
359                        else ckgeditImageReselectObj['link'] = 'nolink';
360                    }
361
362                   if(link) {
363                       if(link['$']['outerHTML'].match(/detail/)) {
364                             ckgeditImageReselectObj['link'] = 'detail';
365                        }
366                         else {
367                              ckgeditImageReselectObj['link'] = 'direct';
368                         }
369                    }
370					if ( element && element.getName() == 'img' && !element.data( 'cke-realelement' ) || element && element.getName() == 'input' && element.getAttribute( 'type' ) == 'image' ) {
371						this.imageEditMode = element.getName();
372						this.imageElement = element;
373					}
374
375					if ( this.imageEditMode ) {
376						// Use the original element as a buffer from  since we don't want
377						// temporary changes to be committed, e.g. if the dialog is canceled.
378						this.cleanImageElement = this.imageElement;
379						this.imageElement = this.cleanImageElement.clone( true, true );
380
381						// Fill out all fields.
382						this.setupContent( IMAGE, this.imageElement );
383					} else
384						this.imageElement = editor.document.createElement( 'img' );
385
386					// Refresh LockRatio button
387					switchLockRatio( this, true );
388
389					// Dont show preview if no URL given.
390					if ( !CKEDITOR.tools.trim( this.getValueOf( 'info', 'txtUrl' ) ) ) {
391						this.preview.removeAttribute( 'src' );
392						this.preview.setStyle( 'display', 'none' );
393					}
394				},
395				onOk: function() {
396					// Edit existing Image.
397					if ( this.imageEditMode ) {
398						var imgTagName = this.imageEditMode;
399						// Image dialog and Input element.
400						if ( dialogType == 'image' && imgTagName == 'input' && confirm( editor.lang.image.button2Img ) ) {
401							// Replace INPUT-> IMG
402							imgTagName = 'img';
403							this.imageElement = editor.document.createElement( 'img' );
404							this.imageElement.setAttribute( 'alt', '' );
405							editor.insertElement( this.imageElement );
406						}
407						// ImageButton dialog and Image element.
408						else if ( dialogType != 'image' && imgTagName == 'img' && confirm( editor.lang.image.img2Button ) ) {
409							// Replace IMG -> INPUT
410							imgTagName = 'input';
411							this.imageElement = editor.document.createElement( 'input' );
412							this.imageElement.setAttributes({
413								type: 'image',
414								alt: ''
415							});
416							editor.insertElement( this.imageElement );
417						} else {
418							// Restore the original element before all commits.
419							this.imageElement = this.cleanImageElement;
420							delete this.cleanImageElement;
421						}
422					} else // Create a new image.
423					{
424						// Image dialog -> create IMG element.
425						if ( dialogType == 'image' )
426							this.imageElement = editor.document.createElement( 'img' );
427						else {
428							this.imageElement = editor.document.createElement( 'input' );
429							this.imageElement.setAttribute( 'type', 'image' );
430						}
431						this.imageElement.setAttribute( 'alt', '' );
432					}
433
434
435                     var link_sel = document.getElementById(ckgeditLinkTypeId);
436                     var linktype = 'detail';
437                     if(link_sel.selectedIndex > 0) {
438                         var linktype =  link_sel.options[link_sel.selectedIndex].value;
439                     }
440                     this.imageElement.setAttribute( 'type', linktype );
441					// Create a new link.
442					if ( !this.linkEditMode )
443						this.linkElement = editor.document.createElement( 'a' );
444
445					// Set attributes.
446					this.commitContent( IMAGE, this.imageElement );
447
448                                         var align_sel = document.getElementById(ckgeditAlignInputId);
449                     if(align_sel.selectedIndex > 0) {
450                         var img_alignment =  align_sel.options[align_sel.selectedIndex].value;
451                         this.imageElement.setAttribute( 'class', img_alignment );
452                     }
453                     else this.imageElement.setAttribute( 'class', 'media' );
454
455					// Remove empty style attribute.
456					if ( !this.imageElement.getAttribute( 'style' ) )
457						this.imageElement.removeAttribute( 'style' );
458
459					// Insert a new Image.
460					if ( !this.imageEditMode ) {
461						if ( this.addLink ) {
462							//Insert a new Link.
463							if ( !this.linkEditMode ) {
464								editor.insertElement( this.linkElement );
465								this.linkElement.append( this.imageElement, false );
466							} else //Link already exists, image not.
467							editor.insertElement( this.imageElement );
468						} else
469							editor.insertElement( this.imageElement );
470					} else // Image already exists.
471					{
472						//Add a new link element.
473						if ( !this.linkEditMode && this.addLink ) {
474							editor.insertElement( this.linkElement );
475							this.imageElement.appendTo( this.linkElement );
476						}
477						//Remove Link, Image exists.
478						else if ( this.linkEditMode && !this.addLink ) {
479							editor.getSelection().selectElement( this.linkElement );
480							editor.insertElement( this.imageElement );
481						}
482					}
483				},
484				onLoad: function() {
485					if ( dialogType != 'image' )
486						this.hidePage( 'Link' ); //Hide Link tab.
487					var doc = this._.element.getDocument();
488
489					if ( this.getContentElement( 'info', 'ratioLock' ) ) {
490						this.addFocusable( doc.getById( btnResetSizeId ), 5 );
491						this.addFocusable( doc.getById( btnLockSizesId ), 5 );
492					}
493                    oDokuWiki_FCKEditorInstance.isLocalDwikiBrowser=false;
494                    oDokuWiki_FCKEditorInstance.isDwikiMediaFile = true;
495                    oDokuWiki_FCKEditorInstance.isDwikiImage = true;
496					this.commitContent = commitContent;
497				},
498				onHide: function() {
499					if ( this.preview )
500						this.commitContent( CLEANUP, this.preview );
501
502					if ( this.originalElement ) {
503						this.originalElement.removeListener( 'load', onImgLoadEvent );
504						this.originalElement.removeListener( 'error', onImgLoadErrorEvent );
505						this.originalElement.removeListener( 'abort', onImgLoadErrorEvent );
506						this.originalElement.remove();
507						this.originalElement = false; // Dialog is closed.
508					}
509
510					delete this.imageElement;
511				},
512				contents: [
513					{
514					id: 'info',
515					label: editor.lang.image.infoTab,
516					accessKey: 'I',
517					elements: [
518						{
519						type: 'vbox',
520						padding: 0,
521						children: [
522							{
523							type: 'hbox',
524							widths: [ '280px', '110px' ],
525							align: 'right',
526							children: [
527								{
528								id: 'txtUrl',
529								type: 'text',
530								label: editor.lang.common.url,
531								required: true,
532								onChange: function() {
533									var dialog = this.getDialog(),
534										newUrl = this.getValue();
535
536									//Update original image
537									if ( newUrl.length > 0 ) //Prevent from load before onShow
538									{
539										dialog = this.getDialog();
540										var original = dialog.originalElement;
541
542										dialog.preview.removeStyle( 'display' );
543
544										original.setCustomData( 'isReady', 'false' );
545										// Show loader
546										var loader = CKEDITOR.document.getById( imagePreviewLoaderId );
547										if ( loader )
548											loader.setStyle( 'display', '' );
549
550										original.on( 'load', onImgLoadEvent, dialog );
551										original.on( 'error', onImgLoadErrorEvent, dialog );
552										original.on( 'abort', onImgLoadErrorEvent, dialog );
553										original.setAttribute( 'src', newUrl );
554
555										// Query the preloader to figure out the url impacted by based href.
556										previewPreloader.setAttribute( 'src', newUrl );
557										dialog.preview.setAttribute( 'src', previewPreloader.$.src );
558										updatePreview( dialog );
559									}
560									// Dont show preview if no URL given.
561									else if ( dialog.preview ) {
562										dialog.preview.removeAttribute( 'src' );
563										dialog.preview.setStyle( 'display', 'none' );
564									}
565								},
566								setup: function( type, element ) {
567									if ( type == IMAGE ) {
568										var url = element.data( 'cke-saved-src' ) || element.getAttribute( 'src' );
569										var field = this;
570
571										this.getDialog().dontResetSize = true;
572
573										field.setValue( url ); // And call this.onChange()
574										// Manually set the initial value.(#4191)
575										field.setInitValue();
576									}
577								},
578								commit: function( type, element ) {
579									if ( type == IMAGE && ( this.getValue() || this.isChanged() ) ) {
580										element.data( 'cke-saved-src', this.getValue() );
581										element.setAttribute( 'src', this.getValue() );
582									} else if ( type == CLEANUP ) {
583										element.setAttribute( 'src', '' ); // If removeAttribute doesn't work.
584										element.removeAttribute( 'src' );
585									}
586								},
587								validate: CKEDITOR.dialog.validate.notEmpty( editor.lang.image.urlMissing )
588							},
589								{
590								type: 'button',
591								id: 'browse',
592								// v-align with the 'txtUrl' field.
593								// TODO: We need something better than a fixed size here.
594								style: 'display:inline-block;margin-top:10px;',
595								align: 'center',
596								label: editor.lang.common.browseServer,
597								hidden: true,
598								filebrowser: 'info:txtUrl'
599							}
600							]
601						}
602						]
603					},
604						{
605						id: 'txtAlt',
606						type: 'text',
607                        hidden: false,
608						label: editor.lang.image.alt,
609						accessKey: 'T',
610						'default': '',
611						onChange: function() {
612							updatePreview( this.getDialog() );
613						},
614						setup: function( type, element ) {
615							if ( type == IMAGE )
616								this.setValue( element.getAttribute( 'alt' ) );
617						},
618						commit: function( type, element ) {
619							if ( type == IMAGE ) {
620								if ( this.getValue() || this.isChanged() )
621									element.setAttribute( 'alt', this.getValue() );
622							} else if ( type == PREVIEW ) {
623								element.setAttribute( 'alt', this.getValue() );
624							} else if ( type == CLEANUP ) {
625								element.removeAttribute( 'alt' );
626							}
627						}
628					},
629						{
630						type: 'hbox',
631						children: [
632							{
633							id: 'basic',
634							type: 'vbox',
635							children: [
636								{
637								type: 'hbox',
638								widths: [ '50%', '50%' ],
639								children: [
640									{
641									type: 'vbox',
642									padding: 1,
643									children: [
644										{
645										type: 'text',
646										width: '40px',
647										id: 'txtWidth',
648										label: editor.lang.common.width,
649										onKeyUp: onSizeChange,
650										onChange: function() {
651											commitInternally.call( this, 'advanced:txtdlgGenStyle' );
652										},
653										validate: function() {
654											var aMatch = this.getValue().match( regexGetSizeOrEmpty ),
655												isValid = !!( aMatch && parseInt( aMatch[ 1 ], 10 ) !== 0 );
656											if ( !isValid )
657												alert( editor.lang.common.invalidWidth );
658											return isValid;
659										},
660										setup: setupDimension,
661										commit: function( type, element, internalCommit ) {
662											var value = this.getValue();
663											if ( type == IMAGE ) {
664												if ( value )
665													element.setStyle( 'width', CKEDITOR.tools.cssLength( value ) );
666												else
667													element.removeStyle( 'width' );
668
669												!internalCommit && element.removeAttribute( 'width' );
670											} else if ( type == PREVIEW ) {
671												var aMatch = value.match( regexGetSize );
672												if ( !aMatch ) {
673													var oImageOriginal = this.getDialog().originalElement;
674													if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' )
675														element.setStyle( 'width', oImageOriginal.$.width + 'px' );
676												} else
677													element.setStyle( 'width', CKEDITOR.tools.cssLength( value ) );
678											} else if ( type == CLEANUP ) {
679												element.removeAttribute( 'width' );
680												element.removeStyle( 'width' );
681											}
682										}
683									},
684										{
685										type: 'text',
686										id: 'txtHeight',
687										width: '40px',
688										label: editor.lang.common.height,
689										onKeyUp: onSizeChange,
690										onChange: function() {
691											commitInternally.call( this, 'advanced:txtdlgGenStyle' );
692										},
693										validate: function() {
694											var aMatch = this.getValue().match( regexGetSizeOrEmpty ),
695												isValid = !!( aMatch && parseInt( aMatch[ 1 ], 10 ) !== 0 );
696											if ( !isValid )
697												alert( editor.lang.common.invalidHeight );
698											return isValid;
699										},
700										setup: setupDimension,
701										commit: function( type, element, internalCommit ) {
702											var value = this.getValue();
703											if ( type == IMAGE ) {
704												if ( value )
705													element.setStyle( 'height', CKEDITOR.tools.cssLength( value ) );
706												else
707													element.removeStyle( 'height' );
708
709												!internalCommit && element.removeAttribute( 'height' );
710											} else if ( type == PREVIEW ) {
711												var aMatch = value.match( regexGetSize );
712												if ( !aMatch ) {
713													var oImageOriginal = this.getDialog().originalElement;
714													if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' )
715														element.setStyle( 'height', oImageOriginal.$.height + 'px' );
716												} else
717													element.setStyle( 'height', CKEDITOR.tools.cssLength( value ) );
718											} else if ( type == CLEANUP ) {
719												element.removeAttribute( 'height' );
720												element.removeStyle( 'height' );
721											}
722										}
723									}
724									]
725								},
726									{
727									id: 'ratioLock',
728									type: 'html',
729									style: 'margin-top:30px;width:40px;height:40px;',
730									onLoad: function() {
731										// Activate Reset button
732										var resetButton = CKEDITOR.document.getById( btnResetSizeId ),
733											ratioButton = CKEDITOR.document.getById( btnLockSizesId );
734										if ( resetButton ) {
735											resetButton.on( 'click', function( evt ) {
736												resetSize( this );
737												evt.data && evt.data.preventDefault();
738											}, this.getDialog() );
739											resetButton.on( 'mouseover', function() {
740												this.addClass( 'cke_btn_over' );
741											}, resetButton );
742											resetButton.on( 'mouseout', function() {
743												this.removeClass( 'cke_btn_over' );
744											}, resetButton );
745										}
746										// Activate (Un)LockRatio button
747										if ( ratioButton ) {
748											ratioButton.on( 'click', function( evt ) {
749												var locked = switchLockRatio( this ),
750													oImageOriginal = this.originalElement,
751													width = this.getValueOf( 'info', 'txtWidth' );
752
753												if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' && width ) {
754													var height = oImageOriginal.$.height / oImageOriginal.$.width * width;
755													if ( !isNaN( height ) ) {
756														this.setValueOf( 'info', 'txtHeight', Math.round( height ) );
757														updatePreview( this );
758													}
759												}
760												evt.data && evt.data.preventDefault();
761											}, this.getDialog() );
762											ratioButton.on( 'mouseover', function() {
763												this.addClass( 'cke_btn_over' );
764											}, ratioButton );
765											ratioButton.on( 'mouseout', function() {
766												this.removeClass( 'cke_btn_over' );
767											}, ratioButton );
768										}
769									},
770									html: '<div>' +
771										'<a href="javascript:void(0)" tabindex="-1" title="' + editor.lang.image.lockRatio +
772										'" class="cke_btn_locked" id="' + btnLockSizesId + '" role="checkbox"><span class="cke_icon"></span><span class="cke_label">' + editor.lang.image.lockRatio + '</span></a>' +
773										'<a href="javascript:void(0)" tabindex="-1" title="' + editor.lang.image.resetSize +
774										'" class="cke_btn_reset" id="' + btnResetSizeId + '" role="button"><span class="cke_label">' + editor.lang.image.resetSize + '</span></a>' +
775										'</div>'
776								}
777								]
778							},
779								{
780								type: 'vbox',
781								padding: 1,
782								children: [
783									{
784                                        id: 'cmbLinkType',
785                                        type: 'select',
786                                        label: editor.lang.common.linkType||"Link Type",
787                                        'default': 'detail',
788                                        items: [
789                                            [ editor.lang.common.linkDetail  || "Detail", 'detail'],
790                                            [ editor.lang.common.linkDirect ||"Direct", 'direct' ],
791                                            [ editor.lang.common.linkNoLink || "No Link" , 'nolink'],
792                                            [ editor.lang.common.linkOnly || "Link only" , 'linkonly'],
793                                        ],
794							    },
795                                {
796                                   type: "html",
797                                   html: "<p>&nbsp;</p>",
798                                },
799									{
800									type: 'text',
801									id: 'txtBorder',
802									width: '60px',
803                                    disabled: true,
804                                    hidden: true,
805									label: editor.lang.image.border,
806									'default': '',
807									onKeyUp: function() {
808										updatePreview( this.getDialog() );
809									},
810									onChange: function() {
811										commitInternally.call( this, 'advanced:txtdlgGenStyle' );
812									},
813									validate: CKEDITOR.dialog.validate.integer( editor.lang.image.validateBorder ),
814									setup: function( type, element ) {
815										if ( type == IMAGE ) {
816											var value,
817												borderStyle = element.getStyle( 'border-width' );
818											borderStyle = borderStyle && borderStyle.match( /^(\d+px)(?: \1 \1 \1)?$/ );
819											value = borderStyle && parseInt( borderStyle[ 1 ], 10 );
820											isNaN( parseInt( value, 10 ) ) && ( value = element.getAttribute( 'border' ) );
821											this.setValue( value );
822										}
823									},
824									commit: function( type, element, internalCommit ) {
825										var value = parseInt( this.getValue(), 10 );
826										if ( type == IMAGE || type == PREVIEW ) {
827											if ( !isNaN( value ) ) {
828												element.setStyle( 'border-width', CKEDITOR.tools.cssLength( value ) );
829												element.setStyle( 'border-style', 'solid' );
830											} else if ( !value && this.isChanged() )
831												element.removeStyle( 'border' );
832
833											if ( !internalCommit && type == IMAGE )
834												element.removeAttribute( 'border' );
835										} else if ( type == CLEANUP ) {
836											element.removeAttribute( 'border' );
837											element.removeStyle( 'border-width' );
838											element.removeStyle( 'border-style' );
839											element.removeStyle( 'border-color' );
840										}
841									}
842								},
843									{
844									type: 'text',
845									id: 'txtHSpace',
846									width: '60px',
847									label: editor.lang.image.hSpace,
848                                    disabled: true,
849                                    hidden: true,
850									'default': '',
851									onKeyUp: function() {
852										updatePreview( this.getDialog() );
853									},
854									onChange: function() {
855										commitInternally.call( this, 'advanced:txtdlgGenStyle' );
856									},
857									validate: CKEDITOR.dialog.validate.integer( editor.lang.image.validateHSpace ),
858									setup: function( type, element ) {
859										if ( type == IMAGE ) {
860											var value, marginLeftPx, marginRightPx,
861												marginLeftStyle = element.getStyle( 'margin-left' ),
862												marginRightStyle = element.getStyle( 'margin-right' );
863
864											marginLeftStyle = marginLeftStyle && marginLeftStyle.match( pxLengthRegex );
865											marginRightStyle = marginRightStyle && marginRightStyle.match( pxLengthRegex );
866											marginLeftPx = parseInt( marginLeftStyle, 10 );
867											marginRightPx = parseInt( marginRightStyle, 10 );
868
869											value = ( marginLeftPx == marginRightPx ) && marginLeftPx;
870											isNaN( parseInt( value, 10 ) ) && ( value = element.getAttribute( 'hspace' ) );
871
872											this.setValue( value );
873										}
874									},
875									commit: function( type, element, internalCommit ) {
876										var value = parseInt( this.getValue(), 10 );
877										if ( type == IMAGE || type == PREVIEW ) {
878											if ( !isNaN( value ) ) {
879												element.setStyle( 'margin-left', CKEDITOR.tools.cssLength( value ) );
880												element.setStyle( 'margin-right', CKEDITOR.tools.cssLength( value ) );
881											} else if ( !value && this.isChanged() ) {
882												element.removeStyle( 'margin-left' );
883												element.removeStyle( 'margin-right' );
884											}
885
886											if ( !internalCommit && type == IMAGE )
887												element.removeAttribute( 'hspace' );
888										} else if ( type == CLEANUP ) {
889											element.removeAttribute( 'hspace' );
890											element.removeStyle( 'margin-left' );
891											element.removeStyle( 'margin-right' );
892										}
893									}
894								},
895									{
896									type: 'text',
897									id: 'txtVSpace',
898									width: '60px',
899                                    hidden: true,
900									label: editor.lang.image.vSpace,
901									'default': '',
902									onKeyUp: function() {
903										updatePreview( this.getDialog() );
904									},
905									onChange: function() {
906										commitInternally.call( this, 'advanced:txtdlgGenStyle' );
907									},
908									validate: CKEDITOR.dialog.validate.integer( editor.lang.image.validateVSpace ),
909									setup: function( type, element ) {
910										if ( type == IMAGE ) {
911											var value, marginTopPx, marginBottomPx,
912												marginTopStyle = element.getStyle( 'margin-top' ),
913												marginBottomStyle = element.getStyle( 'margin-bottom' );
914
915											marginTopStyle = marginTopStyle && marginTopStyle.match( pxLengthRegex );
916											marginBottomStyle = marginBottomStyle && marginBottomStyle.match( pxLengthRegex );
917											marginTopPx = parseInt( marginTopStyle, 10 );
918											marginBottomPx = parseInt( marginBottomStyle, 10 );
919
920											value = ( marginTopPx == marginBottomPx ) && marginTopPx;
921											isNaN( parseInt( value, 10 ) ) && ( value = element.getAttribute( 'vspace' ) );
922											this.setValue( value );
923										}
924									},
925									commit: function( type, element, internalCommit ) {
926										var value = parseInt( this.getValue(), 10 );
927										if ( type == IMAGE || type == PREVIEW ) {
928											if ( !isNaN( value ) ) {
929												element.setStyle( 'margin-top', CKEDITOR.tools.cssLength( value ) );
930												element.setStyle( 'margin-bottom', CKEDITOR.tools.cssLength( value ) );
931											} else if ( !value && this.isChanged() ) {
932												element.removeStyle( 'margin-top' );
933												element.removeStyle( 'margin-bottom' );
934											}
935
936											if ( !internalCommit && type == IMAGE )
937												element.removeAttribute( 'vspace' );
938										} else if ( type == CLEANUP ) {
939											element.removeAttribute( 'vspace' );
940											element.removeStyle( 'margin-top' );
941											element.removeStyle( 'margin-bottom' );
942										}
943									}
944								},
945									{
946									id: 'cmbAlign',
947									type: 'select',
948									widths: [ '35%', '65%' ],
949									style: 'width:90px',
950									label: editor.lang.common.align,
951									'default': '',
952									items: [
953										[ editor.lang.common.notSet, '' ],
954										[ editor.lang.common.alignLeft, 'medialeft' ],
955										[ editor.lang.common.alignRight, 'mediaright' ],
956                                        [editor.lang.common.alignCenter , 'mediacenter'],
957                                        [ editor.lang.common.alignBaseLine||"Baseline" , 'baseline'],
958									],
959                                    									onChange: function() {
960										updatePreview( this.getDialog() );
961										commitInternally.call( this, 'advanced:txtdlgGenStyle' );
962									},
963									setup: function( type, element ) {
964									},
965									commit: function( type, element, internalCommit ) {
966										var value = this.getValue();
967										if ( type == IMAGE || type == PREVIEW ) {
968											if ( value ) {
969                                                value =  value.replace(/media/,"");
970                                                switch(value) {
971                                                    case 'center':
972                                                       element.removeStyle( 'float' );
973                                                       element.setAttribute( 'class', 'mediacenter');
974                                                       break;
975                                                    case 'baseline':
976                                                       value = 'left';
977                                                    default:
978                                                      element.setStyle( 'float', value );
979                                                   }
980
981                                                }
982											else
983												element.removeStyle( 'float' );
984
985											if ( !internalCommit && type == IMAGE ) {
986												value = ( element.getAttribute( 'align' ) || '' ).toLowerCase();
987												switch ( value ) {
988													// we should remove it only if it matches "left" or "right",
989													// otherwise leave it intact.
990													case 'left':
991													case 'right':
992														element.removeAttribute( 'align' );
993												}
994											}
995										} else if ( type == CLEANUP )
996											element.removeStyle( 'float' );
997
998									}
999								}
1000								]
1001							}
1002							]
1003						},
1004							{
1005							type: 'vbox',
1006							height: '250px',
1007							children: [
1008								{
1009								type: 'html',
1010								id: 'htmlPreview',
1011								style: 'width:95%;',
1012								html: '<style type = "text/css">.mediacenter { display: block; margin-left: auto; margin-right: auto;}</style><div>' + CKEDITOR.tools.htmlEncode( editor.lang.common.preview ) + '<br>' +
1013								     	'<div id="' + imagePreviewLoaderId + '" class="ImagePreviewLoader" style="display:none"><div class="loading">&nbsp;</div></div>' +
1014									'<div class="ImagePreviewBox"><table><tr><td>' +
1015										'<a href="javascript:void(0)" target="_blank" onclick="return false;" id="' + previewLinkId + '">' +
1016										'<img id="' + previewImageId + '" alt="" /></a>' +
1017										( editor.config.image_previewText || 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. ' +
1018											'Maecenas feugiat consequat diam. Maecenas metus. Vivamus diam purus, cursus a, commodo non, facilisis vitae, ' +
1019											'nulla. Aenean dictum lacinia tortor. Nunc iaculis, nibh non iaculis aliquam, orci felis euismod neque, sed ornare massa mauris sed velit. Nulla pretium mi et risus. Fusce mi pede, tempor id, cursus ac, ullamcorper nec, enim. Sed tortor. Curabitur molestie. Duis velit augue, condimentum at, ultrices a, luctus ut, orci. Donec pellentesque egestas eros. Integer cursus, augue in cursus faucibus, eros pede bibendum sem, in tempus tellus justo quis ligula. Etiam eget tortor. Vestibulum rutrum, est ut placerat elementum, lectus nisl aliquam velit, tempor aliquam eros nunc nonummy metus. In eros metus, gravida a, gravida sed, lobortis id, turpis. Ut ultrices, ipsum at venenatis fringilla, sem nulla lacinia tellus, eget aliquet turpis mauris non enim. Nam turpis. Suspendisse lacinia. Curabitur ac tortor ut ipsum egestas elementum. Nunc imperdiet gravida mauris.' ) +
1020									'</td></tr></table></div></div>'
1021								}
1022							]
1023						}
1024						]
1025					}
1026					]
1027				},
1028					{
1029					id: 'Link',
1030					label: editor.lang.image.linkTab,
1031					padding: 0,
1032                    hidden: true,
1033					elements: [
1034						{
1035						id: 'txtUrl',
1036						type: 'text',
1037                        disabled: true,
1038						label: editor.lang.common.url,
1039						style: 'width: 100%',
1040						'default': '',
1041						setup: function( type, element ) {
1042							if ( type == LINK ) {
1043								var href = element.data( 'cke-saved-href' );
1044								if ( !href )
1045									href = element.getAttribute( 'href' );
1046                                var matches = href.match(/media\s*=(.*)/);
1047                                if(matches) {
1048                                    href = ckgeditDwikiSaveDir + '/'+  matches[1].replace(':','/');
1049                                    element.setAttribute( 'href' );
1050                                }
1051								this.setValue( href );
1052							}
1053						},
1054						commit: function( type, element ) {
1055							if ( type == LINK ) {
1056								if ( this.getValue() || this.isChanged() ) {
1057									var url = decodeURI( this.getValue() );
1058									element.data( 'cke-saved-href', url );
1059									element.setAttribute( 'href', url );
1060
1061									if ( this.getValue() || !editor.config.image_removeLinkByEmptyURL )
1062										this.getDialog().addLink = true;
1063								}
1064							}
1065						}
1066					},
1067						{
1068						type: 'button',
1069						id: 'browse',
1070                        disabled: true,
1071						filebrowser: {
1072							action: 'Browse',
1073							target: 'Link:txtUrl',
1074							url: editor.config.filebrowserImageBrowseLinkUrl
1075						},
1076						style: 'float:right',
1077						hidden: true,
1078						label: editor.lang.common.browseServer
1079					},
1080						{
1081						id: 'cmbTarget',
1082						type: 'select',
1083                        disabled: true,
1084						label: editor.lang.common.target,
1085						'default': '',
1086						items: [
1087							[ editor.lang.common.notSet, '' ],
1088							[ editor.lang.common.targetNew, '_blank' ],
1089							[ editor.lang.common.targetTop, '_top' ],
1090							[ editor.lang.common.targetSelf, '_self' ],
1091							[ editor.lang.common.targetParent, '_parent' ]
1092							],
1093						setup: function( type, element ) {
1094							if ( type == LINK )
1095								this.setValue( element.getAttribute( 'target' ) || '' );
1096						},
1097						commit: function( type, element ) {
1098							if ( type == LINK ) {
1099								if ( this.getValue() || this.isChanged() )
1100									element.setAttribute( 'target', this.getValue() );
1101							}
1102						}
1103					}
1104					]
1105				},
1106					{
1107					id: 'Upload',
1108					hidden: true,
1109					filebrowser: 'uploadButton',
1110					label: editor.lang.image.upload,
1111					elements: [
1112						{
1113						type: 'file',
1114						id: 'upload',
1115						label: editor.lang.image.btnUpload,
1116						style: 'height:40px',
1117						size: 38
1118					},
1119						{
1120						type: 'fileButton',
1121						id: 'uploadButton',
1122						filebrowser: 'info:txtUrl',
1123						label: editor.lang.image.btnUpload,
1124						'for': [ 'Upload', 'upload' ]
1125					}
1126					]
1127				},
1128					{
1129					id: 'advanced',
1130                    hidden: true,
1131					label: editor.lang.common.advancedTab,
1132					elements: [
1133						{
1134						type: 'hbox',
1135						widths: [ '50%', '25%', '25%' ],
1136						children: [
1137							{
1138							type: 'text',
1139							id: 'linkId',
1140                            disabled: true,
1141							label: editor.lang.common.id,
1142							setup: function( type, element ) {
1143								if ( type == IMAGE )
1144									this.setValue( element.getAttribute( 'id' ) );
1145							},
1146							commit: function( type, element ) {
1147								if ( type == IMAGE ) {
1148									if ( this.getValue() || this.isChanged() )
1149										element.setAttribute( 'id', this.getValue() );
1150								}
1151							}
1152						},
1153							{
1154							id: 'cmbLangDir',
1155							type: 'select',
1156                            disabled: true,
1157							style: 'width : 100px;',
1158							label: editor.lang.common.langDir,
1159							'default': '',
1160							items: [
1161								[ editor.lang.common.notSet, '' ],
1162								[ editor.lang.common.langDirLtr, 'ltr' ],
1163								[ editor.lang.common.langDirRtl, 'rtl' ]
1164								],
1165							setup: function( type, element ) {
1166								if ( type == IMAGE )
1167									this.setValue( element.getAttribute( 'dir' ) );
1168							},
1169							commit: function( type, element ) {
1170								if ( type == IMAGE ) {
1171									if ( this.getValue() || this.isChanged() )
1172										element.setAttribute( 'dir', this.getValue() );
1173								}
1174							}
1175						},
1176							{
1177							type: 'text',
1178							id: 'txtLangCode',
1179                            disabled: true,
1180							label: editor.lang.common.langCode,
1181							'default': '',
1182							setup: function( type, element ) {
1183								if ( type == IMAGE )
1184									this.setValue( element.getAttribute( 'lang' ) );
1185							},
1186							commit: function( type, element ) {
1187								if ( type == IMAGE ) {
1188									if ( this.getValue() || this.isChanged() )
1189										element.setAttribute( 'lang', this.getValue() );
1190								}
1191							}
1192						}
1193						]
1194					},
1195						{
1196						type: 'text',
1197						id: 'txtGenLongDescr',
1198						label: editor.lang.common.longDescr,
1199                        disabled: true,
1200						setup: function( type, element ) {
1201							if ( type == IMAGE )
1202								this.setValue( element.getAttribute( 'longDesc' ) );
1203						},
1204						commit: function( type, element ) {
1205							if ( type == IMAGE ) {
1206								if ( this.getValue() || this.isChanged() )
1207									element.setAttribute( 'longDesc', this.getValue() );
1208							}
1209						}
1210					},
1211						{
1212						type: 'hbox',
1213						widths: [ '50%', '50%' ],
1214						children: [
1215							{
1216							type: 'text',
1217							id: 'txtGenClass',
1218                            disabled: true,
1219							label: editor.lang.common.cssClass,
1220							'default': '',
1221							setup: function( type, element ) {
1222								if ( type == IMAGE )
1223									this.setValue( element.getAttribute( 'class' ) );
1224							},
1225							commit: function( type, element ) {
1226								if ( type == IMAGE ) {
1227									if ( this.getValue() || this.isChanged() )
1228										element.setAttribute( 'class', this.getValue() );
1229								}
1230							}
1231						},
1232							{
1233							type: 'text',
1234							id: 'txtGenTitle',
1235                            disabled: true,
1236							label: editor.lang.common.advisoryTitle,
1237							'default': '',
1238							onChange: function() {
1239								updatePreview( this.getDialog() );
1240							},
1241							setup: function( type, element ) {
1242								if ( type == IMAGE )
1243									this.setValue( element.getAttribute( 'title' ) );
1244							},
1245							commit: function( type, element ) {
1246								if ( type == IMAGE ) {
1247									if ( this.getValue() || this.isChanged() )
1248										element.setAttribute( 'title', this.getValue() );
1249								} else if ( type == PREVIEW ) {
1250									element.setAttribute( 'title', this.getValue() );
1251								} else if ( type == CLEANUP ) {
1252									element.removeAttribute( 'title' );
1253								}
1254							}
1255						}
1256						]
1257					},
1258						{
1259						type: 'text',
1260						id: 'txtdlgGenStyle',
1261                        disabled: true,
1262						label: editor.lang.common.cssStyle,
1263						validate: CKEDITOR.dialog.validate.inlineStyle( editor.lang.common.invalidInlineStyle ),
1264						'default': '',
1265						setup: function( type, element ) {
1266							if ( type == IMAGE ) {
1267								var genStyle = element.getAttribute( 'style' );
1268								if ( !genStyle && element.$.style.cssText )
1269									genStyle = element.$.style.cssText;
1270								this.setValue( genStyle );
1271
1272								var height = element.$.style.height,
1273									width = element.$.style.width,
1274									aMatchH = ( height ? height : '' ).match( regexGetSize ),
1275									aMatchW = ( width ? width : '' ).match( regexGetSize );
1276
1277								this.attributesInStyle = {
1278									height: !!aMatchH,
1279									width: !!aMatchW
1280								};
1281							}
1282						},
1283						onChange: function() {
1284							commitInternally.call( this, [ 'info:cmbFloat', 'info:cmbAlign',
1285								'info:txtVSpace', 'info:txtHSpace',
1286								'info:txtBorder',
1287								'info:txtWidth', 'info:txtHeight' ] );
1288							updatePreview( this );
1289						},
1290						commit: function( type, element ) {
1291							if ( type == IMAGE && ( this.getValue() || this.isChanged() ) ) {
1292								element.setAttribute( 'style', this.getValue() );
1293							}
1294						}
1295					}
1296					]
1297				}
1298				]
1299			};
1300		};
1301
1302	CKEDITOR.dialog.add( 'image', function( editor ) {
1303		return imageDialog( editor, 'image' );
1304	});
1305
1306	CKEDITOR.dialog.add( 'imagebutton', function( editor ) {
1307		return imageDialog( editor, 'imagebutton' );
1308	});
1309})();
1310