var apg = new apgObj();

$(document).ready(function() {
	loadPasswords($("#apgContent"), apg.getNext);

	$("#apgPrevious").click(function() {
		loadPasswords($("#apgContent"), apg.getPrevious);
	});
	$("#apgNext").click(function() {
		loadPasswords($("#apgContent"), apg.getNext);
	});
});

function apgObj() {
	var current = 0;
	var list = new Array();

	var getNewPasswordSet = function() {
		var newPasswordSet = "";

		$.ajax({
			type: "POST",
			url: "/ajax/misc/apg.xml",
			async: false,
			success: function(xml) {
				if ($("error", xml).length > 0) {
					throw new APGException( $("error", xml).text() );
				} else {
					$("password", xml).each(function() {
						newPasswordSet += $(this).text() + "\n";
					});
					newPasswordSet = newPasswordSet.replace(/(\n|\r)+$/, '');
				}
			},
			error: function() {
				throw new APGException("Error retreiving password set.");
			}
		});

		return newPasswordSet;
	}

	this.getCurrent = function() {
		return list[current];
	}

	this.getPrevious = function() {
		if (current > 0) {
			current--;
		} else {
			list.unshift( getNewPasswordSet() );
			current = 0;
		}
		return list[current];
	}
	this.getNext = function() {
		if (current < list.length - 1) {
			current++;
		} else {
			current = list.push( getNewPasswordSet() ) - 1;
		}
		return list[current];
	}
}
function loadPasswords(container, passwordSet) {
	$(".apgLoading").show();
	try {
		var newPasswordSet = passwordSet();
		container.html( newPasswordSet );
	} catch (e) {
		alert(e.getErrorMessage());
		//alert("an error occured: " + e);
	}
	$(".apgLoading").fadeOut(500);
}

function Exception() {
	var errorMessage = "standard error";

	this.getErrorMessage = function() {
		return errorMessage;
	}
	this.setErrorMessage = function(_errorMessage) {
		errorMessage = _errorMessage;
	}
}

function APGException(apgErrorMessage) {
	this.setErrorMessage(apgErrorMessage);
}
APGException.prototype = new Exception;

