(function() {

	CKEDITOR.plugins.add('imagevariations', {

        requires: 'richcombo',
        init : function(editor) {
            
        	var scope = {
        		variations: []
        	};
        	
        	fillVariations();
            
            var config = editor.config;
                config.disableObjectResizing = true;

            var lang = editor.lang.format;

            var variationExp = /(\-)([^\-]*)(\.)/i; // -<variation>.
            
            function fillVariations() {
                var variations = editor.element.getAttribute('cf-variations');
                if (!variations) {
                    return false;
                }
            	variations = variations.replace(/'/g, '"');
            	variations = JSON.parse(variations);
            	for (var i in variations) {
            	    scope.variations.push({
            	        code: i,
            	        name: variations[i]
            	    });
            	}
            	return true;
            }

            function buildList() {
                for (var i = 0; i < scope.variations.length; i++){
                    this.add(scope.variations[i].code, scope.variations[i].name, scope.variations[i].name);
                }
                this._.committed = 0;
                this.commit();
                this.changeSelected();
            }

            function getSelectedImage(editor) {

                var el = editor.getSelection().getSelectedElement();
                if (el && el.is('img')) {
                    return el;
                }
                return null;

            }

            function getVariation(el) {

                var src = el.getAttribute('src');
                var r = variationExp.exec(src);
                if (r) {
                    return r[2];
                }
                return null;

            }

            function setVariation(el, variation) {

                var src = el.getAttribute('src');
                    src = src.replace(variationExp, '$1' + variation + '$3');
                el.setAttribute('src', src);
                return src;

            }
            
            editor.ui.addRichCombo('ImageVariations', {

                label: 'Image variation',
                title: 'Image variation',
                voiceLabel: 'Image variation',
                className : 'cke_image_variations',
                multiSelect : false,

                panel: {
                    css: [CKEDITOR.skin.getPath('editor')].concat(config.contentsCss)
                },

                init: function() {
                    
                    this.startGroup('Image variation');

                    //this.disable();

                    var rebuildList = CKEDITOR.tools.bind(buildList, this);

                    if (scope.variations.length) {
                        rebuildList();
                    } else {
                    	/*
                        scope.$watch('variations', function() {
                            if (scope.variations.length) {
                                rebuildList();
                            }
                        });
						*/
						/*
						$.get('/api/variations/', function(response) {
							for (var i in response) {
								scope.variations.push(response[i]);
							}
							rebuildList();
						});
						*/
						var timer = setInterval(function() {
						    if (fillVariations()) {
						        clearInterval(timer);
						        rebuildList();
						    }
						}, 100);
                    }
                },

                onRender: function() {

                    editor.on('selectionChange', function(e) {

                        this.changeSelected();

                    }, this);

                },

                changeSelected: function() {

                    if (!scope.variations.length) {
                        return;
                    }

                    var el = getSelectedImage(editor);
                    if (el) {
                        var variation = getVariation(el);
                        if (variation) {
                            for (var i = 0; i < scope.variations.length; i++) {
                                if (variation == scope.variations[i].code) {
                                    this.setValue(scope.variations[i].code, scope.variations[i].name);
                                    //this.setState(CKEDITOR.TRISTATE_OFF);
                                    this.enable();
                                    return;
                                }
                            }
                        }
                    }

                    this.setValue('', this.label);
                    //this.setState(CKEDITOR.TRISTATE_DISABLED);
                    //this.disable();

                },

                onClick : function(variation) {

                    editor.focus();
                    var el = getSelectedImage(editor);
                    var src = $(el.$.outerHTML).attr('src');

                    editor.fire( 'saveSnapshot' );
                    var data = $('<div>' + editor.getData() + '</div>');
                        data.find('img[src="' + src + '"]')
                            .attr('src', setVariation(el, variation))
                            .attr('data-variation', variation);
                    // console.log('----------------------------------');
                    // console.log(data.html());
                    editor.setData(data.html());
                    if (data.length) {
                        editor.fire( 'saveSnapshot' );
                    }
                    this.changeSelected();
                    if (0 && el) {

                        editor.fire( 'saveSnapshot' );
                        setVariation(el, variation);
                        editor.fire( 'saveSnapshot' );
                        this.changeSelected();
                        
                    }

                }
            });
        }

    });

})();