(function() {
	CKEDITOR.dialog.add("twinimg", function(g) {
		var l = CKEDITOR.plugins.link,
			u1 = '',
			u2 = '',
			//a = this.getDialog(),
			h = function(a) {
				a && this.setValue(a[this.id] || "")
//				console.log(a[this.id]);
			},
			j = function(a) {
				a.advanced || (a.advanced = {});
				a.advanced[this.id] = this.getValue() || ""
			},
            rand = function()
            {
                var r = "";
                var ch = "abcdefghijklmnopqrstuvwxyz0123456789";
                for(var i=0; i<10; i++)r += ch.charAt(Math.floor(Math.random() * ch.length));
                return r;
            },
            gal_id = function(b){
//				gal = b.id
                return gal!="" ? gal : 'x'+rand();
            },
            e = false,
            imageExists = function(url){
                icon = CKEDITOR.getUrl(CKEDITOR.plugins.get("twinimg").path + "images/loading.gif");
                document.getElementById('cke_twinimg_image_preview').style.backgroundSize = "auto auto";
                document.getElementById('cke_twinimg_image_preview').style.backgroundImage = "url('"+icon+"')";
                var img = new Image();
                img.onload = function(){
                    e=true;
                    document.getElementById('cke_twinimg_image_preview').style.backgroundSize = "contain";
                    document.getElementById('cke_twinimg_image_preview').style.backgroundImage = "url('"+url+"')";
                };
                img.onerror = function(){e=false;};
                img.src = url;
            },
            imageExists2 = function(url){
                icon = CKEDITOR.getUrl(CKEDITOR.plugins.get("twinimg").path + "images/loading.gif");
                document.getElementById('cke_twinimg_image_preview2').style.backgroundSize = "auto auto";
                document.getElementById('cke_twinimg_image_preview2').style.backgroundImage = "url('"+icon+"')";
                var img = new Image();
                img.onload = function(){
                    e=true;
                    document.getElementById('cke_twinimg_image_preview2').style.backgroundSize = "contain";
                    document.getElementById('cke_twinimg_image_preview2').style.backgroundImage = "url('"+url+"')";
                };
                img.onerror = function(){e=false;};
                img.src = url;
            },
			c = g.lang.common,
			b = g.lang.link,
            d;
		return {
			title: 'TwinImg',
			minWidth: 350,
			minHeight: 230,
			contents: [{
				id: "info",
				label: b.info,
				title: b.info,
				elements: [{
					type: "vbox",
					id: "urlOptions",
					children: [{
						type: "hbox",
						widths: ["25%", "75%"],
						children: [{
							type: "text",
							id: "url",
							label: g.lang.twinimg.url,
							required: !0,
							onLoad: function() {
								this.allowOnChange = !0
							},
							onKeyUp: function() {
								this.allowOnChange = !1;
								var b = this.getValue(),
									k = /^((javascript:)|[#\/\.\?])/i;
                                k.test(b);
                                document.getElementById('cke_twinimg_image_preview').style.backgroundImage = "url('"+b+"')";
                                imageExists(b);
                                this.allowOnChange = !0
							},
							onChange: function() {
								if (this.allowOnChange) this.onKeyUp()
							},
							validate: function() {
                                var a = this.getDialog();
                                return !e ? (alert(c.invalidValue), !1) : !g.config.linkJavaScriptLinksAllowed && /javascript\:/.test(this.getValue()) ? (alert(c.invalidValue), !1) : this.getDialog().fakeObj ? !0 : CKEDITOR.dialog.validate.notEmpty(b.noUrl).apply(this);
                            },
							setup: function(a) {
//								console.log(a);
								this.allowOnChange = !1;
								a.url1 && this.setValue(a.url1);
								imageExists(a.url1);
								this.allowOnChange = !0
							},
							commit: function(a) {
								this.onChange();
                                a.type = "url";
                                a.url || (a.url = {});
                                a.url.protocol = "";
                                a.url.url = this.getValue();
								this.allowOnChange = !1
							}
						}],
						setup: function() {
							this.getDialog().getContentElement("info", "linkType") || this.getElement().show()
						}
					},
					{
						type: "button",
						id: "browse",
						hidden: "true",
//						filebrowser: "info:url", // amitel fixed
                                            style : 'display:inline-block;margin-top:0px;',
                                            filebrowser :
                                            {
                                                action : 'Browse',
                                                target: 'info:url',
                                                url: g.config.filebrowserImageBrowseUrl || g.config.filebrowserBrowseUrl
                                            },					 
						label: c.browseServer,
					}]
				},
    			{
                    id: "prev",
                    type: "html",
                    html : g.lang.twinimg.preview+'<div id="cke_twinimg_image_preview" class="ImagePreview" style="border:2px solid #000; height:100px; text-align:center; background-size:contain; background-position:center center; background-repeat:no-repeat;"></div>'
                },
				{
					type: "vbox",
					id: "urlOptions2",
					children: [{
						type: "hbox",
						widths: ["25%", "75%"],
						children: [{
							type: "text",
							id: "url2",
							label: g.lang.twinimg.url,
							required: !0,
							onLoad: function() {
								this.allowOnChange = !0
							},
							onKeyUp: function() {
								this.allowOnChange = !1;
								var b = this.getValue(),
									k = /^((javascript:)|[#\/\.\?])/i;
                                k.test(b);
                                document.getElementById('cke_twinimg_image_preview2').style.backgroundImage = "url('"+b+"')";
                                imageExists2(b);
                                this.allowOnChange = !0
							},
							onChange: function() {
								if (this.allowOnChange) this.onKeyUp()
							},
							validate: function() {
                                var a2 = this.getDialog();
                                return !e ? (alert(c.invalidValue), !1) : !g.config.linkJavaScriptLinksAllowed && /javascript\:/.test(this.getValue()) ? (alert(c.invalidValue), !1) : this.getDialog().fakeObj ? !0 : CKEDITOR.dialog.validate.notEmpty(b.noUrl).apply(this);
                            },
							setup: function(a) {
								this.allowOnChange = !1;
								a.url2 && this.setValue(a.url2);
								imageExists2(a.url2);
								this.allowOnChange = !0
							},
							commit: function(a) {
								this.onChange();
                                a.type = "url";
                                a.url || (a.url = {});
                                a.url.protocol = "";
                                a.url.url2 = this.getValue();
								this.allowOnChange = !1
							}
						}],
						setup: function() {
							this.getDialog().getContentElement("info", "linkType") || this.getElement().show()
						}
					},
					{
						type: "button",
						id: "browse",
						hidden: "true",
//						filebrowser: "info:url", // amitel fixed
                                            style : 'display:inline-block;margin-top:0px;',
                                            filebrowser :
                                            {
                                                action : 'Browse',
                                                target: 'info:url2',
                                                url: g.config.filebrowserImageBrowseUrl || g.config.filebrowserBrowseUrl
                                            },
						label: c.browseServer,
					}]
				},
    			{
                    id: "prev2",
                    type: "html",
                    html : g.lang.twinimg.preview+'<div id="cke_twinimg_image_preview2" class="ImagePreview" style="border:2px solid #000; height:100px; text-align:center; background-size:contain; background-position:center center; background-repeat:no-repeat;"></div>'
                },
                {
					type: "text",
					label: g.lang.twinimg.gallery,
					"default": "",
					id: "advRel",
					setup: h,
					commit: j
                },
                {
					type: "text",
					label: g.lang.twinimg.gallery2,
					"default": "",
					id: "advRel2",
					setup: h,
					commit: j
                },
                {
					type: "text",
					label: g.lang.twinimg.title,
					"a[title]": "",
					id: "advTitle",
					setup: h,
					commit: j
                }]
			}],
			onShow: function(data) {
				console.log('onShow');
                var selection = g.getSelection(),
        		    ranges = selection.getRanges();
				el = ranges[0].getTouchedStartNode();
                document.getElementById('cke_twinimg_image_preview').style.backgroundSize = "auto auto";
                document.getElementById('cke_twinimg_image_preview').style.backgroundSize = "contain";

			//    document.getElementById('cke_twinimg_image_preview').style.backgroundImage = "url('"+CKEDITOR.getUrl(CKEDITOR.plugins.get("twinimg").path + "images/noimage.png")+"')";
				id = $(el).attr('id');
				id = (id != undefined) ? id : 'x'+rand();
				console.log(id);
                var a = {
					id: id,
					element: el,
					url1: el.getAttribute('rel-url1'),
					url2: el.getAttribute('rel-url2'),
					advRel: el.getAttribute('rel-label1'),
					advRel2: el.getAttribute('rel-label2'),
					advTitle: el.getAttribute('rel-title')
					};
//				a = l.parseLinkAttributes(this, el);
				console.log(a);
//				this._.selectedElement = c;
//console.log(a);
//                p = '';//(typeof a.url['protocol'] !== 'undefined') ? a.url.protocol : "";
				//console.log(data);
               // document.getElementById('cke_twinimg_image_preview').style.backgroundImage = "url('"+p+a.url.url+"')";
				//a.url.url = p+a.url.url;
//                e = true;
//                gal = c.getAttribute('data-twinimg-saved');
				gal=id;
                this.setupContent(a)
			},
			onOk: function() {
				console.log('ok');
				console.log(this.a);
				var a = {};
				this.commitContent(a);


				if (this._.selectedElement) {
					var e = this._.selectedElement,
						d = e.data("cke-saved-href"),
						f = e.getHtml();
					e.setAttributes(c.set);
					e.removeAttributes(c.removed);
					if (d == f) e.setHtml(c.set["data-cke-saved-href"]), b.selectElement(e);
					delete this._.selectedElement
//				} else b = b.getRanges()[0], b.collapsed && (a = new CKEDITOR.dom.text(c.set["data-cke-saved-href"], g.document), b.insertNode(a), b.selectNodeContents(a)), c = new CKEDITOR.style({
//					element: "a",
//					attributes: c.set
//				}), c.type = CKEDITOR.STYLE_INLINE, c.applyToRange(b, g), b.select()
					} else {
/*
                               b = b.getRanges()[0];
                               if (b.collapsed) {
                                       a = new CKEDITOR.dom.element('img', g.document);
                                       a.setAttribute('src', c.set["data-cke-saved-href"]);
                                       b.insertNode(a);
                                       b.selectNodeContents(a);
                               }
                               c.set['data-cke-saved-href'] =  c.set['data-cke-saved-href'].replace( /\/100|\/50/g,'' );

                               c = new CKEDITOR.style({
                                       element: "a",
                                       attributes: c.set
                               });
							   //c.set['data-cke-saved-href'] = 'ooo';
                               c.type = CKEDITOR.STYLE_INLINE;
							  // console.log(c);
                               c.applyToRange(b, g);
                               b.select();
*/
							id = gal_id(a);
							$.each($("[rel-id='"+id+"']"),
								function(e){
									console.log(el);
									delete el;
								}
							);
							delete $("#"+id);
							delete $("#twinimg");
							var imgdiv = new CKEDITOR.dom.element( 'div' );
							//class="juxtapose" data-animate="true" data-showcredits="true" data-showlabels="true" data-startingposition="35%"
								imgdiv.setAttribute('class', 'juxtapose');
								imgdiv.setAttribute('id', id );
						//		imgdiv.setAttribute('style', "width:100%;min-height:200px;background-image: url('"+a.url.url+"');background-size:50%;background-position:50%;background-repeat: no-repeat;" );
								imgdiv.setAttribute('data-animate','true');
								imgdiv.setAttribute('data-showcredits','false');

							var img1 = new CKEDITOR.dom.element( 'img' );
								img1.setAttribute('data-label', a.advanced.advRel || "" );
							//	img1.setAttribute('data-credit', a.advanced.advTitle || "" );
								img1.setAttribute('src', a.url.url );
							var img2 = new CKEDITOR.dom.element( 'img' );
								img2.setAttribute('data-label', a.advanced.advRel2 || "" );
							//	img2.setAttribute('data-credit', a.advanced.advTitle || "" );
								img2.setAttribute('src', a.url.url2 );
							var script = new CKEDITOR.dom.element( 'script' );
								script.setAttribute('src', 'https://lib.amic.ru/js/juxtapose/juxtapose.min.js' );
								script.setAttribute('rel-id', 'twinimg' );
								script.setAttribute('defer', 'true' );


							var pt = new CKEDITOR.dom.element( 'p' );
								pt.setAttribute('class', 'style3');
								pt.appendText(a.advanced.advTitle || "");
								g.insertElement( imgdiv );
								imgdiv.append( img1 );
								imgdiv.append( img2 );
								g.insertElement( pt );
//								g.insertElement( script );
//								g.insertElement( script2 );
                       }
			}
		}
	})
})();
