/*
 * wishlist.js
 *
 * Utilities for managing PMM property wishlists. Requires cookie.js.
 *
 * Note: Script for removing buttons, properties etc. from the DOM is located
 * within the calling document.
 *
 * (c) Copyright 2006 Future Medium Pty Ltd - http://www.futuremedium.com.au/
 *
 * @author scampbell
 */


/**
 * Declares and instantiates an instance of WishList, which is responsible for
 * adding and removing properties to/from the user's wish list.
 *
 * Properties are stored as a comma-separated list of reference numbers, which
 * are saved as a cookie in the user's browser.
 *
 * @param id The ID for this wishlist.
 */
function WishList(id) {

	/** Cookie wrapper. */
	var _cookie = new Cookie("wishlist." + id);

	/**
	 * The list of property IDs. Populated on initialisation (see last line of
	 * class definition).
	 */
	var properties;


	/**
	 * Adds the property with the specified ID to the user's wishlist. If the
	 * property is already in the user's wishlist, this operation has no
	 * effect.
	 *
	 * @param propertyId The property ID.
	 */
	this.add = function(propertyId) {
		if (properties == null) {
			properties = new Array();
		}

		if (!this.contains(propertyId)) {
			properties.push(propertyId);
			save();
			alert("Property " + propertyId + " added to wishlist.");
		}
	}

	/**
	 * Removes the property with the specified ID from the user's wishlist. If
	 * the property isn't in the user's wishlist, this operation has no effect.
	 *
	 * @param propertyId The property ID.
	 */
	this.remove = function(propertyId) {
		if (properties == null) {
			return;
		}

		var propertyIdx = -1;
		for (var ii = 0; ii < properties.length; ii++) {
			if (properties[ii] == propertyId) {
				propertyIdx = ii;
			}
		}

		if (propertyIdx < 0) {
			return;
		} else {
			properties.splice(propertyIdx, 1);
		}

		if (properties.length > 0) {
			save();
		} else {
			_cookie.unload();
		}
		alert("Property " + propertyId + " removed from wishlist.");
	}

	/**
	 * Returns true if the specified property ID exists in the wishlist,
	 * otherwise false.
	 *
	 * @return True if the wishlist contains the property, otherwise false.
	 */
	this.contains = function(propertyId) {
		if (properties == null) {
			return false;
		}
		for (var ii = 0; ii < properties.length; ii++) {
			if (properties[ii] == propertyId) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Private helper method that populates the list of property IDs from the
	 * user's cookie.
	 */
	function load() {
		var propertiesStr = _cookie.getValue();
		properties = (propertiesStr == null) ? null : propertiesStr.split(',');
	}

	/**
	 * Private helper method that saves the list of property IDs to the user's
	 * cookie.
	 */
	function save() {
		_cookie.setValue(properties.join(','));
	}

	// Load stored values on initialisation
	load();
}