BT.ns(function() {with(BT) {
	Product_wishlist = {
		product_id: false,
		attribute_key: false,
		model_id: false,
		bind_wishlist: function() {
			var self = this;
			var product_id = $('product_id');
			if (product_id) {
				this.product_id = product_id.value;
			}
			Event.observe('add_to_wishlist', 'click', function(e) {
				e.stop();
				if (self.product_id) {
					var attributes = [];
					var index = 0;
					var attribute_fields = $$('div.product_attributes select');
					if (attribute_fields != '') {
						attribute_fields.each(function(e) {
							attributes[index] = e.value;
							++index;
						});
					} else {
						$$('input.attributes').each(function(e) {
							attributes[index] = e.value;
							++index;
						});
					}
					attributes.sort(function(a, b) {return b - a});
					self.attribute_key = attributes.join(';');
				} else {
					var model_input = $$('select[name=model_id]');
					if (!model_input) {
						$$('input[name=model_id]');
					}
					self.model_id = model_input[0].value;
				}
				self.add_to_wishlist();
			});
			Event.observe('account_login', 'click', function(e) {
				e.stop();
				self.login();
			});
		},
		add_to_wishlist: function() {
			var self = this;
			var params;
			if (this.product_id) {
				params = '&product_id=' + this.product_id + '&attribute_key=' + this.attribute_key
			} else {
				params = '&model_id=' + this.model_id;
			}
			new Jument.ajax({
				url: '/ajax/cart/add',
				options: {
					parameters: 'add_to_wishlist=true' + params,
					onComplete: function(data) {self.handle_response(data)},
					onFailure: function() {alert('An error occurred. Please try again.');}
				}
			});
		},
		require_login: function() {
			Effect.Appear('require_login', {duration: 1});
		},
		login: function() {
			var self = this;
			new Jument.ajax({
				url: '/ajax/auth/login',
				form: 'login_form',
				options: {
					onComplete: function(data) {self.handle_response(data)},
					onFailure: function() {alert('An error occurred. Please try again.');}
				}
			});
		},
		handle_response: function(data) {
			if (data.added) {
				document.location = '/wishlist/edit';
			} else if (data.require_login) {
				this.require_login();
			} else if (data.login_success) {
				this.add_to_wishlist();
			} else if (data.login_error_msg) {
				$('require_login_error').update('<li>' + data.login_error_msg + '</li>');
				$('require_login_error').show();
			}
		}
	}
}});

Event.observe(window, 'load', function() {
	Product_wishlist.bind_wishlist();
});