
 
window.onload = function() {
  if (!window.google || !google.gears) {
    addStatus('Gears is not installed', 'error');
    return;
  }
}

var CHUNK_BYTES		= 200000; 	// Send file in packets of 200KB
var MAX_FILE_SIZE	= 100000000;	// Limit the total upload size to 100MB
var UPLOAD_RETRIES	= 3;		// Number of retries
var mylist		= {}; 		// Array of file and properties
var fileName		= "";		// Index of mylist that is being processed

/**
 * Display information to the client
 */
function addStatus(s){ $("status").innerHTML +=  s + "<br />"; return 1;}

/**
 * Get the minimum of two results.
 */
function min(a,b){ return (a<b?a:b); }

/**
 * Open file browser window
 */
function browse(){
	var desktop = google.gears.factory.create('beta.desktop');
	desktop.openFiles( function(files) {
		
		for ( var i = 0; i < files.length; i++ )
		{
			if ( mylist[files[i].name] ){ continue; } // Has the file by the same name already been selected?
			
			mylist[files[i].name] = {
				filename:	files[i].name, 
				uploaded:	0,
				length: 	files[i].blob.length, 
				blob:		files[i].blob, 
				bytesUploaded: 0,
				status:		(files[i].blob.length>MAX_FILE_SIZE?"File too large":"Pending")};
			
			addStatus( "Selected: " + files[i].name + " " + files[i].blob.length );
		}
		setTimeout("uploadAll();", 500);
		$('upload').innerHTML = ('<a href="#upload" onclick="return uploadAll();">Uploading...</a>');
	},
    {  }
    //  { singleFile: true }
	);
}

function uploadAll() {
	upload();
	hasChunk = false;
	for ( file in mylist ) if ( ( mylist[file].uploaded < mylist[file].length && !mylist[file].error ) ) {
		hasChunk = true;
	}

	if (hasChunk == true) {
		setTimeout("uploadAll();", 20000);
	}

	if (hasChunk == false) {
		$('upload').innerHTML = "";		
	}
}

function upload()
{
	var chunkLength, chunk;

	/**
	 * Loop through the files and upload the next file/chunk
	 */

	for ( file in mylist ) if ( ( mylist[file].uploaded < mylist[file].length && !mylist[file].error ) )
	{
		/**
		 * what is the current filename
		 */
		fileName = file;
		chunkLength = min( mylist[file].uploaded + CHUNK_BYTES, mylist[file].length);
//		addStatus( "Uploading " + fileName + ": from " + mylist[file].uploaded + " to " + chunkLength );

		/**
		 * Get the next chunk to send.
		 */
		chunk = mylist[file].blob.slice( mylist[file].uploaded, (chunkLength - mylist[file].uploaded) );
//		addStatus( "Chunk length " + chunk.length );
		
		/**
		 * Send Chunk
		 */
		sendChunk( mylist[file], chunk, mylist[file].uploaded, chunkLength, mylist[file].length );
		break;
	}
}


function sendChunk ( entry, chunk, start, end, total )
{
	var req = google.gears.factory.create('beta.httprequest');
	var prcnt = Math.ceil( ( end/total ) * 100 );
	/**
	 * Start Post
	 */
	req.open('POST', '?n='+encodeURIComponent(fileName)+'&b='+encodeURIComponent(start) );

	/**
	 * Assign Headers
	 */
	var h = { 'Content-Disposition'	: 'attachment; filename="' + fileName + '"', 
					'Content-Type' 	: 'application/octet-stream',
					'Content-Range'	: 'bytes ' + start + '-' + end + '/' + total };
	
	for( var x in h ) if (h.hasOwnProperty(x)) { req.setRequestHeader( x, h[x] ); }
	
	/**
	 * Build Response function
	 */
	req.onreadystatechange = function(){
		if (req.readyState == 4 && req.status == 200 ) {
			entry.uploaded = end;
			addStatus( fileName + ( (end + 1) >= total ? " Finished" : ' Upload: so far ' + prcnt + '%' ) );
			setTimeout("uploadAll()", 500);
			//upload();
		} else {
			if (req.status != 200) {
				addStatus( "WARNING: Resp (" + req.status + ")" )
			}
		}
	}

	/**
	 * Send Chunk
	 */
	req.send(chunk);
}



