var sportspickle = window.sportspickle || {};

/**
 * Generic delete function that makes a call to template->delete
 * method and redirects user back to content listing.
 */
sportspickle.delete =  function(node_id, type) {
	if(!confirm('Are you sure you want to delete this content? There is no undo.')) {
		return false;
	}

	jument.ajax.request({
		url: '/ajax/template/delete',
		parameters: 'node_id=' + node_id,
		success: function(data) {
			if(type == 'picture_gallery') {
				window.location.replace('/picture_galleries');
			} else {
				window.location.replace('/' + type + 's/');
			}
		}
	});

	return false;
};


$(document).ready(function() {
	$('input.date').datetime({
		userLang: 'en',
		americanMode: true
	});

	$('input[type="text"][value=""]:not(.date), input[type="password"][value=""]:not(.date)').first().focus();

	/**
	 * Binds to a button with 'delete' class and figures out
	 * what type of work we are dealing with based on form
	 * action parameter.
	 */
	$('.delete.generic_delete').click(function() {
		// Retrieve type of item we are deleting based on URI
		var action = $(this).parents('form').attr('action');
		if(action !== undefined) {
			var type = new RegExp('([^/]+)', '').exec(action);
			if(type[0] !== undefined) {
				var node_id = action.replace(new RegExp('/([^/]+)/', 'g'), '');
				sportspickle.delete(node_id, type[0]);
			}
		}

		return false;
	});

	// Automatically append rel=external to URLs that go off site.
	$('a').filter(function() {
		return this.hostname && this.hostname !== location.hostname;
	}).each(function() {
		var rel = $(this).attr('rel');
		if(rel) {
			$(this).attr('rel', rel + ' external');
		} else {
			$(this).attr('rel', 'external');
		}
	});

	//	Alternative to target="blank"
	$('a[rel*=external]').click( function() {
		window.open(this.href);
		return false;
	});

});

