(function(){
    var AuctionItemsEdit = function() {

        return {

            init: function() {
                var uploadedImages = [];
                var _result = [];

                if( $('#mainForm').find('input[name="images[]"]').length > 0 ) {
                    $('#mainForm').find('input[name="images[]"]').each(function(val) {
                        var val = $(this).val();

                        uploadedImages.push(val);
                        _result.push({
                            "name": val,
                            "size": "",
                            "url": window.imageStorageUrl + '/items/' + val,
                            "thumbnailUrl": window.imageStorageUrl + '/items/thumbnails/' + val
                        });
                        $(this).remove();
                    });
                }

                $('#fileupload').fileupload({
                    disableImageResize: false,
                    autoUpload: false,
                    disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
                    maxFileSize: 50000000,
                    acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
                    // Uncomment the following to send cross-domain cookies:
                    //xhrFields: {withCredentials: true},                
                }).on('fileuploaddone', function (e, data) {

                    $.each(data.result.files, function(val, key) {
                        uploadedImages.push( this.name );
                    });
                });

                $('#mainForm').on('submit', function(e) {
                    e.preventDefault();

                    if( uploadedImages.length == 0 ) {
                        alert('You have to upload at least one image for the item.')
                        return false;
                    }

                    $('#mainForm').find('input[name="images[]"]').remove();

                    $.each(uploadedImages, function(val, key) {
                        $('#mainForm').append('<input name="images[]" type="hidden" value="' + this + '" />');
                    });

                    this.submit();
                });

                $('#fileupload').fileupload('option', 'done').call($('#fileupload'), $.Event('done'), { 
                    result: {files: _result}
                });

                $('#datetimepicker-1').datetimepicker({
                    format: 'YYYY-MM-DD HH:mm:ss',
                    sideBySide: true
                });

                $('#datetimepicker-2').datetimepicker({
                    format: 'YYYY-MM-DD HH:mm:ss',
                    sideBySide: true
                });

                var editor_config = {
                    path_absolute : "/laravel-filemanager/",
                    selector: "textarea.tinyeditor",
                    plugins: [
                        "advlist autolink lists link image charmap print preview hr anchor pagebreak",
                        "searchreplace wordcount visualblocks visualchars code fullscreen",
                        "insertdatetime media nonbreaking save table contextmenu directionality",
                        "emoticons template paste textcolor colorpicker textpattern"
                    ],
                    toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media",
                    relative_urls: false,
                    file_browser_callback : function(field_name, url, type, win) {
                        var x = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;
                        var y = window.innerHeight|| document.documentElement.clientHeight|| document.getElementsByTagName('body')[0].clientHeight;

                        var cmsURL = editor_config.path_absolute + '?field_name=' + field_name;
                        if (type == 'image') {
                            cmsURL = cmsURL + "&type=Images";
                        } else {
                            cmsURL = cmsURL + "&type=Files";
                        }

                        tinyMCE.activeEditor.windowManager.open({
                            file : cmsURL,
                            title : 'Filemanager',
                            width : x * 0.8,
                            height : y * 0.8,
                            resizable : "yes",
                            close_previous : "no"
                        });
                    }
                };

                tinymce.init(editor_config);
            }
        }

    }();

    $(document).ready(function() {
        AuctionItemsEdit.init();
    });

})();