/**
* Fx.ProgressBar
* @version		1.1
* @license		MIT License
* @author		Harald Kirschner <mail [at] digitarald [dot] de>
* @copyright	Authors
*/

Fx.ProgressBar = new Class({

    Extends: Fx,

    options: {
        text: null,
        url: null,
        transition: Fx.Transitions.Circ.easeOut,
        fit: true,
        link: 'cancel'
    },

    initialize: function (element, options) {
        this.element = $(element);
        this.parent(options);

        var url = this.options.url;
        if (url) {
            this.element.setStyles({
                'background-image': 'url(' + url + ')',
                'background-repeat': 'no-repeat'
            });
        }

        if (this.options.fit) {
            url = url || this.element.getStyle('background-image').replace(/^url\(["']?|["']?\)$/g, '');
            if (url) {
                var fill = new Image();
                fill.onload = function () {
                    this.fill = fill.width;
                    fill = fill.onload = null;
                    this.set(this.now || 0);
                } .bind(this);
                fill.src = url;
                if (!this.fill && fill.width) fill.onload();
            }
        } else {
            this.set(0);
        }
    },

    start: function (to, total) {
        return this.parent(this.now, (arguments.length == 1) ? to.limit(0, 100) : to / total * 100);
    },

    set: function (to) {
        this.now = to;
        var css = (this.fill)
			? (((this.fill / -2) + (to / 100) * (this.element.width || 1) || 0).round() + 'px')
			: ((100 - to) + '%');

        this.element.setStyle('backgroundPosition', css + ' 0px').title = Math.round(to) + '%';

        var text = $(this.options.text);
        if (text) text.set('text', Math.round(to) + '%');

        return this;
    }

});

/**
* Swiff.Uploader - Flash FileReference Control
* @version		3.0
* @license		MIT License
* @author		Harald Kirschner <http://digitarald.de>
* @author		Valerio Proietti, <http://mad4milk.net>
* @copyright	Authors
*/

Swiff.Uploader = new Class({

    Extends: Swiff,

    Implements: Events,

    options: {
        path: 'Swiff.Uploader.swf',

        target: null,
        zIndex: 9999,

        height: 30,
        width: 100,
        callBacks: null,
        params: {
            wMode: 'opaque',
            menu: 'false',
            allowScriptAccess: 'always'
        },

        typeFilter: null,
        multiple: true,
        queued: true,
        verbose: false,

        url: null,
        method: null,
        data: null,
        mergeData: true,
        fieldName: null,

        fileSizeMin: 1,
        fileSizeMax: null, // Official limit is 100 MB for FileReference, but I tested up to 2Gb!
        allowDuplicates: false,
        timeLimit: (Browser.Platform.linux) ? 0 : 30,

        buttonImage: null,
        policyFile: null,

        fileListMax: 0,
        fileListSizeMax: 0,

        instantStart: false,
        appendCookieData: false,

        fileClass: null
        /*
        onLoad: $empty,
        onFail: $empty,
        onStart: $empty,
        onQueue: $empty,
        onComplete: $empty,
        onBrowse: $empty,
        onDisabledBrowse: $empty,
        onCancel: $empty,
        onSelect: $empty,
        onSelectSuccess: $empty,
        onSelectFail: $empty,
		
        onButtonEnter: $empty,
        onButtonLeave: $empty,
        onButtonDown: $empty,
        onButtonDisable: $empty,
		
        onFileStart: $empty,
        onFileStop: $empty,
        onFileRequeue: $empty,
        onFileOpen: $empty,
        onFileProgress: $empty,
        onFileComplete: $empty,
        onFileRemove: $empty,
		
        onBeforeStart: $empty,
        onBeforeStop: $empty,
        onBeforeRemove: $empty
        */
    },

    initialize: function (options) {
        // protected events to control the class, added
        // before setting options (which adds own events)
        this.addEvent('load', this.initializeSwiff, true)
			.addEvent('select', this.processFiles, true)
			.addEvent('complete', this.update, true)
			.addEvent('fileRemove', function (file) {
			    this.fileList.erase(file);
			} .bind(this), true);

        this.setOptions(options);

        // callbacks are no longer in the options, every callback
        // is fired as event, this is just compat
        if (this.options.callBacks) {
            Hash.each(this.options.callBacks, function (fn, name) {
                this.addEvent(name, fn);
            }, this);
        }

        this.options.callBacks = {
            fireCallback: this.fireCallback.bind(this)
        };

        var path = this.options.path;
        if (!path.contains('?')) path += '?noCache=' + $time(); // cache in IE

        // container options for Swiff class
        this.options.container = this.box = new Element('span', { 'class': 'swiff-uploader-box' }).inject($(this.options.container) || document.body);

        // target 
        this.target = $(this.options.target);
        if (this.target) {
            var scroll = window.getScroll();
            this.box.setStyles({
                position: 'absolute',
                visibility: 'visible',
                zIndex: this.options.zIndex,
                overflow: 'hidden',
                height: 1, width: 1,
                top: scroll.y, left: scroll.x
            });

            // we force wMode to transparent for the overlay effect
            this.parent(path, {
                params: {
                    wMode: 'transparent'
                },
                height: '100%',
                width: '100%'
            });

            this.target.addEvent('mouseenter', this.reposition.bind(this, []));

            // button interactions, relayed to to the target
            this.addEvents({
                buttonEnter: this.targetRelay.bind(this, ['mouseenter']),
                buttonLeave: this.targetRelay.bind(this, ['mouseleave']),
                buttonDown: this.targetRelay.bind(this, ['mousedown']),
                buttonDisable: this.targetRelay.bind(this, ['disable'])
            });

            this.reposition();
            window.addEvent('resize', this.reposition.bind(this, []));
        } else {
            this.parent(path);
        }

        this.inject(this.box);

        this.fileList = [];

        this.size = this.uploading = this.bytesLoaded = this.percentLoaded = 0;

        if (Browser.Plugins.Flash.version < 9) {
            this.fireEvent('fail', ['flash']);
        } else {
            this.verifyLoad.delay(1000, this);
        }
    },

    verifyLoad: function () {
        if (this.loaded) return;
        if (!this.object.parentNode) {
            this.fireEvent('fail', ['disabled']);
        } else if (this.object.style.display == 'none') {
            this.fireEvent('fail', ['hidden']);
        } else if (!this.object.offsetWidth) {
            this.fireEvent('fail', ['empty']);
        }
    },

    fireCallback: function (name, args) {
        // file* callbacks are relayed to the specific file
        if (name.substr(0, 4) == 'file') {
            // updated queue data is the second argument
            if (args.length > 1) this.update(args[1]);
            var data = args[0];

            var file = this.findFile(data.id);
            this.fireEvent(name, file || data, 5);
            if (file) {
                var fire = name.replace(/^file([A-Z])/, function ($0, $1) {
                    return $1.toLowerCase();
                });
                file.update(data).fireEvent(fire, [data], 10);
            }
        } else {
            this.fireEvent(name, args, 5);
        }
    },

    update: function (data) {
        // the data is saved right to the instance 
        $extend(this, data);
        this.fireEvent('queue', [this], 10);
        return this;
    },

    findFile: function (id) {
        for (var i = 0; i < this.fileList.length; i++) {
            if (this.fileList[i].id == id) return this.fileList[i];
        }
        return null;
    },

    initializeSwiff: function () {
        // extracted options for the swf 
        this.remote('initialize', {
            width: this.options.width,
            height: this.options.height,
            typeFilter: this.options.typeFilter,
            multiple: this.options.multiple,
            queued: this.options.queued,
            url: this.options.url,
            method: this.options.method,
            data: this.options.data,
            mergeData: this.options.mergeData,
            fieldName: this.options.fieldName,
            verbose: this.options.verbose,
            fileSizeMin: this.options.fileSizeMin,
            fileSizeMax: this.options.fileSizeMax,
            allowDuplicates: this.options.allowDuplicates,
            timeLimit: this.options.timeLimit,
            buttonImage: this.options.buttonImage,
            policyFile: this.options.policyFile
        });

        this.loaded = true;

        this.appendCookieData();
    },

    targetRelay: function (name) {
        if (this.target) this.target.fireEvent(name);
    },

    reposition: function (coords) {
        // update coordinates, manual or automatically
        coords = coords || (this.target && this.target.offsetHeight)
			? this.target.getCoordinates(this.box.getOffsetParent())
			: { top: window.getScrollTop(), left: 0, width: 40, height: 40 }
        this.box.setStyles(coords);
        this.fireEvent('reposition', [coords, this.box, this.target]);
    },

    setOptions: function (options) {
        if (options) {
            if (options.url) options.url = Swiff.Uploader.qualifyPath(options.url);
            if (options.buttonImage) options.buttonImage = Swiff.Uploader.qualifyPath(options.buttonImage);
            this.parent(options);
            if (this.loaded) this.remote('setOptions', options);
        }
        return this;
    },

    setEnabled: function (status) {
        this.remote('setEnabled', status);
    },

    start: function () {
        this.fireEvent('beforeStart');
        this.remote('start');
    },

    stop: function () {
        this.fireEvent('beforeStop');
        this.remote('stop');
    },

    remove: function () {
        this.fireEvent('beforeRemove');
        this.remote('remove');
    },

    fileStart: function (file) {
        this.remote('fileStart', file.id);
    },

    fileStop: function (file) {
        this.remote('fileStop', file.id);
    },

    fileRemove: function (file) {
        this.remote('fileRemove', file.id);
    },

    fileRequeue: function (file) {
        this.remote('fileRequeue', file.id);
    },

    appendCookieData: function () {
        var append = this.options.appendCookieData;
        if (!append) return;

        var hash = {};
        document.cookie.split(/;\s*/).each(function (cookie) {
            cookie = cookie.split('=');
            if (cookie.length == 2) {
                hash[decodeURIComponent(cookie[0])] = decodeURIComponent(cookie[1]);
            }
        });

        var data = this.options.data || {};
        if ($type(append) == 'string') data[append] = hash;
        else $extend(data, hash);

        this.setOptions({ data: data });
    },

    processFiles: function (successraw, failraw, queue) {
        var cls = this.options.fileClass || Swiff.Uploader.File;

        var fail = [], success = [];

        if (successraw) {
            successraw.each(function (data) {
                var ret = new cls(this, data);
                if (!ret.validate()) {
                    ret.remove.delay(10, ret);
                    fail.push(ret);
                } else {
                    this.size += data.size;
                    this.fileList.push(ret);
                    success.push(ret);
                    ret.render();
                }
            }, this);

            this.fireEvent('selectSuccess', [success], 10);
        }

        if (failraw || fail.length) {
            fail.extend((failraw) ? failraw.map(function (data) {
                return new cls(this, data);
            }, this) : []).each(function (file) {
                file.invalidate().render();
            });

            this.fireEvent('selectFail', [fail], 10);
        }

        this.update(queue);

        if (this.options.instantStart && success.length) this.start();
    }

});

$extend(Swiff.Uploader, {

    STATUS_QUEUED: 0,
    STATUS_RUNNING: 1,
    STATUS_ERROR: 2,
    STATUS_COMPLETE: 3,
    STATUS_STOPPED: 4,

    log: function () {
        if (window.console && console.info) console.info.apply(console, arguments);
    },

    unitLabels: {
        b: [{ min: 1, unit: 'B' }, { min: 1024, unit: 'kB' }, { min: 1048576, unit: 'MB' }, { min: 1073741824, unit: 'GB'}],
        s: [{ min: 1, unit: 's' }, { min: 60, unit: 'm' }, { min: 3600, unit: 'h' }, { min: 86400, unit: 'd'}]
    },

    formatUnit: function (base, type, join) {
        var labels = Swiff.Uploader.unitLabels[(type == 'bps') ? 'b' : type];
        var append = (type == 'bps') ? '/s' : '';
        var i, l = labels.length, value;

        if (base < 1) return '0 ' + labels[0].unit + append;

        if (type == 's') {
            var units = [];

            for (i = l - 1; i >= 0; i--) {
                value = Math.floor(base / labels[i].min);
                if (value) {
                    units.push(value + ' ' + labels[i].unit);
                    base -= value * labels[i].min;
                    if (!base) break;
                }
            }

            return (join === false) ? units : units.join(join || ', ');
        }

        for (i = l - 1; i >= 0; i--) {
            value = labels[i].min;
            if (base >= value) break;
        }

        return (base / value).toFixed(1) + ' ' + labels[i].unit + append;
    }

});

Swiff.Uploader.qualifyPath = (function () {

    var anchor;

    return function (path) {
        (anchor || (anchor = new Element('a'))).href = path;
        return anchor.href;
    };

})();

Swiff.Uploader.File = new Class({

    Implements: Events,

    initialize: function (base, data) {
        this.base = base;
        this.update(data);
    },

    update: function (data) {
        return $extend(this, data);
    },

    validate: function () {
        var options = this.base.options;

        if (options.fileListMax && this.base.fileList.length >= options.fileListMax) {
            this.validationError = 'fileListMax';
            return false;
        }

        if (options.fileListSizeMax && (this.base.size + this.size) > options.fileListSizeMax) {
            this.validationError = 'fileListSizeMax';
            return false;
        }

        return true;
    },

    invalidate: function () {
        this.invalid = true;
        this.base.fireEvent('fileInvalid', this, 10);
        return this.fireEvent('invalid', this, 10);
    },

    render: function () {
        return this;
    },

    setOptions: function (options) {
        if (options) {
            if (options.url) options.url = Swiff.Uploader.qualifyPath(options.url);
            this.base.remote('fileSetOptions', this.id, options);
            this.options = $merge(this.options, options);
        }
        return this;
    },

    start: function () {
        this.base.fileStart(this);
        return this;
    },

    stop: function () {
        this.base.fileStop(this);
        return this;
    },

    remove: function () {
        this.base.fileRemove(this);
        return this;
    },

    requeue: function () {
        this.base.fileRequeue(this);
    }

});
/**
* FancyUpload.Attach - Flash meets Ajax for powerful and elegant uploads.
* @version		3.0 rc1
* @license		MIT License
* @author		Harald Kirschner <mail [at] digitarald [dot] de>
* @copyright	Authors
*/

if (!window.FancyUpload3) var FancyUpload3 = {};

FancyUpload3.Attach = new Class({

    Extends: Swiff.Uploader,

    options: {
        queued: false,
        instantStart: true
    },

    initialize: function (list, selects, options) {
 		this.list = list;
		this.selects = selects
				
		options.target = this.selects[0];
		options.fileClass = options.fileClass || FancyUpload3.Attach.File;
		
		this.parent(options);

        /**
        * Button state
        */
        var self = this;

        $$(this.selects).addEvents({
            click: function () {
                return false;
            },
            mouseenter: function () {
                this.addClass('hover');
                self.reposition();
            },
            mouseleave: function () {
                this.removeClass('hover');
                this.blur();
            },
            mousedown: function () {
                this.focus();
            }
        });

        if (this.selects.length == 2) {
            this.selects[1].setStyle('display', 'none');
            this.addEvents({
                'selectSuccess': this.onSelectSuccess,
                'fileRemove': this.onFileRemove
            });
        }
    },

    onSelectSuccess: function () {
        if (this.fileList.length > 0) {
            this.selects[0].setStyle('display', 'none');
            this.selects[1].setStyle('display', 'inline');
            this.target = this.selects[1];
            this.reposition();
        }
    },

    onFileRemove: function () {
        if (this.fileList.length == 0) {
            this.selects[0].setStyle('display', 'inline');
            this.selects[1].setStyle('display', 'none');
            this.target = this.selects[0];
            this.reposition();
        }
    },

    start: function () {
        if (Browser.Platform.linux && window.confirm(MooTools.lang.get('FancyUpload', 'linuxWarning'))) return this;
        return this.parent();
    }

});

FancyUpload3.Attach.File = new Class({

    Extends: Swiff.Uploader.File,

    render: function () {

        if (this.invalid) {
            if (this.validationError) {
                var msg = MooTools.lang.get('FancyUpload', 'validationErrors')[this.validationError] || this.validationError;
                this.validationErrorMessage = msg.substitute({
                    name: this.name,
                    size: Swiff.Uploader.formatUnit(this.size, 'b'),
                    fileSizeMin: Swiff.Uploader.formatUnit(this.base.options.fileSizeMin || 0, 'b'),
                    fileSizeMax: Swiff.Uploader.formatUnit(this.base.options.fileSizeMax || 0, 'b'),
                    fileListMax: this.base.options.fileListMax || 0,
                    fileListSizeMax: Swiff.Uploader.formatUnit(this.base.options.fileListSizeMax || 0, 'b')
                });
            }
            this.remove();
            return;
        }

        this.addEvents({
            'open': this.onOpen,
            'remove': this.onRemove,
            'requeue': this.onRequeue,
            'progress': this.onProgress,
            'stop': this.onStop,
            'complete': this.onComplete,
            'error': this.onError
        });

        this.ui = {};

        this.ui.element = new Element('li', { 'class': 'file', id: 'file-' + this.id });
        this.ui.title = new Element('span', { 'class': 'file-title', text: this.name });
        this.ui.size = new Element('span', { 'class': 'file-size', text: Swiff.Uploader.formatUnit(this.size, 'b') });

        this.ui.cancel = new Element('a', { 'class': 'file-cancel', text: 'Cancel', href: '#' });
        this.ui.cancel.addEvent('click', function () {
            this.remove();
            return false;
        } .bind(this));

        this.ui.element.adopt(
			this.ui.title,
			this.ui.size,
			this.ui.cancel
		).inject(this.base.list).highlight();

        var progress = new Element('img', { 'class': 'file-progress', src: '/images/bar.gif' }).inject(this.ui.size, 'after');
        this.ui.progress = new Fx.ProgressBar(progress, {
            fit: true
        }).set(0);

        this.base.reposition();

        return this.parent();
    },

    onOpen: function () {
        this.ui.element.addClass('file-uploading');
        if (this.ui.progress) this.ui.progress.set(0);
    },

    onRemove: function () {
        this.ui = this.ui.element.destroy();
    },

    onProgress: function () {
        if (this.ui.progress) this.ui.progress.start(this.progress.percentLoaded);
    },

    onStop: function () {
        this.remove();
    },

    onComplete: function () {
        this.ui.element.removeClass('file-uploading');

        if (this.response.error) {
            var msg = MooTools.lang.get('FancyUpload', 'errors')[this.response.error] || '{error} #{code}';
            this.errorMessage = msg.substitute($extend({ name: this.name }, this.response));

            this.base.fireEvent('fileError', [this, this.response, this.errorMessage]);
            this.fireEvent('error', [this, this.response, this.errorMessage]);
            return;
        }

        if (this.ui.progress) this.ui.progress = this.ui.progress.cancel().element.destroy();
        this.ui.cancel = this.ui.cancel.destroy();

        var response = this.response.text || '';
        this.base.fireEvent('fileSuccess', [this, response]);
    },

    onError: function () {
        this.ui.element.addClass('file-failed');
    }

});

//Avoiding MooTools.lang dependency
(function () {

    var phrases = {
        'fileName': '{name}',
        'cancel': 'Cancel',
        'cancelTitle': 'Click to cancel and remove this entry.',
        'validationErrors': {
            'duplicate': 'File <em>{name}</em> is already added, duplicates are not allowed.',
            'sizeLimitMin': 'File <em>{name}</em> (<em>{size}</em>) is too small, the minimal file size is {fileSizeMin}.',
            'sizeLimitMax': 'File <em>{name}</em> (<em>{size}</em>) is too big, the maximal file size is <em>{fileSizeMax}</em>.',
            'fileListMax': 'File <em>{name}</em> could not be added, amount of <em>{fileListMax} files</em> exceeded.',
            'fileListSizeMax': 'File <em>{name}</em> (<em>{size}</em>) is too big, overall filesize of <em>{fileListSizeMax}</em> exceeded.'
        },
        'errors': {
            'httpStatus': 'Server returned HTTP-Status #{code}',
            'securityError': 'Security error occured ({text})',
            'ioError': 'Error caused a send or load operation to fail ({text})'
        },
        'linuxWarning': 'Warning: Due to a misbehaviour of Adobe Flash Player on Linux,\nthe browser will probably freeze during the upload process.\nDo you want to start the upload anyway?'
    };

    if (MooTools.lang) {
        MooTools.lang.set('en-US', 'FancyUpload', phrases);
    } else {
        MooTools.lang = {
            get: function (from, key) {
                return phrases[key];
            }
        };
    }

})();

/***
* Kaf Form
*
*/

var KafForm = new Class({

    hasAttachment: false,

    initialize: function () {
        document.getElements('.kaf-form').each(function (form) {
            new KafFormElement(form);
        })
    }
});

var KafFormElement = new Class({
    Implements: [Options],
    options: {
        ajax: true,
        resetOnSubmit: true,
        validation: true,
        loadingElement: null
    },

    initialize: function (form) {

        this.form = form;

        if (this.form.hasClass('done')) { return; }
        this.form.addClass('done');

        options = JSON.decode(this.form.get("title"));
        this.setOptions(options);
        this.form.erase("title");

        this.loadingIndicator = this.options.loadingElement ? document.id(loadingElement) : this.form.getElement('.loading');

        this.validator = new Form.Validator(this.form, {
            onFormValidate: this.validate.bind(this),
            onElementFail: this.elementFailed.bind(this),
            onElementPass: this.elementPassed.bind(this),
            evaluateFieldsOnBlur: true,
            serial: false,
            useTitles: true
        });

        if (this.options.ajax) {
            this.form.addEvent('submit', this.submitManager.bind(this));
            this.form.set('send', {
                onComplete: this.responseManager.bind(this),
                evalScripts: true
            });
        }
		if (form.getElement('.kaf-upload') != null ){
		
			$$('.kaf-upload').each(function(item){

                var uploadLink = item.getElement('.kaf-upload-link'),
				    attachList = item.getElement('.kaf-attach-list'),
                    moreAttach = item.getElement('.kaf-attach-2');
                var uploadOptions = JSON.decode(uploadLink.getProperty('title'));
                	

                new FancyUpload3.Attach(attachList, [uploadLink, moreAttach], {
					path: KafConfig.basePath + 'form/js/Swiff.Uploader.swf',
					url: uploadLink.get('href'),
					fileListMax: uploadOptions.fileListMax || 0,
					fileSizeMax: uploadOptions.fileSizeMax || 2 * 1024 * 1024,
					typeFilter: uploadOptions.typeFilter || {
	                    'All Supported files (*.jpg, *.jpeg, *.gif, *.png ,*.doc, *.docx, *.xls, *.xlsx ,*.pdf, *.zip, *.rar)': '*.jpg; *.jpeg; *.gif; *.png; *.doc; *.docx; *.xls; *.xlsx; *.pdf; *.zip; *.rar',
	                    'Images (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png',
	                    'Documents (*.doc, *.docx, *.xls, *.xlsx , *.pdf)': '*.doc; *.docx; *.xls; *.xlsx; *.pdf',
	                    'Compressed (*.rar, *.zip)': '*.rar; *.zip;'
                },
				
				verbose: true,
				
				onSelectFail: function(files) {
					files.each(function(file) {
						new Element('li', {
							'class': 'file-invalid',
							events: {
								click: function() {
									this.destroy();
								}
							}
						}).adopt(
							new Element('span', {html: file.validationErrorMessage || file.validationError})
						).inject(this.list, 'bottom');
					}, this);	
				},
				
				onFileSuccess: function(file) {
					/*new Element('input', { type: 'checkbox', 'checked': true, id: JSON.decode(file.response.text).hash }).inject(file.ui.element, 'top');*/
					new Element('label', { id: JSON.decode(file.response.text).hash}).inject(file.ui.element, 'top');
					file.ui.element.highlight('#e6efc2');
				},
				
				onFileError: function(file) {
					file.ui.cancel.set('html', 'Retry').removeEvents().addEvent('click', function() {
						file.requeue();
						return false;
					});
					
					new Element('span', {
						html: file.errorMessage,
						'class': 'file-error'
					}).inject(file.ui.cancel, 'after');
				},
				
				onFileRequeue: function(file) {
					file.ui.element.getElement('.file-error').destroy();
					
					file.ui.cancel.set('html', 'Cancel').removeEvents().addEvent('click', function() {
						file.remove();
						return false;
					});
					
					this.start();
				}
				
			});
            });
		}
    },

    submitManager: function (e) {
        e.stop();
        this.validator.start();
    },

    validate: function (passed) {
        if (passed) {
            if ($defined(this.loadingIndicator)) {
                this.showLoading();
            }
            this.form.send();
        }
    },
    elementFailed: function (element, validators) {
        var p = element.getParent().getElement('.validation');
        if (p) {
            return 0;
        }
        p = new Element('p', { 'class': 'validation' });
        p.setStyle('opacity', 0);
        p.set('html', element.get('title'));
        p.inject(element.getParent(), 'bottom');
        p.reveal().tween('opacity', [0, 1]);

        var parentLi = p.getParent('li').addClass('error');
    },

    elementPassed: function (element) {
        var p = element.getParent().getElement('.validation');
        var parentLi = element.getParent('li');

        if (p) {
            p.dissolve();
            setTimeout(function () { p.dispose(); }, 1000);
            parentLi.removeClass('error');
        }
    },

    responseManager: function (response) {
        var temp = JSON.decode(response);
        if ($defined(this.loadingIndicator) && !$defined(temp.redirect) || $defined(temp.errors)) {
            this.hideLoading();
        }
        this.clearForm();
        new KafResponseManager(response, this.form);
    },

    showLoading: function () {
        this.loadingIndicator.setStyle('display', 'block');
    },

    hideLoading: function () {
        this.loadingIndicator.setStyle('display', 'none');
    },

    clearForm: function () {
        var summary = this.form.getElement('.summary');
        if ($defined(summary)) {
            summary.removeClass('error');
            summary.removeClass('success');
            summary.empty();
        }

        var validations = this.form.getElements('.error');
        validations.each(function (item, index) {
            item.getElements("p.error").each(function (item, index) {
                item.dispose();
            });
            item.removeClass("error");
        });
    }
});

new KafForm();

/* test */
function SampleCallBack(param, param2) {
    alert(param + " - " + param2);
}
