/* Copyright (c) 2006-2009, Apple Inc. All rights reserved. */

var UserWeblogListingPage = Class.createWithSharedInstance('userWeblogListingPage', true);
UserWeblogListingPage.prototype = {
	
	initialize: function()
	{
		bindEventListeners(this, [
			'onCreateBlogButtonClick'
		]);
		
		if ($$('#users_button a.selected').length < 1) return; // bail if this isn't actually the user weblog listing
		if (window.parent && parent.addService) parent.addService('users', '/users/');
		// patch the checkSessionAuthorization to remove the path from the args
		var s = server(); // force shared instance creation
		s.beforeuserweblog_checkSessionAuthorization = s.checkSessionAuthorization;
		s.checkSessionAuthorization = function(inCallback, inOptAction, inOptPath) {
			s.beforeuserweblog_checkSessionAuthorization(inCallback, inOptAction);
		};
		// patch login method to remove the path from the args
		s.beforeuserweblog_login = s.login;
		s.login = function(inCallback, inUsername, inPassword, inOptAuthorizePath, inOptPersistent) {
			s.beforeuserweblog_login(inCallback, inUsername, inPassword, null, inOptPersistent);
		};
		
		// patch some UID stuff -- otherwise we set the test cookie (cookies=1) in /users/list
		uid().mBaseLocation = '/';
		
		if ($('create_entity_button')) $('create_entity_button').observe('click', this.onCreateBlogButtonClick);
		if ($('paginator_choose')) paginator();
		
		this.entityList = new EntityList('entity_list');
	},
	
	onCreateBlogButtonClick: function(e)
	{
		e.stop();
		if (getMetaTagValue('apple_collab_user_is_admin') == 'True') {
			showAdminBlogDialog();
		} else {
			createBlogForUser();
		}
	}
};

function showAdminBlogDialog() {
	if (!$('weblog_createblog_dialog')) {
		targetedDialogManager().drawDialog('weblog_createblog_dialog', [
			{label:'weblog_createblog_username', contents:'<input type="text" id="weblog_createblog_dialog_username">'}
		], 'weblog_createblog_ok');
	}
	var dialogCallback = function() {
		createBlogForUser($F('weblog_createblog_dialog_username'));
	};
	targetedDialogManager().show('weblog_createblog_dialog', null, dialogCallback, 'create_entity_button');
}

function createBlogForUser(inOptUsername) {
	var createdBlogCallback = function(inRequestObj, inResponseObj) {
		notifier().printAtPage('weblog_createblog_confirm', inResponseObj);
	};
	var errorCallback = function(inRequestObj, inFaultCode, inFaultString) {
		if (inFaultCode == 19) {
			alert(Loc.weblog_createblog_error_notallowed);
		}
		else {
			alert(Loc.weblog_createblog_error_misc);
		}
	};
	var r = new XMLRPCRequest(server(), 'provisionUser', [createdBlogCallback, errorCallback], inOptUsername);
}

if (window.loaded) loaded('user_weblog_listing.js');