 // Put jQuery in compatibility mode (so it will work together with other js libraries)
 var $j = jQuery.noConflict();

// Uploadify file upload plug-in initialization and settings
var swfu;

$j(document).ready(function() {

//    $j(function(){
//        $j('#swfupload-control').swfupload({
    var settings = {
        upload_url: base_url+'upload/process/',
        flash_url : base_url+'vendor/jquery.swfupload/swfupload/swfupload.swf',
        flash9_url : base_url+'vendor/jquery.swfupload/swfupload/swfupload_fp9.swf',
        file_post_name: 'customer_file',
        file_size_limit : "200 MB",
//        file_types : "*.jpg;*.png;*.gif",
        file_types : '*.*',
        file_types_description : "All Files",
        file_upload_limit : 5,
        debug: false,
        // Button settings
        button_image_url : base_url+'images/upload-button-submit-states.png',
        button_width : 250,
        button_height : 31,
        button_placeholder : $j('#customer_file')[0],
        button_disabled : false,
        button_cursor : SWFUpload.CURSOR.HAND,
        button_window_mode: 'opaque',
        // Handlers
        file_queued_handler : fileQueued,
        file_queue_error_handler : fileQueueError,
        file_dialog_complete_handler: fileDialogComplete,
        upload_start_handler: uploadStart,
        upload_progress_handler: uploadProgress,
//        upload_error_handler: uploadError,
        upload_success_handler: uploadSuccess,
        upload_complete_handler: uploadComplete,
        queue_complete_handler : queueComplete // Queue plugin event

    };

    swfu = new SWFUpload(settings);

//        })
//            .bind('fileQueued', function(event, file){
//                var listitem='<li id="'+file.id+'" >'+
//                    'File: <em>'+file.name+'</em> ('+Math.round(file.size/1024)+' KB) <span class="progressvalue" ></span>'+
//                    '<div class="progressbar" ><div class="progress" ></div></div>'+
//                    '<p class="status" >待機</p>'+
//                    '<span class="cancel" >&nbsp;</span>'+
//                    '</li>';
//                $j('#log').append(listitem);
//                $j('li#'+file.id+' .cancel').bind('click', function(){ //Remove from queue on cancel click
//                    var swfu = $j.swfupload.getInstance('#swfupload-control');
//                    swfu.cancelUpload(file.id);
//                    $j('li#'+file.id).slideUp('fast');
//                });
                // re-set the upload url, adding a query string with the form data
//                $j(this).swfupload('setUploadURL', base_url+'upload/process/?'+$j('#upload_form').serialize());
                // start the upload since it's queued
//                $j(this).swfupload('startUpload');
//            })
//            .bind('fileQueueError', function(event, file, errorCode, message){
//                alert('選択されたファイル（'+file.name+'）のファイルサイズが大きすぎます。\n200MBまでのファイルをアップロードできます。');
//            })
//            .bind('fileDialogComplete', function(event, numFilesSelected, numFilesQueued){
//                $j('#queuestatus').text('Files Selected: '+numFilesSelected+' / Queued Files: '+numFilesQueued);
//            })
//            .bind('uploadStart', function(event, file){
//                $j('#log li#'+file.id).find('p.status').text('アップロード中...');
//                $j('#log li#'+file.id).find('span.progressvalue').text('0%');
//                $j('#log li#'+file.id).find('span.cancel').hide();
//            })
//            .bind('uploadProgress', function(event, file, bytesLoaded){
                //Show Progress
//                var percentage=Math.round((bytesLoaded/file.size)*100);
//                $j('#log li#'+file.id).find('div.progress').css('width', percentage+'%');
//                $j('#log li#'+file.id).find('span.progressvalue').text(percentage+'%');
//            })
//            .bind('uploadSuccess', function(event, file, serverData){
//                var item=$j('#log li#'+file.id);
//                item.find('div.progress').css('width', '100%');
//                item.find('span.progressvalue').text('100%');
//                var pathtofile='<a href="uploads/'+file.name+'" target="_blank" >view &raquo;</a>';
//                item.addClass('success').find('p.status').html('アップロード終了！');
//            })
//            .bind('uploadComplete', function(event, file){
                // upload has completed, try the next one in the queue
//                $j(this).swfupload('startUpload');
//            })
//            .bind('queueComplete', function(uploadCount){
                // all uploads in the queue have finished, display a success message
//                alert('ファイルアップロード無事に終了しました！');
//            })
//    });

});

function fileQueued (file){
    var listitem='<li id="'+file.id+'" >'+
        'File: <em>'+file.name+'</em> ('+Math.round(file.size/1024)+' KB) <span class="progressvalue" ></span>'+
        '<div class="progressbar" ><div class="progress" ></div></div>'+
        '<p class="status" >待機</p>'+
        '<span class="cancel" >&nbsp;</span>'+
        '</li>';
    $j('#log').append(listitem);
    $j('li#'+file.id+' .cancel').bind('click', function(){ //Remove from queue on cancel click
        swfu.cancelUpload(file.id);
        $j('li#'+file.id).slideUp('fast');
    });
    // re-set the upload url, adding a query string with the form data
    swfu.setUploadURL(base_url+'upload/process/?'+$j('#upload_form').serialize());
    // start the upload since it's queued
    swfu.startUpload();
    // Block the user from interacting with the page while the uploading is in progress
    $j.blockUI({
        fadeIn: 700,
        fadeOut: 400,
        message: '<span class="loading">アップロード中...<br><img src="'+base_url+'images/loading-bar.gif" /><br>しばらくお待ちください。</span>',
        css: { border: '3px solid #B3B3B3', cursor: 'wait' },
        overlayCSS:  { backgroundColor: '#000', opacity: 0.5, border: '2px solid #999999', cursor: 'wait' },
        baseZ: 99999999999
    });
}

function fileQueueError(file, errorCode, message){
    alert('選択されたファイル（'+file.name+'）のファイルサイズが大きすぎます。\n200MBまでのファイルをアップロードできます。');
}

function fileDialogComplete(numFilesSelected, numFilesQueued){
    $j('#queuestatus').text('Files Selected: '+numFilesSelected+' / Queued Files: '+numFilesQueued);
}

function uploadStart(file){
    // Set the status to "uploading"
    $j('#log li#'+file.id).find('p.status').text('アップロード中...');
    $j('#log li#'+file.id).find('span.progressvalue').text('0%');
    $j('#log li#'+file.id).find('span.cancel').hide();
}

function uploadProgress(file, bytesLoaded){
    // Show Progress
    var percentage=Math.round((bytesLoaded/file.size)*100);
    $j('#log li#'+file.id).find('div.progress').css('width', percentage+'%');
    $j('#log li#'+file.id).find('span.progressvalue').text(percentage+'%');
}

function uploadSuccess(file, serverData){
    var item=$j('#log li#'+file.id);
    item.find('div.progress').css('width', '100%');
    item.find('span.progressvalue').text('100%');
    var pathtofile='<a href="uploads/'+file.name+'" target="_blank" >view &raquo;</a>';
    item.addClass('success').find('p.status').html('アップロード終了！');
}

function uploadComplete(file){
    // upload has completed, try the next one in the queue
    swfu.startUpload();
}

function queueComplete(uploadCount){
    // Unblock the page
    $j.unblockUI({
        onUnblock: function(){
            // all uploads in the queue have finished, display a success message
            // alert('ファイルアップロード無事に終了しました！');
            // Redirect to the home page
            window.location = base_url+'upload/success';
        }
    });
}

// This is fired when the UI is unblocked
function allFinished(element, options){
    // all uploads in the queue have finished, display a success message
    alert('ファイルアップロード無事に終了しました！');
    // Redirect to the home page
    window.location = base_url;
}
