// Project image manipulation
$(document).ready(function () {
	//alert( 'jqproject loaded and ready' );
	$('a.delete').click( imagedelete );
	// Various project update stuff
	$('input.save,select.save,textarea.save').change( saveItem );
	// Show before and after, or before only
	$('input[type=radio].save').click(function(){
		// Switch the before image div on and off if this is one of the radio buttons
		if($(this).val() == '_b_a' ) {
			if( $(this).is(':checked') ) {
				$('#bPic').css('display','inline');
				$('#aPic').css('float','right');
			} else {
				$('#bPic').css('display','none');
				$('#aPic').css('float','left');
			}
		} else {
			if( $(this).is(':checked') ) {
				$('#bPic').css('display','none');
				$('#aPic').css('float','left');
			} else {
				$('#bPic').css('display','inline');
				$('#aPic').css('float','right');
			}
		}
	});
	// Initial display of Preview and Submit buttons
	// Project image arranging
	$("#response").hide();
	$(function() {
		$('div.uploadimagelist li').hover( hoverOver, hoverAway );
		$('div.uploadimagelist ul').sortable({ opacity: 0.8, cursor: 'move',
			update: function() {
				var order = $(this).sortable("serialize") + '&id=move';
				$.post(updateserver, order, function(theResponse){
					}, "json");
				}
		});
	});

	// Update the form action according to which button was clicked
    $('#uploadForm .previewsubmit').hover(function(){
		//alert( 'setting form action to '+$('#uploadForm').attr('action'));
		$('#uploadForm').attr('action',$(this).attr('alt'));
    });
	
	$('#uploadForm').submit(function(){
		var submitOK = true;
		$('.required').each(function() {
			var errorID = 'error'+$(this).attr("id");
			//alert( 'Checking '+$(this).attr('name'));
			$('#'+errorID).remove();
			if( $(this).val().length <= 0 ) {
				//alert( $(this).attr('name')+': failed');
				$(this).parent().append('<div id="'+errorID+'" class="red">Cannot be empty</div>');
				submitOK = false;
			}
		});
		if( !submitOK )
			submitOK = confirm( "You have errors that should be corrected. Do you still want to leave?" );
		return submitOK;
	});
});

// Event functions
function imagedelete(){
	try {
		var image_id = $(this).attr('href');
		if( confirm( 'You are about to delete this image.  This cannot be undone and your photo cannot be restored.  Delete image?') ) {
			// We first back up the move in the DB.  If that works we'll update the page.
			var dataString = 'id=move&direction=delete&image_id='+image_id;
			//alert( 'Sending '+dataString );
			$.get( updateserver, dataString,
				function(resp) {
					if( resp.status == 'OK' ) {
						$('#arrayorder_'+image_id).remove();
					} else
						alert( 'ERROR: '+resp.message );
				},
				'json');
		}
	} catch(e) {
		alert( "An exception occurred in the script. Error name: [" + e.name + "]. Error message: " + e.message);
	}
	this.blur();	// Kill further link processing
	return false;
}

function saveItem(){
	//alert( 'Saving '+ $(this).parent().attr('name') + ' length = ' + $(this).val().length );
	var errorID = 'error'+$(this).attr("id");
	$('#'+errorID).remove();
	if( $(this).val().length > 0 ) {
		try {
			var item_id = $(this).parent().attr('title');
			var field = $(this).attr('name');
			//alert( 'Changing '+$(this).attr('name')+' of project '+item_id+' to '+$(this).val() );
			$('.wait_update').show();
			// We first back up the move in the DB.  If that works we'll update the page as needed.
			var type = 'project';
			if( field == 'Supply' || field == 'SupplierName' || field == 'URL' )
				type = 'supply';
			else if( field == 'Caption' )
				type = 'image';
			$.get( updateserver, { id: 'save', type: type, field: field, key: item_id, value: $(this).val() },
				function( resp ) {
					//alert( field=': value = '+window[field]);
					if( resp.status == 'ERROR' )
						alert( 'ERROR: '+resp.message );
					else if( window[field] != undefined ) {
						len = $(this).val().length;
						window[field] = len > 0;
						if( len <= 0 )
							$(this).append('<span id="'+errorID+'">Field must contain a value</span>');
					}
				}, 'json' );
		} catch(e) {
			alert( "An exception occurred in the script. Error name: [" + e.name + "]. Error message: " + e.message);
		}
		$('.wait_update').hide();
	} else {
		//alert( $(this).attr('name')+': failed');
		$(this).parent().append('<div id="'+errorID+'" class="red">Cannot be empty</div>');
	}
	this.blur();	// Kill further link processing
	return false;
}

function hoverOver(){
	$(this).css('border', 'thin solid red');
//	$(this).find('span:first').css('display','inline');
}

function hoverAway(){
	$(this).css('border', 'none');
//	$(this).find('span:first').css('display','none');
}
