////////////////////////////////////////////////////////////////
// Copyright © 2008-2010 ReFreezed.com
////////////////////////////////////////////////////////////////



var CSprite = {};

(function(){















/* MEMBERS
********************************************************************************************************************************/

var mIsBusy = false;















/* PRIVATE METHODS
********************************************************************************************************************************/

/*
	AddCharacter()
	AddCollection()
	AddComic()
	AddComment()
	DeleteCharacter()
	DeleteComicImage()
	DeleteComicThumb()
	DeleteComment()
	HideComment()
	IsAddCharacterInputsValid()
	IsAddComicInputsValid()
	IsAddCommentInputsValid()
	IsDeleteComicImageInputsValid()
	IsDeleteComicThumbInputsValid()
	IsLoadStoryArcsInputsValid()
	IsUpdateCastOrderInputsValid()
	IsUpdateCharacterInputsValid()
	IsUpdateComicInputsValid()
	IsUpdateComicStripInputsValid()
	IsUploadComicStripInputsValid()
	LoadStoryArcs()
	SetBusyState()
	UpdateCastOrder()
	UpdateCharacter()
	UpdateComic()
	UpdateComicStrip()
	UploadComicStrip()
	VoteOnStrip()
*/



function AddCharacter(form) // IMPORTANT: The form contains a file input
{
	if (mIsBusy)
		return false;

	// Validate function parameters
	if ($(form).length == 0)
		return false;

	// Set busy state
	SetBusyState(true, form, 'Adding character...');

	// File inputs
	var inputs = get_inputs(form);
	var file_inputs = $(inputs['photo']);

	// Data
	var data = {};
	data['comicId']     = inputs['comicId'].value;
	data['name']        = inputs['name'].value;
	data['description'] = inputs['description'].value;

	// Timeout
	var timeout_function = function()
	{
		error('A timeout occured while submitting the form. Please try again.');
		SetBusyState(false, form);
	};

	// Success
	var success_function = function(data)
	{
		data = split_iframe_code_and_content(data);
		var code = data.code;
		var content = data.content;
		if (code == 'success')
		{
			location.reload();
		}
		else
		{
			alert(content);
			SetBusyState(false, form);
		}
	};

	// Submit
	FormUpload.SubmitFileInputs('c-sprite/add-character', file_inputs, data, success_function, timeout_function);

	return true;

}



function AddCollection(selectElement, collectionPlaceholder)
{
	// Get selected collection ID
	var collection_id = $(selectElement).val();
	if (collection_id == '-')
		return false;
	// Check if the collection has already been added
	var inputs = $(collectionPlaceholder).find('input[type=hidden]');
	for (var i = 0; i < inputs.length; i++)
	{
		if (inputs.get(i).value == collection_id)
		{
			$(selectElement).get(0).selectedIndex = 0;
			return false;
		}
	}
	// Get collection title
	var select_dom_element = $(selectElement).get(0);
	var title = select_dom_element.options[select_dom_element.selectedIndex].text;
	// Add collection
	var collection_item = $('<div class="comicStripCollection"></div>');
	var remove_collection_button = $('<a href="javascript:;">Remove</a>').click(function()
	{
		$(this).parents('.comicStripCollection').eq(0).remove();
	})
	collection_item.append('<input type="hidden" name="collection-'+collection_id+'" value="'+collection_id+'" />');
	collection_item.append($('<div></div>').append('<span class="bold">'+title.asText()+'</span> (').append(remove_collection_button).append(')'));
	$(collectionPlaceholder).append(collection_item);
	// Reset the 'select' element
	$(selectElement).get(0).selectedIndex = 0;
	// Success!
	return true;
}



function AddComic(form) // IMPORTANT: The form contains a file input
{
	if (mIsBusy)
		return false;

	// Validate function parameters
	if ($(form).length == 0)
		return false;

	// Set busy state
	SetBusyState(true, form, 'Adding comic...');

	// File inputs
	var inputs = get_inputs(form);
	var file_inputs = $(inputs['image']).add(inputs['thumb']);

	// Data
	var data = {};
	data['title']       = inputs['title'].value;
	data['description'] = inputs['description'].value;
	data['ratings']     = get_checkbox_input_value(form, 'aRating')+get_checkbox_input_value(form, 'lRating')
		+get_checkbox_input_value(form, 'nRating')+get_checkbox_input_value(form, 'vRating')+get_checkbox_input_value(form, 'xRating');

	// Timeout
	var timeout_function = function()
	{
		error('A timeout occured while submitting the form. Please try again.');
		SetBusyState(false, form);
	};

	// Success
	var success_function = function(data)
	{
		data = split_iframe_code_and_content(data);
		var code = data.code;
		var content = data.content;
		if (code == 'success')
		{
			redirect(content);
		}
		else
		{
			alert(content);
			SetBusyState(false, form);
		}
	};

	// Submit
	FormUpload.SubmitFileInputs('c-sprite/add-comic', file_inputs, data, success_function, timeout_function);

	return true;

}



function AddComment(form, commentsPlaceholder)
{
	if (mIsBusy)
		return false;

	// Validate function parameters
	if ($(form).length == 0)
		return false;

	// Set busy state
	SetBusyState(true, form, 'Adding comment...');

	// Data
	var inputs = get_inputs(form);
	var data = {};
	data['comicStripId'] = inputs['comicStripId'].value;
	data['message']      = inputs['message'].value;

	// Success
	var success_func = function(data, textStatus)
	{
		data = split_code_and_content(data);
		var code = data.code;
		var content = data.content;
		if (code == 'success')
		{
			$(form).get(0).reset();
			if ($(commentsPlaceholder).hasClass('empty'))
				$(commentsPlaceholder).html('').removeClass('empty');
			$(commentsPlaceholder).append($(content).css('opacity', 0).animate({'opacity': 1}, 1500));
			SetBusyState(false, form);
		}
		else
		{
			if (content)
				alert(content);
			SetBusyState(false, form);
		}
	};

	// Error
	var error_func = function(XMLHttpRequest, textStatus, errorThrown)
	{
		error('Could not contact the server at the moment.');
		SetBusyState(false, form);
	};

	// Request
	FormUpload.SubmitData('c-sprite/add-comment', data, success_func, error_func);
	return true;

}



function DeleteCharacter(characterId)
{
	if (mIsBusy)
		return false;

	// Validate function parameters
	if (!(characterId > 0))
		return false;

	// Set busy state
	SetBusyState(true);
	$('#character-'+characterId).addClass('waitCur');

	// Data
	var data = {};
	data['characterId'] = characterId;

	// Success
	var success_func = function(data, textStatus)
	{
		data = split_code_and_content(data);
		var code = data.code;
		var content = data.content;
		if (code == 'success')
		{
			SetBusyState(false);
			$('#character-'+characterId).remove();
		}
		else
		{
			alert(content);
			SetBusyState(false);
			$('#character-'+characterId).removeClass('waitCur');
		}
	};

	// Error
	var error_func = function(XMLHttpRequest, textStatus, errorThrown)
	{
		error('Could not contact the server at the moment.');
		SetBusyState(false);
		$('#character-'+characterId).removeClass('waitCur');
	};

	// Request
	FormUpload.SubmitData('c-sprite/delete-character', data, success_func, error_func);
	return true;

}



function DeleteComicImage(form)
{
	if (mIsBusy)
		return false;

	// Validate function parameters
	if (!($(form).length > 0))
		return false;

	// Set busy state
	SetBusyState(true, form, 'Deleting comic image...');

	// Data
	var inputs = get_inputs(form);
	var data = {};
	data['comicId'] = inputs['comicId'].value;

	// Success
	var success_func = function(data, textStatus)
	{
		data = split_code_and_content(data);
		var code = data.code;
		var content = data.content;
		if (code == 'success')
		{
			$('.comicImagePreview', $(form)).remove();
			SetBusyState(false, form);
		}
		else
		{
			alert(content);
			SetBusyState(false, form);
		}
	};

	// Error
	var error_func = function(XMLHttpRequest, textStatus, errorThrown)
	{
		error('Could not contact the server at the moment.');
		SetBusyState(false, form);
	};

	// Request
	FormUpload.SubmitData('c-sprite/delete-comic-image', data, success_func, error_func);
	return true;

}



function DeleteComicThumb(form)
{
	if (mIsBusy)
		return false;

	// Validate function parameters
	if (!($(form).length > 0))
		return false;

	// Set busy state
	SetBusyState(true, form, 'Deleting thumbnail...');

	// Data
	var inputs = get_inputs(form);
	var data = {};
	data['comicId'] = inputs['comicId'].value;

	// Success
	var success_func = function(data, textStatus)
	{
		data = split_code_and_content(data);
		var code = data.code;
		var content = data.content;
		if (code == 'success')
		{
			$('.comicThumbPreview', $(form)).remove();
			SetBusyState(false, form);
		}
		else
		{
			alert(content);
			SetBusyState(false, form);
		}
	};

	// Error
	var error_func = function(XMLHttpRequest, textStatus, errorThrown)
	{
		error('Could not contact the server at the moment.');
		SetBusyState(false, form);
	};

	// Request
	FormUpload.SubmitData('c-sprite/delete-comic-thumb', data, success_func, error_func);
	return true;

}



function DeleteComment(commentId)
{
	if (mIsBusy)
		return false;

	// Validate function parameters
	if (!(commentId > 0))
		return false;

	// Set busy state
	SetBusyState(true);
	$('#comment-'+commentId).addClass('waitCur');

	// Data
	var data = {};
	data['commentId'] = commentId;

	// Success
	var success_func = function(data, textStatus)
	{
		data = split_code_and_content(data);
		var code = data.code;
		var content = data.content;
		if (code == 'success')
		{
			$('#comment-'+commentId).animate({opacity: 0}, 750, 0, function()
			{
				$(this).remove();
				SetBusyState(false);
			});
		}
		else
		{
			alert(content);
			$('#comment-'+commentId).removeClass('waitCur');
			SetBusyState(false);
		}
	};

	// Error
	var error_func = function(XMLHttpRequest, textStatus, errorThrown)
	{
		error('Could not contact the server at the moment.');
		$('#comment-'+commentId).removeClass('waitCur');
		SetBusyState(false);
	};

	// Request
	FormUpload.SubmitData('c-sprite/delete-comment', data, success_func, error_func);
	return true;

}



function HideComment(commentId, show)
{
	if (mIsBusy)
		return false;

	// Validate function parameters
	show = ((show) ? 1 : 0);
	if (!(commentId > 0))
		return false;

	// Set busy state
	SetBusyState(true);
	$('#comment-'+commentId).addClass('waitCur');

	// Data
	var data = {};
	data['commentId'] = commentId;
	data['show']      = show;

	// Success
	var success_func = function(data, textStatus)
	{
		data = split_code_and_content(data);
		var code = data.code;
		var content = data.content;
		if (code == 'success')
		{
			$('#comment-'+commentId).replaceWith(content);
			SetBusyState(false);
		}
		else
		{
			alert(content);
			$('#comment-'+commentId).removeClass('waitCur');
			SetBusyState(false);
		}
	};

	// Error
	var error_func = function(XMLHttpRequest, textStatus, errorThrown)
	{
		error('Could not contact the server at the moment.');
		$('#comment-'+commentId).removeClass('waitCur');
		SetBusyState(false);
	};

	// Request
	FormUpload.SubmitData('c-sprite/hide-comment', data, success_func, error_func);
	return true;

}


function IsAddCharacterInputsValid(form)
{
	var inputs = get_inputs(form);
	if (inputs === false)
		return error('No inputs were found in the form.');

	// Comic ID
	var input = inputs['comicId'];
	var value = input.value;
	if (!(value > 0))
		return error('No comic specified.');

	// Name
	var input = inputs['name'];
	var value = input.value;
	if (value == '')
	{
		alert('Please provide a name.');
		focus_input(input);
		return false;
	}
	else if (value.length > 50)
	{
		alert('The name is too long. Maximum length is 50.');
		focus_input(input);
		return false;
	}

	// Description
	var input = inputs['description'];
	var value = input.value;
	if (value.length > 1337)
	{
		alert('The description is too long. Maximum length is 1337.');
		focus_input(input);
		return false;
	}

	// Photo
	// (No client-side validation required)

	return true;
}



function IsAddComicInputsValid(form)
{
	var inputs = get_inputs(form);
	if (inputs === false)
		return error('No inputs were found in the form.');

	// Title
	var input = inputs['title'];
	var value = input.value;
	if (value == '')
	{
		alert('Please provide a title.');
		focus_input(input);
		return false;
	}
	else if (value.length > 50)
	{
		alert('The title is too long. Maximum length is 50.');
		focus_input(input);
		return false;
	}

	// Description
	var input = inputs['description'];
	var value = input.value;
	if (value.length > 1337)
	{
		alert('The description is too long. Maximum length is 1337.');
		focus_input(input);
		return false;
	}

	// Ratings
	// (No client-side validation required)

	// Image
	// (No client-side validation required)

	// Thumbnail
	// (No client-side validation required)

	return true;
}



function IsAddCommentInputsValid(form)
{
	var inputs = get_inputs(form);
	if (inputs === false)
		return error('No inputs were found in the form.');

	// Comic strip ID
	var input = inputs['comicStripId'];
	var value = input.value;
	if (!(value > 0))
		return error('No comic strip specified.');

	// Message
	var input = inputs['message'];
	var value = input.value;
	if (value == '')
	{
		alert('Please provide a message.');
		focus_input(input);
		return false;
	}
	else if (value.length > 1337)
	{
		alert('The message is too long. Maximum length is 1337.');
		focus_input(input);
		return false;
	}

	return true;
}



function IsDeleteComicImageInputsValid(form)
{
	var inputs = get_inputs(form);
	if (inputs === false)
		return error('No inputs were found in the form.');

	// Comic ID
	var input = inputs['comicId'];
	var value = input.value;
	if (!(value > 0))
		return error('No comic specified.');

	return true;
}



function IsDeleteComicThumbInputsValid(form)
{
	var inputs = get_inputs(form);
	if (inputs === false)
		return error('No inputs were found in the form.');

	// Comic ID
	var input = inputs['comicId'];
	var value = input.value;
	if (!(value > 0))
		return error('No comic specified.');

	return true;
}



function IsLoadStoryArcsInputsValid(form)
{
	var inputs = get_inputs(form);
	if (inputs === false)
		return error('No inputs were found in the form.');

	// Comic ID
	var input = inputs['comicId'];
	var value = input.value;
	if (value == '')
	{
		if (!$(input).is('select'))
			return error('No comic specified.');
		alert('Please select a comic.');
		focus_input(input);
		return false;
	}

	return true;
}



function IsUpdateCastOrderInputsValid(form)
{
	var inputs = get_inputs(form);
	if (inputs === false)
		return error('No inputs were found in the form.');

	// Comic ID
	var input = inputs['comicId'];
	var value = input.value;
	if (!(value > 0))
		return error('No comic specified.');

	return true;
}



function IsUpdateCharacterInputsValid(form)
{
	var inputs = get_inputs(form);
	if (inputs === false)
		return error('No inputs were found in the form.');

	// Character ID
	var input = inputs['characterId'];
	var value = input.value;
	if (!(value > 0))
		return error('No character specified.');

	// Name
	var input = inputs['name'];
	var value = input.value;
	if (value == '')
	{
		alert('Please provide a name.');
		focus_input(input);
		return false;
	}
	else if (value.length > 50)
	{
		alert('The name is too long. Maximum length is 50.');
		focus_input(input);
		return false;
	}

	// Description
	var input = inputs['description'];
	var value = input.value;
	if (value.length > 1337)
	{
		alert('The description is too long. Maximum length is 1337.');
		focus_input(input);
		return false;
	}

	// Photo
	// (No client-side validation required)

	return true;
}



function IsUpdateComicInputsValid(form)
{
	var inputs = get_inputs(form);
	if (inputs === false)
		return error('No inputs were found in the form.');

	// Comic ID
	var input = inputs['comicId'];
	var value = input.value;
	if (!(value > 0))
		return error('No comic specified.');

	// Title
	var input = inputs['title'];
	var value = input.value;
	if (value == '')
	{
		alert('Please provide a title.');
		focus_input(input);
		return false;
	}
	else if (value.length > 50)
	{
		alert('The title is too long. Maximum length is 50.');
		focus_input(input);
		return false;
	}

	// Description
	var input = inputs['description'];
	var value = input.value;
	if (value.length > 1337)
	{
		alert('The description is too long. Maximum length is 1337.');
		focus_input(input);
		return false;
	}

	// Ratings
	// (No client-side validation required)

	// Image
	// (No client-side validation required)

	// Thumbnail
	// (No client-side validation required)

	return true;
}



function IsUpdateComicStripInputsValid(form)
{
	var inputs = get_inputs(form);
	if (inputs === false)
		return error('No inputs were found in the form.');

	// Comic strip ID
	var input = inputs['comicStripId'];
	var value = input.value;
	if (!(value > 0))
		return error('No comic strip specified.');

	// Comic ID
	var input = inputs['comicId'];
	var value = input.value;
	if (value == '')
	{
		if (!$(input).is('select'))
			return error('No comic specified.');
		alert('Please select a comic.');
		focus_input(input);
		return false;
	}

	// Title
	var input = inputs['title'];
	var value = input.value;
	if (value == '')
	{
		alert('Please provide a title.');
		focus_input(input);
		return false;
	}
	else if (value.length > 100)
	{
		alert('The title is too long. Maximum length is 100.');
		focus_input(input);
		return false;
	}

	// Story arc
	var input = inputs['storyArc'];
	var value = input.value;
	if (value.length > 100)
	{
		alert('The story arc title is too long. Maximum length is 100.');
		focus_input(input);
		return false;
	}

	// Author's comments
	var input = inputs['comments'];
	var value = input.value;
	if (value.length > 1337)
	{
		alert('The comments are too long. Maximum length is 1337.');
		focus_input(input);
		return false;
	}

	// Tags
	var input = inputs['tags'];
	clean_up_tag_input(input);
	var value = input.value;
	if (value.split(',').length > 20)
	{
		alert('You\'ve entered too many tags ('+value.split(',').length+'). Maximum number of tags is 20.');
		focus_input(input);
		return false;
	}

	// Image
	// (No client-side validation required)

	// Collections
	// (No client-side validation required)

	// Comments
	// (No client-side validation required)

	return true;
}



function IsUploadComicStripInputsValid(form)
{
	var inputs = get_inputs(form);
	if (inputs === false)
		return error('No inputs were found in the form.');

	// Comic ID
	var input = inputs['comicId'];
	var value = input.value;
	if (value == '')
	{
		if (!$(input).is('select'))
			return error('No comic specified.');
		alert('Please select a comic.');
		focus_input(input);
		return false;
	}

	// Title
	var input = inputs['title'];
	var value = input.value;
	if (value == '')
	{
		alert('Please provide a title.');
		focus_input(input);
		return false;
	}
	else if (value.length > 100)
	{
		alert('The title is too long. Maximum length is 100.');
		focus_input(input);
		return false;
	}

	// Story arc
	var input = inputs['storyArc'];
	var value = input.value;
	if (value.length > 100)
	{
		alert('The story arc title is too long. Maximum length is 100.');
		focus_input(input);
		return false;
	}

	// Author's comments
	var input = inputs['comments'];
	var value = input.value;
	if (value.length > 1337)
	{
		alert('The comments are too long. Maximum length is 1337.');
		focus_input(input);
		return false;
	}

	// Tags
	var input = inputs['tags'];
	clean_up_tag_input(input);
	var value = input.value;
	if (value.split(',').length > 20)
	{
		alert('You\'ve entered too many tags ('+value.split(',').length+'). Maximum number of tags is 20.');
		focus_input(input);
		return false;
	}

	// Image
	var input = inputs['image'];
	var value = input.value;
	if (value == '')
	{
		alert('Please choose an image file from your hard drive.');
		focus_input(input);
		return false;
	}

	// Collections
	// (No client-side validation required)

	// Comments
	// (No client-side validation required)

	return true;
}



function LoadStoryArcs(form)
{
	if (mIsBusy)
		return false;

	// Validate function parameters
	if ($(form).length == 0)
		return false;

	// Set busy state
	SetBusyState(true, form, 'Fetching story arcs...');

	// Data
	var inputs = get_inputs(form);
	var data = {};
	data['comicId'] = inputs['comicId'].value;

	// Success
	var success_func = function(data, textStatus)
	{
		data = split_code_and_content(data);
		var code = data.code;
		var content = data.content;
		if (code == 'success')
		{
			$(inputs['storyArc']).val('');
			if (content == '')
				focus_input($(inputs['storyArcList']).html('<option></option>').hide());
			else
				focus_input($(inputs['storyArcList']).html('<option value="-" selected="selected">&mdash; Select arc &mdash;</option>'+content).show());
			SetBusyState(false, form);
		}
		else
		{
			alert(content);
			SetBusyState(false, form);
		}
	};

	// Error
	var error_func = function(XMLHttpRequest, textStatus, errorThrown)
	{
		error('Could not contact the server at the moment.');
		SetBusyState(false, form);
	};

	// Request
	FormUpload.SubmitData('c-sprite/get-story-arcs', data, success_func, error_func);
	return true;
}



function SetBusyState(state, form, busyText)
{
	mIsBusy = !!state;
	if (form != undefined)
	{
		if (mIsBusy)
		{
			$(form).addClass('busy').find('input, select, textarea').attr('disabled', 'disabled');
			if (busyText != undefined)
				$('.busyButton', $(form)).val(busyText);
		}
		else
		{
			$(form).removeClass('busy').find('input, select, textarea').removeAttr('disabled');
		}
	}
}



function UpdateCastOrder(form)
{
	if (mIsBusy)
		return false;

	// Validate function parameters
	if ($(form).length == 0)
		return false;

	// Set busy state
	SetBusyState(true, form, 'Updating order...');

	// Data
	var character_ids = [];
	$('input[name="characterIds[]"]', form).each(function(){
		character_ids.push(this.value);
	});
	var inputs = get_inputs(form);
	var data = {};
	data['comicId'] = inputs['comicId'].value;
	data['characterIds'] = character_ids.join(',');

	// Success
	var success_func = function(data, textStatus)
	{
		data = split_code_and_content(data);
		var code = data.code;
		var content = data.content;
		if (code == 'success')
		{
			alert('The order of appearance has been updated.');
			$('.rearrangeableComicCastButtons', form).hide();
			SetBusyState(false, form);
		}
		else
		{
			alert(content);
			SetBusyState(false, form);
		}
	};

	// Error
	var error_func = function(XMLHttpRequest, textStatus, errorThrown)
	{
		error('Could not contact the server at the moment.');
		SetBusyState(false, form);
	};

	// Request
	FormUpload.SubmitData('c-sprite/update-cast-order', data, success_func, error_func);
	return true;

}



function UpdateCharacter(form) // IMPORTANT: The form contains a file input
{
	if (mIsBusy)
		return false;

	// Validate function parameters
	if ($(form).length == 0)
		return false;

	// Set busy state
	SetBusyState(true, form, 'Updating character...');

	// File inputs
	var inputs = get_inputs(form);
	var file_inputs = $(inputs['photo']);

	// Data
	var data = {};
	data['characterId'] = inputs['characterId'].value;
	data['name']        = inputs['name'].value;
	data['description'] = inputs['description'].value;

	// Timeout
	var timeout_function = function()
	{
		error('A timeout occured while submitting the form. Please try again.');
		SetBusyState(false, form);
	};

	// Success
	var success_function = function(data)
	{
		data = split_iframe_code_and_content(data);
		var code = data.code;
		var content = data.content;
		if (code == 'success')
		{
			location.reload();
		}
		else
		{
			alert(content);
			SetBusyState(false, form);
		}
	};

	// Submit
	FormUpload.SubmitFileInputs('c-sprite/update-character', file_inputs, data, success_function, timeout_function);

	return true;

}



function UpdateComic(form) // IMPORTANT: The form contains a file input
{
	if (mIsBusy)
		return false;

	// Validate function parameters
	if ($(form).length == 0)
		return false;

	// Set busy state
	SetBusyState(true, form, 'Updating comic...');

	// File inputs
	var inputs = get_inputs(form);
	var file_inputs = $(inputs['image']).add(inputs['thumb']);

	// Data
	var data = {};
	data['comicId']     = inputs['comicId'].value;
	data['title']       = inputs['title'].value;
	data['description'] = inputs['description'].value;
	data['ratings']     = get_checkbox_input_value(form, 'aRating')+get_checkbox_input_value(form, 'lRating')
		+get_checkbox_input_value(form, 'nRating')+get_checkbox_input_value(form, 'vRating')+get_checkbox_input_value(form, 'xRating');

	// Timeout
	var timeout_function = function()
	{
		error('A timeout occured while submitting the form. Please try again.');
		SetBusyState(false, form);
	};

	// Success
	var success_function = function(data)
	{
		data = split_iframe_code_and_content(data);
		var code = data.code;
		var content = data.content;
		if (code == 'success')
		{
			redirect(content);
		}
		else
		{
			alert(content);
			SetBusyState(false, form);
		}
	};

	// Submit
	FormUpload.SubmitFileInputs('c-sprite/update-comic', file_inputs, data, success_function, timeout_function);

	return true;

}



function UpdateComicStrip(form) // IMPORTANT: The form contains a file input
{
	if (mIsBusy)
		return false;

	// Validate function parameters
	if ($(form).length == 0)
		return false;

	// Set busy state
	SetBusyState(true, form, 'Updating strip...');

	// File inputs
	var inputs = get_inputs(form);
	var file_inputs = $(inputs['image']);

	// Data
	var comic_strip_collection_inputs = $(form).find('.comicStripCollections input');
	var comic_strip_collection_ids = [];
	for (var i = 0; i < comic_strip_collection_inputs.length; i++)
		comic_strip_collection_ids.push(comic_strip_collection_inputs.eq(i).val());
	var allow_comments = get_radio_input_value(form, 'allowComments');
	var data = {};
	data['comicStripId']  = inputs['comicStripId'].value;
	data['comicId']       = inputs['comicId'].value;
	data['title']         = inputs['title'].value;
	data['storyArc']      = inputs['storyArc'].value;
	data['comments']      = inputs['comments'].value;
	data['tags']          = inputs['tags'].value;
	data['collections']   = comic_strip_collection_ids.join(',');
	data['allowComments'] = allow_comments;

	// Timeout
	var timeout_function = function()
	{
		error('A timeout occured while submitting the form. Please try again.');
		SetBusyState(false, form);
	};

	// Success
	var success_function = function(data)
	{
		data = split_iframe_code_and_content(data);
		var code = data.code;
		var content = data.content;
		if (code == 'success')
		{
			redirect(content);
		}
		else
		{
			alert(content);
			SetBusyState(false, form);
		}
	};

	// Submit
	FormUpload.SubmitFileInputs('c-sprite/update-comic-strip', file_inputs, data, success_function, timeout_function);

	return true;

}



function UploadComicStrip(form) // IMPORTANT: The form contains a file input
{
	if (mIsBusy)
		return false;

	// Validate function parameters
	if ($(form).length == 0)
		return false;

	// Set busy state
	SetBusyState(true, form, 'Uploading strip...');

	// File inputs
	var inputs = get_inputs(form);
	var file_inputs = $(inputs['image']);

	// Data
	var comic_strip_collection_inputs = $(form).find('.comicStripCollections input');
	var comic_strip_collection_ids = [];
	for (var i = 0; i < comic_strip_collection_inputs.length; i++)
		comic_strip_collection_ids.push(comic_strip_collection_inputs.eq(i).val());
	var allow_comments = get_radio_input_value(form, 'allowComments');
	var data = {};
	data['comicId']      = inputs['comicId'].value;
	data['title']        = inputs['title'].value;
	data['storyArc']     = inputs['storyArc'].value;
	data['comments']     = inputs['comments'].value;
	data['tags']         = inputs['tags'].value;
	data['collections']  = comic_strip_collection_ids.join(',');
	data['allowComments'] = allow_comments;

	// Timeout
	var timeout_function = function()
	{
		error('A timeout occured while submitting the form. Please try again.');
		SetBusyState(false, form);
	};

	// Success
	var success_function = function(data)
	{
		data = split_iframe_code_and_content(data);
		var code = data.code;
		var content = data.content;
		if (code == 'success')
		{
			redirect(content);
		}
		else
		{
			alert(content);
			SetBusyState(false, form);
		}
	};

	// Submit
	FormUpload.SubmitFileInputs('c-sprite/add-comic-strip', file_inputs, data, success_function, timeout_function);

	return true;

}



function VoteOnStrip(id, score, scorePlaceholder, voteCountPlaceholder)
{
	if (mIsBusy)
		return false;

	// Validate function parameters
	score = Math.floor(score);
	if (!(id > 0))
		return false;
	if (!(score >= 1 && score <= 5))
		return false;

	// Set busy state
	SetBusyState(true);

	// Data
	var data = {};
	data['id'] = id;
	data['score'] = score;

	// Success
	var success_func = function(data, textStatus)
	{
		data = split_code_and_content(data);
		var code = data.code;
		var content = data.content;
		if (code == 'success')
		{
			if ($(scorePlaceholder).length > 0)
				$(scorePlaceholder).html(data.content);
			$(voteCountPlaceholder).html(Number($(voteCountPlaceholder).html())+1);
			SetBusyState(false);
		}
		else
		{
			alert(content);
			SetBusyState(false);
		}
	};

	// Error
	var error_func = function(XMLHttpRequest, textStatus, errorThrown)
	{
		error('Could not contact the server at the moment.');
		SetBusyState(false);
	};

	// Request
	FormUpload.SubmitData('comic-strips/vote', data, success_func, error_func);
	return true;

}



function WatchComic(comicId, buttonElement, unwatch)
{
	if (mIsBusy)
		return false;

	// Validate function parameters
	if (unwatch === undefined)
		unwatch = false;
	if (!(comicId > 0))
		return false;

	// Set busy state
	SetBusyState(true);

	// Data
	var data = {};
	data['comicId'] = comicId;
	if (unwatch)
		data['unwatch'] = unwatch;

	// Success
	var success_func = function(data, textStatus)
	{
		data = split_code_and_content(data);
		var code = data.code;
		var content = data.content;
		if (code == 'success')
		{
			$(buttonElement).replaceWith(content);
			SetBusyState(false);
		}
		else
		{
			if (content)
				alert(content);
			SetBusyState(false);
		}
	};

	// Error
	var error_func = function(XMLHttpRequest, textStatus, errorThrown)
	{
		error('Could not contact the server at the moment.');
		SetBusyState(false);
	};

	// Request
	FormUpload.SubmitData('c-sprite/watch-comic', data, success_func, error_func);
	return true;

}















/* PUBLIC METHODS
********************************************************************************************************************************/



CSprite.AddCharacter = function(form)
{
	if (mIsBusy)
		return false;
	if (!IsAddCharacterInputsValid(form))
		return false;
	return AddCharacter(form);
};



CSprite.AddCollection = function(selectElement, collectionPlaceholder)
{
	if (mIsBusy)
		return false;
	return AddCollection(selectElement, collectionPlaceholder);
};



CSprite.AddComic = function(form)
{
	if (mIsBusy)
		return false;
	if (!IsAddComicInputsValid(form))
		return false;
	return AddComic(form);
};



CSprite.AddComment = function(form, commentsPlaceholder)
{
	if (mIsBusy)
		return false;
	if (!IsAddCommentInputsValid(form))
		return false;
	return AddComment(form, commentsPlaceholder);
};



CSprite.DeleteComicImage = function(form)
{
	if (mIsBusy)
		return false;
	if (!confirm('Delete image?'))
		return false;
	if (!IsDeleteComicImageInputsValid(form))
		return false;
	return DeleteComicImage(form);
};



CSprite.DeleteComicThumb = function(form)
{
	if (mIsBusy)
		return false;
	if (!confirm('Delete thumbnail?'))
		return false;
	if (!IsDeleteComicThumbInputsValid(form))
		return false;
	return DeleteComicThumb(form);
};



CSprite.DeleteCharacter = function(characterId)
{
	if (mIsBusy)
		return false;
	if (!confirm('Delete character?'))
		return false;
	return DeleteCharacter(characterId);
};



CSprite.DeleteComment = function(commentId)
{
	if (mIsBusy)
		return false;
	if (!confirm('Delete comment?'))
		return false;
	return DeleteComment(commentId);
};



CSprite.HideComment = function(commentId)
{
	if (mIsBusy)
		return false;
	return HideComment(commentId, false);
};



CSprite.LoadStoryArcs = function(form)
{
	if (mIsBusy)
		return false;
	if (!IsLoadStoryArcsInputsValid(form))
		return false;
	return LoadStoryArcs(form);
};



CSprite.ShowComment = function(commentId)
{
	if (mIsBusy)
		return false;
	return HideComment(commentId, true);
};



CSprite.UnwatchComic = function(comicId, buttonElement)
{
	if (mIsBusy)
		return false;
	return WatchComic(comicId, buttonElement, true);
};



CSprite.UpdateCastOrder = function(form)
{
	if (mIsBusy)
		return false;
	if (!IsUpdateCastOrderInputsValid(form))
		return false;
	return UpdateCastOrder(form);
};



CSprite.UpdateCharacter = function(form)
{
	if (mIsBusy)
		return false;
	if (!IsUpdateCharacterInputsValid(form))
		return false;
	return UpdateCharacter(form);
};



CSprite.UpdateComic = function(form)
{
	if (mIsBusy)
		return false;
	if (!IsUpdateComicInputsValid(form))
		return false;
	return UpdateComic(form);
};



CSprite.UpdateComicStrip = function(form)
{
	if (mIsBusy)
		return false;
	if (!IsUpdateComicStripInputsValid(form))
		return false;
	return UpdateComicStrip(form);
};



CSprite.UploadComicStrip = function(form)
{
	if (mIsBusy)
		return false;
	if (!IsUploadComicStripInputsValid(form))
		return false;
	return UploadComicStrip(form);
};



CSprite.Vote = function(id, score, scorePlaceholder, voteCountPlaceholder)
{
	if (mIsBusy)
		return false;
	if (!$(scorePlaceholder).hasClass('comicStripScore'))
		scorePlaceholder = $(scorePlaceholder).parents('.comicStripScore').eq(0);
	return VoteOnStrip(id, score, scorePlaceholder, voteCountPlaceholder);
};



CSprite.WatchComic = function(comicId, buttonElement)
{
	if (mIsBusy)
		return false;
	return WatchComic(comicId, buttonElement);
};















/* ONLOAD
********************************************************************************************************************************/



$(document).ready(function()
{



	// Prepare voting thingy
	if ($('.voteOnComicStrip').length > 0)
	{
		preload_images('http://img.refreezed.com/site-icons/star_empty.png');
		preload_images('http://img.refreezed.com/site-icons/star_empty_hover.png');
		preload_images('http://img.refreezed.com/site-icons/star_full_hover.png');
		preload_images('http://img.refreezed.com/site-icons/star_full.png');
		preload_images('http://img.refreezed.com/site-icons/star_unknown.png');
		$('.voteOnComicStrip').mouseout(function(e)
		{
			var mouse_pos = get_mouse_coords(e);
			var element_offset = $(this).offset();
			var element_width = $(this).width();
			var element_height = $(this).height();
			if (mouse_pos.x >= element_offset.left && mouse_pos.x < element_offset.left+element_width)
			{
				if (mouse_pos.y >= element_offset.top && mouse_pos.y < element_offset.top+element_height)
					return;
			}
			$(this).find('img').attr('src', 'http://img.refreezed.com/site-icons/star_unknown.png');
		});
		$('.voteOnComicStrip a').mouseover(function()
		{
			$(this).prevAll().andSelf().find('img').attr('src', 'http://img.refreezed.com/site-icons/star_full_hover.png');
			$(this).nextAll().find('img').attr('src', 'http://img.refreezed.com/site-icons/star_empty_hover.png');
		});
	}



	// Enable rearranging of comic cast
	(function(){

		$('ul.rearrangeableComicCast').each(function()
		{
			var rearrangeable_list = new RearrangeableList(this);
			rearrangeable_list.SetDragHandles('.rearrangeButton');
			rearrangeable_list.BindEvent('change', on_cast_order_change);
		});

		function on_cast_order_change(e)
		{
			$(this).parents('form').find('.rearrangeableComicCastButtons').show();
		}

	})();



});















})();
