var nullFails = 0;
var stopped = false;

function microtime(get_as_float) {
    // discuss at: http://phpjs.org/functions/microtime
    var now = new Date().getTime() / 1000;
    var s = parseInt(now, 10);
    return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
}

function extension(filename) 
{ 
	var dot = filename.lastIndexOf("."); 
	if( dot == -1 ) return filename;
	var ext = filename.substring(dot);
	return ext;
}

$.fn.insertAlert = function()
{
	return this.each(function(){
		var html = $(this).clone();

		if ( $('#TB_ajaxContent .alert').length == 0 )
		{
		 	$(html).insertBefore('#uploadForm');
		}
		else
		{
		 	$('#TB_ajaxContent .alert:first').replaceWith(html);
		}
	});
}

function formReset()
{
	$('#uploadProgress').css('background-position', '-300px 0');
	
	$('#uploadFile').val('');

	$('#uploadForm :submit')
	.val('Start upload')
	.removeAttr('disabled');
	
	nullFails = 0;
}


function __tick()
{
	$.ajax({
		type: "GET",
		url: '/upload/progress?UPLOAD_IDENTIFIER=' + $('#uploadIdentifier').val(),
		dataType: "script"
	});
}

// Called by the server
function __update (identifier, data) 
{
	if ( stopped == true ) return;
	
	if (data == null || data['bytes_uploaded'] == data['bytes_total'] ) 
	{
		if (data == null) 
		{
			nullFails = nullFails + 1;
			if (nullFails < 3)
			{
				setTimeout('__tick("' + identifier + '")', 500);
			}
			else 
			{
				nullFails = 0;
			}
		} 
				
		return;	
	}
	
	// file too large
	if ( data['bytes_total'] > ($('#s').val()*Math.pow(10,6)) )
	{
		$('<div class="alert bad"><p>The file you are trying to upload is too large. Please choose a different file.</p></div>')
		.insertAlert();

		onCancel();

		return false;
	}
	else
	{
		$('.alert').remove();
	}
	
	setTimeout('__tick("' + identifier + '")', 1000);
	onUpdate(identifier, data);
} // __update

// Default callback - updates a progress bar
function onUpdate(identifier, data) 
{
	if ( null != data && nullFails < 3)
	{
		var percent = Math.floor(data['bytes_uploaded'] * 100 / data['bytes_total']);
		$('#uploadProgress').css('background-position', '-' + (300 - (percent * 3)) + 'px 0');

		// remove path for ie
		var fileName = data.filename;
		if ( fileName.indexOf('\\') != -1 ) // needs to be escaped
		{
			var aFileName = fileName.split('\\');
			fileName = aFileName[aFileName.length - 1];
		}

		if ( fileName.length > 47 ) fileName = fileName.substring(0, 47) + '...';

		$('#uploadInfo').html(
			'<b><span id="uploadPercent">' + percent + '</span>% of ' + fileName + ' uploaded.</b><br />'
			+ '<span id="bytes_uploaded">' + Math.round((data.bytes_uploaded/1000000)*100)/100 + '</span>Mb of '
			+ '<span id="bytes_total">' + Math.round((data.bytes_total/1000000)*100)/100 + '</span>Mb'
		);
	}
}

function onComplete()
{
	if ( stopped == true ) return;
	
	stopped = true;
	$('#uploadPercent').text('100');
	$('#uploadProgress').css('background-position', '0px 0');
	$('#bytes_total').text( $('#bytes_uploaded').text() );
	
	var alerts = $('#uploadIframe').contents().find('.bad');

	// if no bad alerts, reload
	if ( $(alerts).length == 0 )
	{
		window.location.reload(true);

		return;
	}

	$('#uploadForm').show();
	$('#uploadStatus').hide();

	$(alerts).insertAlert();
	formReset();
	
	// for tb instance
	$('#TB_closeAjaxWindow').removeClass('invisible');
}

function onCancel()
{
	stopped = true;
	$('#uploadIdentifier').val(microtime(true)*1000);
	$('#uploadForm').insertBefore('#uploadStatus');
	$('#uploadIframe')
	.insertAfter('#uploadStatus')
	.attr('src', 'about:blank');
	formReset();
	
	$('#uploadForm').show();
	$('#uploadStatus').hide();
	
	$('#TB_closeAjaxWindow').removeClass('invisible');
}

$(document).ready(function(){

	if ($('#uploadIframe').length == 0 )
	{
		$('<iframe name="uploadIframe" id="uploadIframe" src="about:blank"></iframe>')
		.insertAfter('#uploadStatus');
		
		$('#uploadForm').attr('target', 'uploadIframe');
	}
	
	$('#uploadForm :submit').live('click', function()
	{
		$.get("/upload/close");
		
		if ( '' == $('#uploadFile').val() )
		{
			$('<div class="alert bad"><p>Please choose a file.</p></div>')
			.insertAlert();
			
			return false;
		}

		var exts = $('#t').val();
		var aExts = exts.split(',');

		var ext = extension( $('#uploadFile').val() );

		var match = false;
		for ( var i in aExts )
		{
			if (ext == aExts[i] ) match = true;
		}
		
		if ( match == false )
		{
			$('<div class="alert bad"><p>Sorry, we don\'t allow that kind of file. We allow these types of files: ' + exts + '.</p></div>')
			.insertAlert();

			return false;
		}

		
		// for tb instance	
		$('#TB_overlay').unbind('click');
		$('#TB_closeAjaxWindow').addClass('invisible');

		$(this)
//		.attr('disabled', 'disabled')
		.val('Uploading...');
		
		$('#uploadForm')
		.unbind('submit')
		.submit(function(){
			setTimeout('__tick()', 1000);
			$('.alert').remove();
			stopped = false;
			
			$('#uploadInfo').text('Starting the upload...');
			$('#uploadProgress')
			.css('background-position', '-300px 0');
			
			$('#uploadForm').hide();
			$('#uploadStatus').show();
		});

		$('#uploadIframe')
		.unbind('load')
		.load(function(){
			onComplete();
		});

		// disabled button doesn't submit the form on ie
//		if ( $.browser.msie ) $('#uploadForm').submit();
	});

	$('.cancel').live('click', function(){
		$('<div class="alert"><p>We cancelled your upload.</p></div>')
		.insertAlert();

		onCancel();
	});
});