window.pfClientWidgetUpload = function (core) {
    this.core           = core;

    this.albumId        = 0;
    this.title          = '';
    this.iframeReady    = false;

    this.getUploadFormName = function () {
        return this.core.main.name+'_upload_form';
    }

    this.getUploadFormId = function () {
        return this.core.main.name+'_upload_form_id';
    }

    this.getUploadIframeId = function () {
        return this.core.main.name+'_upload_iframe_id';
    }

    this.getUploadIframeName = function () {
        return this.core.main.name+'_upload_iframe';
    }

    this.getUploadFormTrIdByName = function (name) {
        return this.core.main.name+'_upload_tr_'+name;
    }

    this.getAlbumsSelectId = function () {
        return this.core.main.name+'_upload_albums_select';
    }

    this.getGenresSelectId = function () {
        return this.core.main.name+'_upload_genres_select';
    }

    this.getInputHiddenId = function () {
        return this.core.main.name+'_input_hidden_id';
    }

    this.albumsSelectOnChange = function () {
        var display = 'none';

        if (this.getSelectedAlbumId() == -1) {
            if (this.core.is_ie) {
                display = 'block';
            }
            else {
                display = 'table-row';
            }
        }

        this.core.dom(this.getUploadFormTrIdByName('title')).style.display  = display;
        this.core.dom(this.getUploadFormTrIdByName('genre')).style.display  = display;
        this.core.dom(this.getUploadFormTrIdByName('pwd1') ).style.display  = display;
        this.core.dom(this.getUploadFormTrIdByName('pwd2') ).style.display  = display;
    }

    this.uploadFormSubmit = function () {
        if (!this.checkUploadForm()) {
            return false;
        }

        if (this.core.main.model.isFakeAlbumId(this.getSelectedAlbumId())) {
            this.uploadToNewAlbum();
        }
        else {
            this.albumId = this.getSelectedAlbumId();
            this.uploadToExistingAlbum();
        }
    }

    this.uploadToNewAlbum = function () {
        var self = this;
        var form = this.findUploadForm();

        self.core.widgetEtc.debugMsg('uploading to new album, must create album first');

        this.core.main.api.callAlbumCreateFast(
            this.getSelectedAlbumId()

          // callback
          , function (answer) {
                var album = answer;
                self.core.main.model.addAlbum(album);
                self.albumId = album.id;
                self.core.widgetEtc.debugMsg('new album created');
                self.uploadToExistingAlbum();
            }
        );
    }

    this.uploadToExistingAlbum = function () {
        var self = this;

        this.iframeReady = false;

        self.core.widgetEtc.debugMsg('uploading photo in album '+this.albumId);

        this.core.main.api.callUploadGetUrl(this.albumId, this.title, function (answer) {

            //clear photos
            self.core.main.model.clearPhotos(self.albumId);

            self.iframeReady = true;

            var iframe = self.findUploadIframe();
            // form patch
            var form    = self.findUploadForm();
            form.action = answer;

            var ex = null;

            self.core.widgetEtc.debugMsg('trying to post form');

            try {
                form.submit();
                self.core.widgetEtc.debugMsg('form.submit() is ok');

                if (self.core.is_opera) {
                    form.style.display      = 'none';
                    iframe.style.display    = 'block';
                    self.core.main.pageMainAgain();
                }
            }
            catch (ex) {
                self.core.widgetEtc.debugMsg('form.submit() throws exception: '+ex);
                self.iframeReady = false;
                self.core.main.pageMainAgain();
                alert('Введите правильное имя файла!');
            }
        });
    }

    this.getSelectedAlbumId = function () {
        return this.core.dom(this.getAlbumsSelectId()).value;
    }

    this.findUploadForm = function () {
        return this.core.dom(this.getUploadFormId());
    }

    this.findUploadIframe = function () {
        return this.core.dom(this.getUploadIframeId());
    }


    this.checkUploadForm = function () {
        var form = this.findUploadForm();

        if (form.photo.value == undefined || form.photo.value == null || form.photo.value == '') {
            alert('Необходимо выбрать фото для закачки');
            return false;
        }

        // check file extension
        var reg = /^.*(jpg|jpeg|png|gif)$/i;
        if (!form.photo.value.match(reg)) {
            alert('Необходимо выбрать фото в формате JPG,JPEG,GIF или PNG');
            return false;
        }

        // fetch photo title
        var reg = /^.*?([^\/\\]+\.[^\/\\]+)$/;
        var res = reg.exec(form.photo.value);

        if (res == undefined || res == null || res == '') {
            this.title = form.photo.value;
        }
        else {
            this.title  = res[1];
        }


        /* TODO REMOVE
        if (this.getSelectedAlbumId() != -1) {
            return true;
        }

        //check for title
        if (form.title.value == '') {
            alert('Введите название альбома');
            return false;
        }

        //check for pwd
        if (form.pwd1.value != form.pwd2.value) {
            alert('Оба введёных пароля должны совпадать');
            return false;
        }
        */

        return true;
    }

    this.iframeOnLoad = function () {
        var self = this;

        self.core.widgetEtc.debugMsg('iframeOnLoad called');

        if (this.iframeReady) {
            self.core.widgetEtc.debugMsg('calling pagePhotos, because this.iframeReady');
            this.core.main.wrapper.pagePhotos(this.albumId);
        }
        else {
            self.core.widgetEtc.debugMsg('skipping pagePhotos, because !this.iframeReady');
        }
    }

    this.textMsgContentType = function () {
        return 'text/html; charset=utf-8';
    }

    this.htmlMsgCommon = function (msg) {
        return ''
            +'<html>'
            +'<head>'
                +'<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'
                +'<title>Загрузка фотографии</title>'
                +'<style>'
                +'  body { font-family:arial; font-size:12px; font-size-adjust:none; font-style:normal; font-variant:normal; font-weight:normal; line-height:normal; }'
                +'  a    { color: #4d4d4d; }'
                +'</style>'
            +'</head>'
            +'<body>'
                +'<center>'
                    +msg
                    +'<br />'
                    //+'<a href="#" onclick="parent.location=\''+this.core.main.linker.linkAlbums()+'\';">продолжить</a>'
                +'</center>'
            +'</body>'
            +'</html>';
    }

    this.htmlMsgCommonJs = function (msg) {
        return ''
            +'<html>'
            +'<head>'
                +'<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'
                +'<title>Загрузка фотографии</title>'
            +'</head>'
            +'<body>'
                +'<script>'
                +   'alert("'+msg+'");'
                +'</script>'
            +'</body>'
            +'</html>';
    }

    this.htmlMsgOk = function () {
        return this.htmlMsgCommon('Загрузка завершена успешно');
    }

    this.htmlMsgError = function () {
        if (this.core.is_opera) {
            return this.htmlMsgCommon('Ошибка загрузки фотографии _ERRNO_');
        }
        else {
            return this.htmlMsgCommonJs('Ошибка загрузки фотографии _ERRNO_');
        }
    }

    this.pageUpload = function (cont, album) {
        var self = this;
        this.iframeReady = false;

        // iframe
        // грязнохак, патамучта через DOM это ни-ри-аль-на
        cont.innerHTML = 

            // frame
            
            '<iframe'
            +'  name="'+this.getUploadIframeName()+'"'
            +'  id="'+this.getUploadIframeId()+'"'
            +'  class="upload_iframe_opera"'
            //+'  src="about:blank"'
            +'  src="'+self.core.main.api.getLoadingPageUrl()+'"'
            //+'  onload="alert(\'iframe onload\');"'
            +'  onload="'+this.core.main.name+'.widget.widgetUpload.iframeOnLoad();"'
            +'>'
            +'</iframe>'

            //form

            +'<form'
            +'  id="'+this.getUploadFormId()+'"'
            +'  name="'+this.getUploadFormName()+'"'
            +'  class="photoUpload"'
            +'  target="'+this.getUploadIframeName()+'"'
            +'  method="POST"'
            +'  enctype="multipart/form-data"'
            +'>'
            +'</form>'

            +'';

        var iframe = this.findUploadIframe();
        var form   = this.findUploadForm();

        /*
        iframe.onload = function () {
            //alert ('debuggin - anonymous onload');
            self.core.widgetUpload.iframeOnLoad();
        }
        */

        // form

        if (album == undefined) {
            album = null;
        }

        /*
        var form        = this.core.create('form', cont, 'photoUpload');
        form.id         = this.getUploadFormId();
        form.name       = this.getUploadFormName();
        form.action     = 'about:blank';
        form.target     = this.getUploadIframeName();;
        form.enctype    = 'multipart/form-data';
        form.method     = 'POST';
        */
        
        var msgContentType  = this.core.createInput('input', 'hidden', 'msgContentType' , this.textMsgContentType(), null, form);
        var msgOk           = this.core.createInput('input', 'hidden', 'msgOk'          , this.htmlMsgOk(), null, form);
        var msgError        = this.core.createInput('input', 'hidden', 'msgError'       , this.htmlMsgError(), null, form);

        var table       = this.core.create('table', form    , 'upload');
        var tbody       = this.core.create('tbody', table   , 'upload');

        var trHead      = this.core.create('tr', tbody);
        var tdHead      = this.core.create('th', trHead, 'title');
        tdHead.colSpan  = 2;
        this.core.write(tdHead, 'Загрузить фото с компьютера');


        /* Blocked until PF api supported 
        // title
        var trTitle = this.core.create('tr', tbody);
        this.core.write(this.core.create('th', trTitle), 'Название:');
        var inputTitle = this.core.createInput('input', 'input', 'title', null, null, this.core.create('td', trTitle), 'InputBox');

        // desc
        var trDesc = this.core.create('tr', tbody);
        this.core.write(this.core.create('th', trDesc), 'Описание:');
        var inputDesc   = this.core.createInput('textarea', null, 'desc', null, null, this.core.create('td', trDesc), 'InputBox');
        */
        
        var inputAlbumId = this.core.createInput('input', 'hidden', 'albumId', null, null, form);
        inputAlbumId.id     = this.getAlbumsSelectId();
        inputAlbumId.value  = album.id;


        /* TODO REMOVE
        // albums selector
        var trAlbums    = this.core.create('tr', tbody);
        this.core.write(this.core.create('td', trAlbums), 'Альбом');

        var albumsSelect    = this.core.create('select', this.core.create('td', trAlbums));
        albumsSelect.id     = this.getAlbumsSelectId();
        albumsSelect.name   = 'albumId';

        var option      = this.core.create('option', albumsSelect);
        option.value    = -1;
        this.core.write(option, '- новый альбом -');
        if (album != null) {
            option.selected = true;
        }

        var albumsList      = this.core.main.model.getAllAlbums();
        var idx             = 0;
        var idxLim          = albumsList.length;
        
        for (idx = 0; idx < idxLim; idx++) {
            var option      = this.core.create('option', albumsSelect);
            option.value    = albumsList[idx].id

            if (album != null && albumsList[idx].id == album.id) {
                option.selected = true;
            }
            this.core.write(option, albumsList[idx].title);
        }

        albumsSelect.onchange   = function () {
            self.albumsSelectOnChange();
        }

        this.drawTitleTr(tbody);
        this.drawGenreTr(tbody);
        this.drawPwd1Tr(tbody);
        this.drawPwd2Tr(tbody);
        */

        // file input
        var trUpload    = this.core.create('tr', tbody);
        this.core.write(this.core.create('th', trUpload), 'Путь к файлу:');
        var inputUpload = this.core.createInput('input', 'file', 'photo', null, null, this.core.create('td', trUpload), 'InputBox');

        // footer
        var trFoot      = this.core.create('tr', tbody);
        var tdFoot      = this.core.create('td', trFoot, 'footer');
        tdFoot.colSpan  = 2;

        var buttonSubmit        = this.core.createInput('input', 'button', 'load', 'Сохранить изменения', null, tdFoot);
        buttonSubmit.onclick    = function () {
            self.uploadFormSubmit();
        }

        /* TODO REMOVE
        var buttonCancel        = this.core.createInput('input', 'button', 'cancel', 'Отменить', null, tdFoot, 'button');
        buttonCancel.onclick    = function () {
            if (album == null || album.photos == null || album.photos.length == 0) {
                self.core.main.pageAlbums();
            }
            else {
                self.core.main.wrapper.pagePhotos(album.id);
            }
        }
        */

        /*TODO REMOVE
        this.albumsSelectOnChange();
        */
    }

    this.drawTitleTr = function (tbody, value) {
        var trTitle     = this.core.create('tr', tbody);
        trTitle.id      = this.getUploadFormTrIdByName('title');
        this.core.write(this.core.create('td', trTitle), 'Название');
        var inputTitle  = this.core.createInput('input', 'input', 'title', null, null, this.core.create('td', trTitle));

        if (value != undefined) {
            inputTitle.value = value;
        }
    }

    this.drawGenreTr = function (tbody, value) {
        if (value == undefined) {
            value = this.core.main.model.getDefaultAvailableGenreId();
        }

        // genre
        var trGenre             = this.core.create('tr', tbody);
        trGenre.id              = this.getUploadFormTrIdByName('genre');
        this.core.write(this.core.create('td', trGenre), 'Жанр');
        var selectGenre         = this.core.create('select', this.core.create('td', trGenre));
        selectGenre.id          = this.getGenresSelectId();
        selectGenre.name        = 'genreId';
        this.drawGenresOptions(selectGenre, value);
    }

    this.drawPwd1Tr = function (tbody, value) {
        var self = this;

        var trPwd1      = this.core.create('tr', tbody);
        trPwd1.id       = this.getUploadFormTrIdByName('pwd1');
        this.core.write(this.core.create('td', trPwd1), 'Пароль');

        var tdPwd1          = this.core.create('td', trPwd1);
        var inputPwd1       = this.core.createInput('input', 'password', 'pwd1', null, null, tdPwd1);
        inputPwd1.onchange  = function () {
            self.core.dom(self.getInputHiddenId()).value = 1;
        }

        var inputHidden     = this.core.createInput('input', 'hidden', 'pwdChanged', null, null, tdPwd1);
        inputHidden.id      = this.getInputHiddenId();
        inputHidden.value   = 0;
        
        if (value != undefined) {
            inputPwd1.value = value;
        }
    }

    this.drawPwd2Tr = function (tbody, value) {
        var self = this;

        var trPwd2      = this.core.create('tr', tbody);
        trPwd2.id       = this.getUploadFormTrIdByName('pwd2');
        this.core.write(this.core.create('td', trPwd2), 'Ещё раз');

        var inputPwd2   = this.core.createInput('input', 'password', 'pwd2', null, null, this.core.create('td', trPwd2));
        inputPwd2.onchange  = function () {
            self.core.dom(self.getInputHiddenId()).value = 1;
        }

        if (value != undefined) {
            inputPwd2.value = value;
        }
    }

    this.drawDescTr = function (tbody, value) {
        var trDesc      = this.core.create('tr', tbody);
        trDesc.id       = this.getUploadFormTrIdByName('desc');
        this.core.write(this.core.create('td', trDesc), 'Описание');
        var inputDesc   = this.core.createInput('textarea', null, 'desc', null, null, this.core.create('td', trDesc));

        if (value != undefined) {
            inputDesc.value = value;
        }
    }

    this.drawGenresOptions = function (cont, value, parentId, level) {
        if (parentId == undefined || parentId == null) {
            parentId = 0;
        }

        if (level == undefined || level == null) {
            level = 0;
        }

        var genresList = this.core.main.model.getGenresByParentId(parentId);
        var j, jlim;

        for (j = 0, jlim = genresList.length; j < jlim; j++) {

            if (genresList[j].parentId) {
                var option      = this.core.create('option', cont);
                option.value    = genresList[j].id;
                this.core.write(option, genresList[j].name);

                if (value == genresList[j].id) {
                    option.selected = true;
                }
            }
            else {
                var optgroup = this.core.create('optgroup', cont);
                optgroup.title  = genresList[j].name;
                optgroup.label  = genresList[j].name;
            }

            this.drawGenresOptions(cont, value, genresList[j].id, level + 1);
        }
    }
}

