$(document).ready(function() { 

    // Generate 32 char random uuid 
    function gen_uuid() {
        var uuid = ""
        for (var i=0; i < 32; i++) {
            uuid += Math.floor(Math.random() * 16).toString(16); 
        }
        return uuid
    }

    /*
        Demo Movie specific
    */
    $("div#upload_form form:not(.first_select) input[name=movie]").change(function(){
        $("div#upload_form form").submit();
    });

    // Add upload progress for multipart forms.
    $('form#movie-upload').submit(function(){ 
        
        // Make sure we have a file
        var movieInput = $("input[name=movie]", this);
        if (movieInput.length && !movieInput.val())
        {
            alert('Välj en film att ladda upp.') 
            return false;
        }
        else
        {
            $(this).fadeTo(200, 0.5);
            $('div#progress').show(0);
        }
        
        // Prevent multiple submits
        if ($.data(this, 'submitted')) return false;

        var uuid = gen_uuid(),
            progress_url = '/upload/progress/',
            updateFrequency = 1000,
            updateProgressInfo = function() {        
                $.ajax({
                    async: false,
            		type: "GET",
            		url: progress_url,
            		dataType: "json",
            		beforeSend: function(xhr) {
            			xhr.setRequestHeader("X-Progress-ID", uuid);
            		},
            		success: function(upload) {
    
            			// change the width if the inner progress-bar *
            			if (upload.state == 'uploading') {
            			    var progress = "" + Math.floor((upload.received / upload.size) * 100)  + "%";
        			        
        			        // Update width
        			        $('div#progress div.label')
        			            .text(progress)
        			            .animate({'width': progress}, 200);
            			}
        			
            			// Start another timeout
            			if (upload.state != 'done')
            			    setTimeout(updateProgressInfo, updateFrequency);
            		},
            		error: function (XMLHttpRequest, textStatus, errorThrown) {
            		}
            	});
            };
        
        // Append X-Progress-ID uuid form action
        this.action += (this.action.indexOf('?') == -1 ? '?' : '&') + 'X-Progress-ID=' + uuid;
        
        // Start the initial timeout
        setTimeout(updateProgressInfo, updateFrequency);
        
        // Disable submit button
        $('input[type=submit], button', this).attr('disabled', 'disabled');
        
        $.data(this, 'submitted', true); // mark form as submitted.
    });

});
