var ds_Plugin_Wizard = ds_Base.extend({
					   
    options: {
		
        url	        : '',
        entity_id	: 0,
        project_id	: 0,
        title		: '',
        width		: 400,
        height		: 400,
        zindex		: 1,
        closable	: true,
        instanceId  : 0,
        instanceKey : '',
        message		: ''
    },
	
    isClosed: 0,
    currentStep: 0,
    amountSteps: 0,
    form: null,
    fnComplete: null,
    formSteps: [],
    multipleForms: false,
    closeEventChain: false,
	
    initialize: function(options) {
        this.setOptions(options);
        if ($defined(this.options.fnComplete)) {
            this.fnComplete = this.options.fnComplete;
        }
        this.generateWizard();
        this.closeEventChain = new Chain();
    },
	
    generateWizard: function() {
		
        this.wizard = new Element('div').addClass('ds_Wizard').setProperty('id', 'wizard_instance_' + this.options.instanceId);
		
        this.wizardHeader = new Element('div').addClass('ds_WizardHeader').inject(this.wizard);
			
        this.wizardHeaderTitle = new Element('h3').inject(this.wizardHeader);
			
        this.wizardContent = new Element('div').addClass('ds_WizardContent').inject(this.wizard);
			
        this.wizardFooter = new Element('div').addClass('ds_WizardFooter').inject(this.wizard);
		
        this.wizardButtons = new Element('div').addClass('ds_WizardButtons').inject(this.wizardFooter);
				
        if(this.options.closable) {
			
            this.wizardHeaderClose = new Element('div').addClass('close').setProperties({
                'title': 'Sluit het scherm'
            }).addEvents({
                'click': this.closeWizard.bindWithEvent(this)
            }).inject(this.wizardHeader);
        }
		
        this.wizard.inject(document.body);
		
        $(document).addEvent('keydown', this.hotKeyHandler.bind(this));
		
    },
	
    hotKeyHandler: function(evt) {
        evt = new Event(evt);
        switch(evt.key) {
            case 'esc':
                this.closeWizard();
                break;
        }
	    
    },
	
    setDimensions: function() {
		
        if (this.options.height !== 'auto') {
            this.wizard.setStyles({
                'width': this.options.width,
                'height': this.options.height,
                'z-index': this.options.zindex
            });
            this.wizardContent.setStyles({
                'height': this.options.height - 100
            }); 
        } else {
            this.wizard.setStyles({
                'width': this.options.width,
                'height': 'auto',
                'z-index': this.options.zindex
            });
        }
		
        this.wizard.makeDraggable({
            handle: this.wizardHeader,
            snap: 0,
            limit: {
                x: [0, window.getWidth() - this.options.width],
                y: [0, window.getHeight() - this.options.height]
            }
        });
    },
	
    setPosition: function() {
        if (this.options.height !== 'auto') {
            this.wizard.setStyles({
                'top': (window.getHeight() - this.options.height) / 2 + window.getScrollTop(),
                'left': (window.getWidth() - this.options.width) / 2 + window.getScrollLeft()
            });
        } else {
            this.wizard.setStyles({
                'top': (window.getHeight() - 400) / 2 + window.getScrollTop(),
                'left': (window.getWidth() - this.options.width) / 2 + window.getScrollLeft()
            });
        }
    },
	
    setTitle: function() {
        this.wizardHeaderTitle.setHTML(this.options.title);
    },
	
    alterTitle: function(title) {
        this.wizardHeaderTitle.setHTML(title);
    },
	
    setIframe: function() {
		
        var url = this.options.url;
        this.elmIframe = new Element('iframe').setProperties({
            src:url,
            width:'740px',
            height:'540px',
            frameborder: 0
        }).inject(this.wizardContent);
		
        this.setOptions({
            width: 642,
            height: 550
        });
    },
	
    getForm: function () {
        return $(this.wizardContent).getElement('form');
    },
	
    showForm: function(formName, entityId, parentId) {
		
        this.oOverlay = new ds_Plugin_Overlay({
            zindex:(this.options.zindex - 1)
        });
		
        this.setDimensions();
        this.setPosition();
        this.setTitle();
		
        var url = '/form/get/' + formName;
		
        if(this.options.parentId > 0) {
            url = url + '/iItemId/' + entityId + '/iParentId/' + parentId;
        }
        else {
            url = url + '/iItemId/' + entityId;
        }
		
        var onGetForm = this.updateContent.bind(this);
		
        oAjax = new ds_Plugin_Ajax();
		
        oAjax.getAjax(url, onGetForm, true);
		
        this.wizard.setStyle('display', 'block');
    },
	
    updateContent: function(sResponse) {
        if (this.wizardContent.hasClass('wizardLoading')) {
            this.wizardContent.removeClass('wizardLoading');
        }
        this.wizardContent.setHTML(sResponse);
        /* dit is gecomment vanwege content beheer */
        //this.initCalendarButtons(this.wizardContent);
		
        if (this.wizardContent.getElement('fieldset')) {
            this.wizardContent.getElement('fieldset').setStyle('display','block');
        }
		
        if ($defined(this.options.fnComplete)) {
            this.options.fnComplete();
        }
    },
	
    closeWizard: function() {
		
        this.wizard.setStyle('display', 'none');
        this.oOverlay.closeOverlay();
        this.setOptions({
            //title		: 'Wizard',
            //width		: 400,
            //height		: 400,
            closable	: true
        });
		
        this.wizardContent.getElements('.simpleTiny textarea').each(function(elm) {
            var elmId = elm.getProperty('id');
            //console.log(elmId);
            tinyMCE.execCommand('mceRemoveControl', false, elmId );
        });
        this.wizardContent.getElements('.advancedTiny textarea').each(function(elm) {
            var elmId = elm.getProperty('id');
            //console.log(elmId);
            tinyMCE.execCommand('mceRemoveControl', false, elmId);
        });
        this.setDimensions();
        this.setPosition();
        this.setTitle();
        this.clearContent();
        this.closeEventChain.callChain();
    },
	
    chainFnToClose: function(fn) {
        this.closeEventChain.chain(fn);
    },
	
    closeAndReturnOne: function() {
        this.closeWizard();
        history.go(-1);
    },
	
    clearContent: function() {
        this.wizardContent.empty();
        this.wizardButtons.empty();
		
    },
	
    closeForm: function() {
        this.closeWizard();
    },
	
    saveForm: function() {
		
        oForm = new ds_Plugin_Form({
            form:$(this.options.form),
            onValid: function() {
                oProject.getWizard().closeForm();
            }
        });
        oForm.processForm();
    },
	
    show: function() {
        this.oOverlay = new ds_Plugin_Overlay({
            zindex:(this.options.zindex - 1)
        });
        this.setDimensions();
        this.setPosition();
        this.setTitle();
        this.wizard.setStyle('display', 'block');
    },
	
    hide: function() {
        this.closeWizard();
    },
	
    resize: function() {
        this.setDimensions();
        this.setPosition();
    },
	
    setContent: function(obj) {
        this.wizardContent.adopt(obj);
    },
	
    getContent: function(url) {
        this.wizardContent.addClass('wizardLoading');
        oAjax = new ds_Plugin_Ajax();
        oAjax.getAjax(url, this.updateContent.bind(this), true);
    },
	
    setStatus: function(status) {
		
        this.wizardStatusText.empty();
        var statIcon = new Element('span').addClass('icon').addClass(status.icon).inject(this.wizardStatusText);
        var statText = new Element('span').addClass('value').setText(status.text).inject(this.wizardStatusText);
		
    },
	
    addButton: function(button) {
		
		
        if ($type(button) == 'object') {
            var numButtons = $(this.wizardButtons).getElements('.button').length + 1;
            var buttonWidth = numButtons * 120;
            if (this.options.width < buttonWidth) {
                this.options.width = buttonWidth;
                this.resize();
            }
            button.container = this.wizardButtons;
            var buttonLink = this.getButton(button);
        } else {
            alert('Er is een fout opgetreden bij het opmaken van een button.');
        }
    },
	
    removeButtons: function() {
        this.wizardButtons.empty();
    },
	
    getInstanceId: function() {
        return this.wizard.getProperty('id');
    },
	
    showConfirm: function() {
        if (this.options.message !== '') {
			
            this.confirmMessage = new Element('div').setHTML(this.options.message).inject(this.wizardContent);
            this.show();
        } else {
            return false;
        }
    },
	
    showImage: function(fileId) {
        oImage = new Asset.image('/image/get/iImageId/' + fileId, {});
        oImage.inject(this.wizardContent);
        this.show();
    },
	
    setWizardFromFieldsets: function() {
        //if (!this.multipleForms) {
        var fieldsets = this.wizardContent.getElements('fieldset');
        this.amountSteps = fieldsets.length;
							
        currentStep = this.getCurrentStep();
        if (this.amountSteps > 1) {
            var i = 0;
            $each(fieldsets, function(el) {
                var sStyle = (currentStep === i) ? 'block' : 'none';
                el.setStyle('display', sStyle);
                i++;
            });
        }
        //}
        this.setWizardTitleFromLegend();
        this.addFormstepButtons();
    },
	
	
    // Om een of andere reden werkt setText() niet goed op this.wizardTitle
    // Daarom eerst element verwijderen en opnieuw aanmaken
    setWizardTitleFromLegend: function() {
        var fieldsets = this.wizardContent.getElements('fieldset'), i = 0;
        $each(fieldsets, function(fieldset) {
            if (i === this.getCurrentStep()){
                this.wizard.getElement('.ds_WizardHeader h3').remove();
                if ($defined(fieldset.getElement('legend'))) {
                    var wizardTitle = new Element('h3').setText(fieldset.getElement('legend').getText()).injectInside(this.wizard.getElement('.ds_WizardHeader'));
                }
            }
            i++;
        }, this);
    },
	
    addFormstepButtons: function() {
        this.removeButtons();
        this.addButtonNext();
        this.addButtonPrevious();
        this.addButtonCancel();
    },
	
    getCurrentStep: function() {
        return this.currentStep;
    },
	
    setCurrentStep: function(currentStep) {
        this.currentStep = currentStep;
    },
	
    addButtonPrevious: function() {
        if(this.getCurrentStep() !== 0) {
            this.addButton({
                icon:'previous',
                text:'Vorige',
                event:this.previousStep.bind(this)
            });
        }
    },
	
    addButtonCancel: function() {
        this.addButton({
            icon:'cancel',
            text:'Annuleren',
            event:this.closeWizard.bind(this)
        });
    },
	
    addButtonNext: function() {
		
        if(this.getCurrentStep() !== this.amountSteps-1) {
            this.addButton({
                icon:'next',
                text:'Volgende',
                event:this.nextStep.bind(this)
            });
        } else {
            this.addButton({
                icon:'submit',
                text:'Opslaan',
                event:this.submitForm.bind(this)
            });
        }
    },
	
    submitForm: function() {
        this.form = new ds_Plugin_Form({
            form:this.wizardContent.getElement('form'),
            setUrlFormatter: false,
            wizardInstanceKey: this.options.instanceKey,
            onValid: this.closeWizard.bind(this)
        });
        this.form.processForm();
    },
	
    previousStep: function() {
        this.currentStep--;
        if (!this.multipleForms) {
            this.setWizardFromFieldsets();
        } else {
            this.setActiveForm(this.getCurrentStep());
        }
    },

    nextStep: function() {
        this.currentStep++;
        if (!this.multipleForms) {
            this.setWizardFromFieldsets();
        }
    },
	
    setActiveForm: function(step){
        this.setCurrentStep(step);
        this.getContent(this.formSteps[step]);
    },
	
    setActiveFieldset: function(step) {
        this.currentStep = step;
        this.setWizardFromFieldsets();
    },
	
    setFormSteps: function (formSteps) {
        this.multipleForms = true;
        this.formSteps = formSteps;
    },
	
    addFormStep: function (options) { //{url, step, bindTo, fn, event, elm}
        this.multipleForms = true;
        this.formSteps[options.step] = options.url;
        this.amountSteps++;
        this.setCurrentStep(options.step);
        if($defined(options.event) && $defined(options.bindTo) && $defined(options.elm) && $defined(options.fn)) {
            options.elm.addOptionsEvent(options.event, options.fn, options.bindTo);
        }
    },
	
    getInfobox: function(options) {
        if (options.content !== '') {
            this.confirmMessage = new Element('p').setHTML(this.options.message).inject(this.wizardContent);
            this.show();
        } else {
            return false;
        }
    }
});

ds_Plugin_Wizard.implement(new Options);
