/*
 * Asynchronous Files Uploader 0.8
 *
 * Requires:    jQuery 1.4.2 or newer
 *              jQuery Form plugin 2.43 or newer
 */

/**
 * EXAMPLE:
 *
 * CLIENT SIDE
 */
//<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
//<html>
//    <head>
//        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
//        <title></title>
//        <script type="text/javascript" src="jquery-1.4.2.js"></script>
//        <script type="text/javascript" src="jquery.form.js"></script>
//        <script type="text/javascript" src="jquery.afu.js"></script>
//        <style type="text/css" >
//            .uploader {
//                display: block;
//                margin: 0.5em;
//            }
//            .uploading {
//                list-style-image: URL('ajax-loader.gif')
//            }
//            .uploaded {
//                list-style-image: URL('check-mark.png')
//            }
//        </style>
//    </head>
//    <body>
//        <fieldset>
//            <legend>Asynchronous Files Uploader</legend>
//            <form action="upload.php" method="post" enctype="multipart/form-data">
//                <input type="hidden" name="MAX_FILE_SIZE" value="5000000" />
//                <input type="file" name="uploader" class="uploader" />
//            </form>
//        </fieldset>
//        <script type="text/javascript">
//            //inicialization
//            $(document).ready(function() {
//                $('.uploader').change(function() {
//                    $(this).upload();
//                });
//            });
//        </script>
//    </body>
//</html>

/**
 * SERVER SIDE
 */
//<?php//
//$payload = array('inputIndex' => '', 'fileName' => '');
//
//if (isset($_FILES) && is_array($_FILES)) {
//
//    $keys = array_keys($_FILES);
//
//    if (isset($_POST['inputIndex']) && $keys[0]) {
//        $payload['inputIndex'] = $_POST['inputIndex'];
//
//        if (isset($_FILES[$keys[0]]['name'])) {
//            $payload['fileName'] = $_FILES[$keys[0]]['name'];
//        }
//    }
//}
//// check if request was sent by AJAX
//if (isset($_REQUEST['method']) && ($_REQUEST['method'] === 'ajax')) {
//    header('Content-Type: text/plain; charset=utf-8');
//    echo json_encode($payload);
//}
//?>

/**
 * You may use settings:
 */
//{
//classUploading: "yourClassUploading",
//classUploaded: 'yourClassUploaded',
//translationUploading: 'yourTranslationUploading: ',
//translationUploaded: 'yourTranslationUploaded: ',
//outputContainer: $('#output-container')
//}

(function($){
    $.fn.extend({
        isDefined: function(variable) {
            return !(variable === undefined);
        }
    });
})(jQuery);

/**
 * Returns output container as jQuery object
 */
function getOutputContainer(fileInput) {

    var containerId = 'uploader-output-container';
    
    var container = $("ul#" + containerId);
    
    if (container.length == 0) {
        container = jQuery(document.createElement('ul'));
        container.attr('id', containerId);
        fileInput.parent().prepend(container);
    }
    return container;
}

/**
 * Returns action form as jQuery object
 */
function createForm(form, fileInput, inputIndex) {
    var newForm = jQuery(document.createElement('form'));
    newForm.attr('action', form.attr('action'));
    newForm.attr('method', 'post');
    newForm.attr('enctype', 'multipart/form-data');
    newForm.attr('id',  'afu-uploader-form-' + $.fn.upload.indexInput);

    newForm.hide();
    
    $('body').append(newForm);
    
    if ($.fn.upload.settings.sendWholeForm) {
        
        $(':input', form).each(function() {
            if (    ($(this).attr('class') != 'afu-uploader') &&
                ($(this).attr('type') != 'file') &&
                ($(this).attr('type') != 'submit')) {
                $(this).clone().appendTo(newForm);
            }

            if ($(this).attr('type') == 'text') {
                $(this).val('');
            }

        });
    }


	fileInput.attr('id', '').attr('class', '');
    newForm.append(fileInput);

    newForm.ajaxForm({
        dataType:  'json',
        success:   $.fn.upload.settings.success,
        data: {
            method: 'ajax',
            inputIndex: inputIndex
        }
    });

    return newForm;
}


(function($){
    $.fn.extend({
        upload: function(settings, event) {

            var defaultSettings = {
                classUploading: "afu-uploading",
                classUploaded: 'afu-uploaded',
                classError: 'afu-error',
                translationUploading: 'Uploading: ',
                translationUploaded: 'Uploaded: ',
                translationError: 'Error: ',
                outputContainer: getOutputContainer($(this)),
                sendWholeForm: false,
				success: processAFUUploader
            };
            
            settings = $.extend(defaultSettings, settings);

            // set static variable
            $.fn.upload.settings = settings;

            var form = $(this).parents('form');
            
            // set index of input
            if ($.fn.isDefined($.fn.upload.indexInput)) {
                $.fn.upload.indexInput++;
            } else {
                $.fn.upload.indexInput = 0;
            }

            var container = settings.outputContainer;
            
            //create new input
            var newInput = jQuery(document.createElement("input"));
            newInput.attr('type', 'file');
            newInput.attr('name', $(this).attr('name'));
            newInput.attr('class', $(this).attr('class'));
            newInput.attr('id', $(this).attr('id') + $.fn.upload.indexInput);


            var coverId = 'afu-uploader-cover-' + $.fn.upload.indexInput;

            //create container for image and text
            var cover = jQuery(document.createElement('li'));
			var fileName = $(this).val();
			fileName = fileName.substring(Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\')) + 1);
            cover.text(settings.translationUploading + fileName);
            cover.attr('id', coverId);
            cover.attr('class', settings.classUploading)
            container.prepend(cover);

            $(this).after(newInput);

            var actionForm = createForm(form, $(this), coverId);

            if (event) {
				var firedElement = jQuery(event.target);

				firedElement.unbind(event.type);

				firedElement.bind(event.type, function() {
					newInput.upload(event, settings);
				});
			}

            actionForm.submit();
        }
    })
})(jQuery);

//process data from server
function processAFUUploader(data, status, xhr, form) {

    form.remove();

    //authentification failed
    if (data.status == 2) {

//        alert(data.message);

    } else {


        //empty container
        var cover = $('#' + data.inputIndex);
        cover.html('');

        var message = '';

        if (data.message != '') {
            message = ' ' + data.message;
        }

        if (data.status == 0) {
            cover.text($.fn.upload.settings.translationUploaded + data.fileName + message);
            cover.attr('class', $.fn.upload.settings.classUploaded);
        } else {
            cover.text($.fn.upload.settings.translationError + data.fileName + message);
            cover.attr('class', $.fn.upload.settings.classError);
        }
    }
}

