var Uploader = new Class({
    Implements: Options,
    flashvars: {
        button_image    : "/web/js/uploader/button2.png",
        allow_file_caption    : "Obrázky (*.jpg, *.jpeg, *.gif, *.png)",
        allow_file_exts    : "*.jpg; *.jpeg; *.gif; *.png",
        upload_path         : '/_reality/reals/upload/',
        file_num_limit: 1
    },
    params: {
        menu : "false",
        allowScriptAccess : "always"
    },
    attributes: {
        name: '',
        id: ''
    },
    options: {
        img_list            : 'progress',
        id_name_postfix    : '_flash',
        gallery        : true,
        session_id          : '',
        width        : 120,
        height        : 33,
        flash_version    : '10.0.0',
        type_of_uploader    : 'upload',
        upload_type     : 'ftp', // php|ftp
        filename_type     : 'unique', // unique, alias, filename
        filename            : '', // nazev souboru, pokud se jedna u type_of_name = 'filename'
        render_type            : 'gallery', //gallery, simple, list,
        simple_input    : '', // pokud je u render_type = 'simple', hodnota vyjadruje id inputu, kam se ma posleze vratit cesta k souboru
        methods            : {}, // pokud se jedna napr. o gallery, tak nedefinujeme na jake velikost a jakou metodou se obrazek upravi,
        input_name          : 'data[RealityItemPhoto][name][]',
        delete_caption      : 'Opravdu chcete odstranit tento obrazek?'
    },
    initialize: function(element, options) {
        // inicializace objektu a predani pointeru pro flash
        if (!window.objects) {
            window.objects = Object();
        }
        var pointer = Object.getLength(window.objects);
        window.objects[pointer] = this;


        if (options.allow_file_caption)
            this.flashvars.allow_file_caption = options.allow_file_caption;

        if (options.allow_file_exts)
            this.flashvars.allow_file_exts = options.allow_file_exts;

        this.flashvars.pointer = pointer;

        if (options.upload_path) {
            this.flashvars.upload_path = options.upload_path;
        }

        this.setOptions(options);
        this.element = element;
        /**
         * Kontrola, zda existuje SwfObject
         */
        if (typeof swfobject == 'undefined') {
            alert('Neni natahnuta JS component swfobject');
            return;
        }

        this.flashvars.session_id = this.options.session_id;
        this.flashvars.render_type = this.options.render_type;
        this.setAttr();
        this.json_data();
        this.renderSwf();

        $(this.options.img_list).getElements('.remove_image').addEvent('click', (function(e) {
            e.stop();
            if (confirm(this.options.delete_caption))
                e.target.getParent('.image_obal').dispose();
        }).bind(this))
//            this.sort = new Sortables($(this.options.img_list), {
//                constrain: false,
//                clone: true
//            });
    },

    setAttr: function() {
        /**
         * Nastaveni params, tedy hlavne id a name flash objektu
         */
        this.attributes = {
            name: this.element + this.options.id_name_postfix,
            id: this.element + this.options.id_name_postfix
        }
    },

    json_data: function() {
        this.flashvars.json_data = (JSON.encode(this.options)).replace(/"/g, "'");        
//        this.flashvars.json_data = JSON.encode(this.options);
    },

    renderSwf: function() {

        swfobject.embedSWF(
            '/web/js/uploader/' + this.options.type_of_uploader + ".swf?m=" + Math.random(),
            this.element,
            this.options.width,
            this.options.height,
            this.options.flash_version,
            "",
            this.flashvars,
            this.params,
            this.attributes,
            function(returnObj) {
                if (returnObj.success) {
                    //returnObj.ref.focus();
                }
            }
        );

    },

    getFlashMovieObject: function(movieName) {
        if (window.document[movieName]) {
            return window.document[movieName];
        }
        if (navigator.appName.indexOf("Microsoft Internet") == -1) {
            if (document.embeds && document.embeds[movieName])
                return document.embeds[movieName];
            else
                return false;
        } else {
            return $(movieName);
        }
    },

    convert_units: function(value){
        var unit = 'B';
        if (value > 1024){
            value = Math.round(value/1024*100)/100;
            unit = 'kB';
        }
        if (value > 1024){
            value = Math.round(value/1024*100)/100;
            unit = 'MB';
        }
        return value + ' ' + unit;
    },

    info: function(file, num, preneseno, celkem) {
        $(this.options.img_list).set('html',this.convert_units(preneseno) + ' z ' + this.convert_units(celkem) + ' (' + (Math.round(preneseno/celkem*100 * 100)/100) + '%)');
    },

    create_obal: function(file) {
        obal = new Element('div', {'class':'image_obal'})
            .setProperty('id', file)
            .inject($(this.options.img_list))
        progress_obal = new Element('div', {'class':'img_progressobal'}).inject(obal);
        progress = new Element('div', {'class':'img_progressbar'}).inject(progress_obal)
    },

    load_image: function(file, img_data) {
        if ($(file) == null) {
            this.create_obal(file);
        }
        new Element('img', {src:'data:image/jpeg;base64,' + img_data}).inject($(file));
    },

    upload_complete: function(data) {
        switch (this.options.render_type) {
            case 'gallery':
                var file = data.filename;
                var response = JSON.decode(data.responce);
                var value = response.upload_file.name;
                $(file).getElement('.img_progressobal').dispose();
                new Element('input', {type:'hidden',name:this.options.input_name, value:value}).inject($(file));

                var lista = new Element('div', {'class':'lista_pos'}).inject($(file).getElement('img'), 'before');
                new Element('a', {href:'#', 'class':'ta move_image'}).inject(lista);
                new Element('a', {href:'#', 'class':'ta remove_image'})
                    .inject(lista)
                    .addEvent('click', (function(e) {
                    if (confirm(this.options.delete_caption))
                        e.target.getParent('.image_obal').dispose();
                }).bind(this))
                this.sort.addItems($(file));
                break;
            case 'simple':
                var file = data.filename;
                var response = JSON.decode(data.responce);
                var value = response.upload_file.name;
                $(this.options.input_id).setProperty('value', response.upload_file.db_id);
                $(this.options.img_list).set('html',response.upload_file.db_name);
                break;
            case 'attachment':
                var file = data.filename;
                var response = JSON.decode(data.responce);
                var value = response.upload_file.name;
                if ($(this.options.img_list)) {
                    if ($('ListAttachmentName') && $('ListAttachmentDescription') && $('ListAttachmentId')) {
                        $('fset_file_upload').addClass('green');
                        $('ListAttachmentId').setProperty('value', response.upload_file.db_id);
                        $('ListAttachmentPath').setProperty('value', response.upload_file.db_name);
                    }

                }
                refresh_dir();
                break;
        }
    },

    getPHPSessionId: function() {
        return this.options.session_id;

        var start = document.cookie.lastIndexOf('PHPSESSID=');
        var cookies = document.cookie.substr(start + 10, document.cookie.length);
        var end = cookies.indexOf(';');

        if (end != -1) {
            return cookies.substr(0, end);
        } else {
            return document.cookie.substr(start, document.cookie.length);
        }
    }

})
