var ckEditors = new Array();

function formUpdateProgress() {
	// Chrome won't allow ajax while submitting form :(
	var isWebkit = navigator.userAgent.indexOf('AppleWebKit') > -1;
	if( isWebkit ) { return; }

	var id = $('#progress_key').attr('value');
	$.ajax({
		url: '/mod/form/upload-progress.php?id='+id,
		dataType: 'json',
		success: function(response) { 
			setTimeout('formUpdateProgress()', 1000);
			if( !response ) { return; }

			if( $('#progressOuter').is(':hidden') ) {
				$('#progressOuter').fadeIn();
			}

			var maxBytes = parseInt($('input[name="MAX_FILE_SIZE"]').attr('value'));
			if( maxBytes > 0 && parseInt(response['total']) > maxBytes ) {
				alert("Your upload is too large. It must be less than " 
					+ Math.round(maxBytes/1000/1000) + 'MB. Please try again.');
				location.reload();
			}
			var percentage = Math.floor(100 * parseInt(response['current']) / parseInt(response['total']));
			$('#progressInner').css('width',percentage+'%');
			if( response['est_sec'] > 0 ) {
				$('#progressStatus').html('About <b>' + formatTime(response['est_sec']) + '</b> remain...');
				$('input[type="submit"]').attr('disabled','true');
			}
		}
	});
}

function formatTime(secs) {
	if( secs < 60 ) {
		return secs + ' seconds';
	} else if( secs < 60*60 ) {
		return Math.round(secs/60) + ' minutes and ' + (secs%60) + ' seconds';
	} else {
		return Math.round(secs/60/60) + ' hours and ' + Math.round((secs/60)%60) + ' minutes';
	}
}

$(document).ready(function() {
	$('.formCalendar').datepicker({
		'dateFormat': 'yy-mm-dd',
		'changeMonth': true,
		'changeYear': true
	});

	$('.dateRange').each(function() {
		var dates = $(this).find('.date').datepicker({
			'dateFormat': 'yy-mm-dd',
			'changeMonth': true,
			'changeYear': true,
			'onSelect': function( selectedDate ) {
				var option = $(this).hasClass('start') ? "minDate" : "maxDate",
					instance = $( this ).data( "datepicker" ),
					date = $.datepicker.parseDate(
						instance.settings.dateFormat ||
						$.datepicker._defaults.dateFormat,
						selectedDate, instance.settings );
				eLog(dates);
				eLog(option);
				eLog(instance);
				eLog(date);
				dates.not( this ).datepicker( "option", option, date );
			}
		});
	});

	$('.eform').submit(function() {
		var success = verifyForm(this);
		if( !success ) { return false; }


			formUpdateProgress();

		return true;
	});
});





























function verifyForm(f) {
	var foundError = false;
	$(f).find('input[validation="required"],textarea[validation="required"]').each(function() {
		if( foundError || $(this).val() != '' ) { return; }
		alert($("label[for=\""+$(this).attr('name')+"\"]").text() + " Field is required.");
		$(this).focus();
		foundError = true;
	});
	return !foundError;
}


/* end validation stuff */

