﻿var form_upload_setup = false;

function setupUploads() {
    $('#upload_section .upload_region').each(function() {
        var me      = $(this);
        var text    = me.attr('value');
        var section = me.attr('section');
        var ticket  = me.attr('ticket');

        var checkUrl = window.location.pathname + "?Check=1";

        me.uploadify({
            'uploader'      : 'Scripts/Upload/uploadify.swf',
            'cancelImg'     : 'Scripts/Upload/cancel.png',
            'script'        : window.location.pathname + window.location.search,
            'checkScript'   : checkUrl,
            'folder'        : ticket,
            'fileDesc'      : 'Any document (*.doc, *.docx*, *.txt, *.rtf)',
            'fileExt'       : '*.doc;*.docx;*.txt;*.rtf',
            'multi'         : true,
            'auto'          : true,
            'sizeLimit'     : 5 * (1024 * 1024),
            'buttonText'    : text,
            scriptData: { 'section': section },
            onComplete: function() {
                return false;
            },
            onError: function(event, queueId, fileObj, errorObj) {
                if (console != null)
                    console.log(errorObj.info);
                else
                    alert(errorObj.info);
            },
            onAllComplete: function(filesUploaded, errors, allBytesLoaded, speed) {
                $.post(window.location.pathname + window.location.search, { 'retrieve_documents': section }, function(data) {
                    me.parent().find('.uploadifyQueue').each(function() {
                        if ($(this).attr('id').length == 0)
                            $(this).remove();
                    });
                    me.parent().find('.uploadifyQueue:first').html('').after(data);

                    $('.delete_button').click(deletebtn_action);
                }, "html");
            }
        });
    });

    $('.delete_button').click(deletebtn_action);
    
    if (!form_upload_setup) {
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(setupUploads);
        form_upload_setup = true;
    }
}

function deletebtn_action() {
    if (!confirm("Are you sure you want to delete this file?"))
        return;

    var me  = $(this);
    var id  = me.attr('surveyid');
    var url = window.location.pathname + window.location.search;

    $.post(url, { "delete_file": id }, function() {
        me.parents('.uploadifyQueueItem').remove();
    });
}

$(setupUploads);