
function backgroundResize() {
    var $$ = $('img').slice(0);
    var wh = $(window).height();
    var ww = $(window).width();
    var bh = $$.height();
    var bw = $$.width();
    if( wh > bh ) {
        $$.css({'width':'auto', 'height':'100%'});
    }
    else if( ww > bw) {
        $$.css({'width':'100%', 'height':'auto'});
    }
}

$(function() {

});


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

$(function() {
    // Add upload progress for multipart forms.
    $('form[@enctype=multipart/form-data]').submit(function(){ 
        // First make sure we're actually uploading something.
        var has_upload_data = false;
        var $inputs = $('input[@type=file]',this).each(function() {
            if (this.value) has_upload_data = true;
        });
        if (!has_upload_data) return true;

        // Prevent multiple submits
        if ($.data(this, 'submitted')) return false;

        var freq = 5000; // freqency of update in ms
        var id = gen_id(); // id for this upload so we can fetch progress info.
        var progress_url = '/admin/upload_progress/'; // ajax view serving progress info

        // Append X-Progress-ID id form action
        this.action += (this.action.indexOf('?') == -1 ? '?' : '&') + 'X-Progress-ID=' + id;
        
        var $progress = $('<div id="upload-progress" class="upload-progress"></div>').
            appendTo($inputs.slice(0,1).parent()).append('<div class="progress-container"><span class="progress-info">uploading 0%</span><div class="progress-bar"></div></div>');
        
        // progress bar position
        $progress.show();

        // Update progress bar
        function update_progress_info() {
            $progress.show();
            $.getJSON(progress_url, {'X-Progress-ID': id}, function(data, status){
                if (data) {
                    var progress = parseInt(data.uploaded) / parseInt(data.length);
                    var width = $progress.find('.progress-container').width()
                    var progress_width = width * progress;
                    $progress.find('.progress-bar').width(progress_width);
                    $progress.find('.progress-info').text('uploading ' + parseInt(progress*100) + '%');
                }
                window.setTimeout(update_progress_info, freq);
            });
        };
        window.setTimeout(update_progress_info, freq);

        $.data(this, 'submitted', true); // mark form as submitted.
    });
});


