var active_uploads = 0;
jQuery(document).ready(function() {
	if(jQuery('#sign_quantity').attr('name') != undefined && jQuery('#sign_cost_each').attr('value') > 0) {
		jQuery('#sign_cost').html('= $0.00');

		jQuery('#sign_quantity').bind('change', function() {
			var total = jQuery(this).attr('value') <= 1 ? 0 : (jQuery(this).attr('value')-1) * jQuery('#sign_cost_each').attr('value');
			total = total.toFixed(2);
			jQuery('#sign_cost').html('= $'+total);
		});
	}

	if(jQuery('form[@name="listing"]').attr('name') != undefined) {
		// Remove extra upload field if more than one
		if(jQuery('div.image-upload').length > 1) {
			jQuery('div.image-upload:last').remove();
		}
	
		// Enable upload preview image
		jQuery('div.image-upload .image-preview:hidden').css('display', 'block');
	
		// Allow multiple image uploads
		jQuery('#add-image').html('<a class="add-image" href="javascript: void(0);" onclick="addFileUploadField();">Add an Image</a>');
	
		// Setup mailing city and state
		if(jQuery('#mailing_postal_code').attr('value') == '') {
			jQuery('#city_state').html('Waiting for postal code...');
		} else {
			fetchCityState(jQuery('#mailing_postal_code').attr('value'));
		}
	
		// Setup postal code handler
		jQuery('#mailing_postal_code').bind('keyup', function(e) {
			var key = e.charCode || e.keyCode || 0;
			if((key >= 48 && key <= 57) /* top numbers */ || (key >= 96 && key <= 105) /* num pad */ || key == 8 /* backspace */ || key == 46 /* delete */) {
				fetchCityState(this.value);
			}
	
			return true;
		});

		// Make sure image uploads have completed on submit and 
		// Change form enctype so uploads are only done via ajax 
		// and not also on post
		jQuery('form[@name="listing"]').bind('submit', function() { 
			if(active_uploads > 0) {
				alert("Notice:\nPlease wait while all image uploads complete...");
				return false;
			}
		
			return true;
		}).attr('enctype', 'application/x-www-form-urlencoded');
	}
});
function ajaxFileUpload(el_id) {
	active_uploads += 1;
	jQuery('#preview-'+el_id).attr('alt', 'Uploading...').parents('span').addClass('loading');

	jQuery.ajaxFileUpload({
		url: '/member/json.file-upload.html',
		secureuri: false,
		fileElementId: el_id,
		dataType: 'json',
		success: function (data, status) {
			active_uploads -= 1;
			if(typeof(data.error) != 'undefined') {
				if(data.error != '') {
					jQuery('#preview-'+el_id).fadeTo('fast', 0.01, function() {
					   jQuery(this).parents('span').removeClass('loading');
						jQuery(this).attr('alt', 'Placeholder').fadeTo('slow', 1, function() {
							alert("Notice:\n"+data.error);
						});
					});
				} else {
					jQuery('#selected-'+el_id).attr('value', data.file_name);
					jQuery('<img>').attr('src', data.file_path).bind('load', function() {
						jQuery('#preview-'+el_id).fadeTo('fast', 0.01, function() {
							jQuery(this).parents('span').removeClass('loading');
							jQuery(this).attr('src', data.file_path).attr('width', '150').attr('alt', data.file_name).fadeTo('slow', 1);
						});
					});
				}
			}
		},
		error: function (data, status, e) {
			active_uploads -= 1;
			alert("Error\n"+e);
		}
	})
	return false;
}
function ajaxFileDelete(index) {
	if(jQuery('#images .image-upload').length == 1 && jQuery('#selected-img'+index).attr('value') == '') {
		return false;
	}

	if(jQuery('#selected-img'+index).attr('value') == '') {
		jQuery('#img'+index).animate({height:0, opacity:0}, 500, function() { 
			jQuery(this).remove();
		});

		return true;
	}

	if (confirm("Notice:\nAre you sure you want to delete this file? This action cannot be undone.")) {
		var file_name 	= jQuery('#selected-img'+index).attr('value');
		var type		= jQuery('#type-img'+index).attr('value');
		var listing_id	= jQuery('#listing_id').attr('value') == undefined ? 0 : jQuery('#listing_id').attr('value');

		jQuery.getJSON('/member/json.delete-file-upload.html', {file_name: file_name, type: type, listing_id: listing_id}, function(data) {
			if(data.status == false) {
				alert("Error:\n"+((data.error != undefined || data.error != '') ? data.error : 'Unknown error'));
				return false;
			} else {
				jQuery('#img'+index).animate({height:0, opacity:0}, 500, function() { 
					jQuery(this).remove();

					if(jQuery('#images > .image-upload').length == 0) {
						addFileUploadField();
					}
				});
			}
		});
	}

	return true;
}
function addFileUploadField(fields_to_add) { 
	fields_to_add = fields_to_add == undefined ? 1 : fields_to_add;
	jQuery('#add-image a').addClass('loading').html('Loading...');
	jQuery.getJSON('/member/json.get_file_upload_html.html', {fields_to_add: fields_to_add}, function(data) {
		if(!data.status) {
			alert("Error:\n"+((data.error != undefined && data.error != '') ? data.error : 'An unknown error occurred. Please try again.'));
			return false;
		}

		jQuery('#add-image').before(data.html);
		jQuery('#images div.image-upload:last').fadeTo(0, 0).animate({height: '120px', opacity: 1}, 1000, function() { 
			jQuery(this).css('display', 'block');
			jQuery('#add-image a').removeClass('loading').html('Add an image');
		});

		return true;
	});
}
function fetchCityState(postal_code) { 
	if(postal_code.length == undefined) {
		return;
	}

	switch(postal_code.length) {
		default :
			jQuery('#city_state').html('Waiting for postal code...');
			return false;
		break;
		case 5 :
			jQuery('#city_state').html('Loading...');

			jQuery.getJSON('member/json.get-city-state.html', {postal_code: postal_code}, function(data) { 
				if(data.found == 'false') { 
					jQuery('#city_state').html('Invalid (or unknown) postal code. Please try again.');
				} else {
					jQuery('#city_state').html(data.city+', '+data.state);
				}
		
				return true;
			});
		break;
	}
}