var timeout;

function markReviewHelpful(reviewId, helpful)
{
	$.getJSON('/ajax/product/review-helpful.dyn?reviewId=' + reviewId + '&helpful=' + helpful,
		function (data)
		{
			document.getElementById('reviewHelpfulSubmitted[' + reviewId + ']').style.display = 'inline';
			document.getElementById('reviewHelpfulSubmitted[' + reviewId + ']').innerHTML = ' ' + data.response;
			document.getElementById('reviewHelpfulForm[' + reviewId + ']').style.display = 'none';
			document.getElementById('reviewHelpfulScore-' + reviewId).innerHTML = data.helpfulScore;
		}
	);
}

function removeFromWishlist(productId, elementId)
{
	var requestUrl = '/ajax/product/toggle-wishlist/product/' + productId + '/';

	$.getJSON(requestUrl, function (data) {
		$('#' + elementId).fadeOut();
	});

	return true;
}

function toggleWishlist(productId)
{
	var requestUrl = '/ajax/product/toggle-wishlist/product/' + productId + '/';

	$('#wishlistButton').addClass('loading')
						.html('Adding...');

	$.getJSON(requestUrl, function (data) {
		var wishlistUrl = $('#wishlistUrl').val();

		$('#wishlistButton').replaceWith('<span class="button done">On your <a href="' + wishlistUrl + '">Wish List</a></span>');
		var wishlistTitle = '<a class="notificationLink" href="' + wishlistUrl + '">Change email notifications</a>';

		$('#wishlistTitle').html(wishlistTitle);
		$('#wishlistOptions-' + productId).find('div.alerts').html(data.alertsHtml);

		wishlistHelper.initialiseWishlistNotifications(productId);
		wishlistHelper.toggleNotificationsPopup(productId);
	});

	return false;
}

function toggleCollection(productId)
{
	var requestUrl = '/ajax/product/toggle-collection/product/' + productId + '/';

	$('#collectionButton').addClass('loading')
						  .html('Adding...');

	$.getJSON(requestUrl, function (data) {
		switch (data.response) {
			case 'added':
				$('#collectionButton').replaceWith('<span class="button done">In your <b>Collection</b></span>');

				var collectionUrl = $('#collectionUrl').val();
				var collectionTitle = '<a href="' + collectionUrl + '">View your Collection</a>';

				$('#collectionTitle').html(collectionTitle);
				break;
			default:

				break;
		}
	});
}


var productRaters = new Array();

function ProductRater(productId, defaultRatingText, mode)
{
	this.productId = productId;
	this.defaultRatingText = defaultRatingText;
	this.mode = mode;

	this.container = $('#productRating' + productId);
	this.userRating = null;

	this.setStars = function(number, name)
	{
		this.container.find('.ratingText').html(name);
	}

	this.clearStars = function()
	{
		if (this.userRating === null) {
			if (this.mode == 1) {
				this.container.find('.ratingText').html(this.defaultRatingText);
			}
			else {
				this.container.find('.ratingText').html('');
			}
		}
		else {
			this.container.find('.ratingText').html('Thanks for your vote!');
		}
	}

	this.rateProduct = function(rating)
	{
		var requestUrl = '/ajax/product/rate/rating/' + rating + '/product/' + this.productId + '/';

		$.getJSON(requestUrl, $.proxy(function (data) { this.handleResponse(rating, data); }, this));
	}

	this.handleResponse = function(rating, data)
	{
		this.userRating = rating;
		this.defaultRatingText = data.averageText;
		this.container.find('.ratingText').html(data.response);

		var ratingList = this.container.find('.rating');
		ratingList.removeClass()
				  .addClass('rating');

		switch (rating) {
			case 1:
				ratingList.addClass('onestar');
				break;
			case 2:
				ratingList.addClass('twostar');
				break;
			case 3:
				ratingList.addClass('threestar');
				break;
			case 4:
				ratingList.addClass('fourstar');
				break;
			case 5:
				ratingList.addClass('fivestar');
				break;
		}

		this.container.addClass('rated');
	}
}

function setProductAlert(productId, eventId, value)
{
	var newValue;
	var alertElement = $('#liAlert' + eventId);
	var alertStatusElement = $('#liAlert' + eventId + 'Status');

	if (value == true) {
		newValue = 1;
	} else {
		newValue = 0;
	}

	alertStatusElement.html('');
	alertElement.addClass('processing');

	$.getJSON('/ajax/product/alert.dyn?productId=' + productId + '&eventId=' + eventId + '&value=' + newValue,
		function (data)
		{
			alertElement.removeClass('processing');
			alertStatusElement.html(data.response);
			if (newValue == 1) {
				alertElement.animate( {backgroundColor: '#e9f7c7'} );
			} else {
				alertElement.animate( {backgroundColor: '#fff'} );
			}
		}
	);
}

function subscribeToNewsletter(newsletterId)
{
	$.get('/ajax/newsletter/subscribe/list/'+newsletterId+'/', null,
		function(data, textStatus) {
			$('#newsletter-subscribe-box p').html('Thanks, you have been subscribed! Unsubscribe at any time from My Account.');
			$('#newsletter-subscribe-box div.button').remove();

			setTimeout(function() {
				$('#newsletter-subscribe-box').slideUp();
			}, 5000);
		}
	);
}

function logProductImpression(productId, versionId, ts)
{
	$.get('/ajax/product/impression/productId/' + productId + '/versionId/' + versionId + '/ts/' + ts + '/');
	eraseCookie('linkRef');
}

function updateOrderCutoffTimer (productId) {
	var orderCutoffTimerStartVal = $('#orderCutoffTimer').html();
	if (orderCutoffTimerStartVal != null) {
		$.getJSON("/ajax/product/get-order-cutoff-timer/productId/" + productId + "/", function(data) {
			if (data.seconds <= 0) {
				window.location.reload(false);
			}
			$('#orderCutoffTimer').html(data.response);
		});
		setTimeout("updateOrderCutoffTimer(" + productId + ")", 60000);
	}
}

function messageFeedback(messageId, feedback)
{
	$.getJSON('/ajax/customers/message-feedback/messageId/' + messageId + '/feedback/' + feedback + '/', function(data) {
		if (feedback == 1) {
			$('#smiley-happy').removeClass('happy-active').addClass('happy');
			$('#smiley-sad').removeClass('sad-active').addClass('sad');
			$('#smiley-indifferent').removeClass('indifferent').addClass('indifferent-active');
		} else if (feedback == 2) {
			$('#smiley-happy').removeClass('happy').addClass('happy-active');
			$('#smiley-sad').removeClass('sad-active').addClass('sad');
			$('#smiley-indifferent').removeClass('indifferent-active').addClass('indifferent');
		} else if (feedback == 3) {
			$('#smiley-happy').removeClass('happy-active').addClass('happy');
			$('#smiley-sad').removeClass('sad').addClass('sad-active');
			$('#smiley-indifferent').removeClass('indifferent-active').addClass('indifferent');
		}
		$('#message-feedback-thanks').html(data.response);
	});

	return false;
}

/* REVIEW OVERLAY */

function ReviewOverlayWindow(productId, reviewUrl)
{
	$.extend(this, new OverlayWindow('reviewOverlay'));

	this.productId = productId;
	this.minimisedHeight = 120;
	this.maximisedHeight = 420;
	this.outerBoxHeightDelta = 22;
	this.reviewUrl = reviewUrl;

	this.beforeOpen = function()
	{
		$('#'+this.id).removeClass('success');
	}

	// method to load the data (content)
	this.load = function()
	{
		this.XHR = $.ajax(
		{
			url: reviewUrl
		,	type: 'get'
		,	data: { format: 'json' }
		,	cache: false
		,	timeout: 30 * 1000
		,	dataType: 'json'
		,	context: this
		,	success: function(data, textStatus, XHR)
			{
				switch (data.status) {
					case 3:
						// not signed in
						window.location.href = this.reviewUrl;
						break;
					default:
						this.render(data);
						break;
				}
			}
		,	error: function (XHR, textStatus, errorThrown)
			{
				alert('An error occurred: ' + textStatus + '\n\n' + 'Please click the Write a Review button again to retry.');
				this.close();
			}
		});
	}

	this.submit = function()
	{
		this.XHR = $.ajax(
		{
			url: reviewUrl
		,	type: 'post'
		,	data: { format: 'json', reviewSubject: $('#reviewSubject').val(), reviewBody: $('#reviewBody').val(), reviewRating: $('#reviewRating').val() }
		,	cache: false
		,	timeout: 30 * 1000
		,	dataType: 'json'
		,	context: this
		,	success: function(data, textStatus, XHR)
			{
				switch (data.status) {
					case 1:
						// success
						this.render(data);

						$('#'+this.id).addClass('success');

						$('#'+this.id+'OuterBox').delay(0).animate({ height: this.minimisedHeight + this.outerBoxHeightDelta}, 'slow');
						$('#'+this.id+'Content').delay(0).animate({ height: this.minimisedHeight }, 'slow');

						// hide review button on collection/product list
						$('#writeReview' + productId).hide();
						break;
					case 2:
						// error
						this.render(data);
						break;
					case 3:
						// not signed in
						window.location.href = this.reviewUrl;
						break;
				}
			}
		,	error: function (XHR, textStatus, errorThrown)
			{
				alert('An error occurred: ' + textStatus + '\n\n' + 'Please click the Submit Review button again to retry.');
				this.close();
			}
		});
	}

	// method to take the loaded data and render it
	this.render = function (data)
	{
		$('#'+this.id).removeClass('loading');
		$('#'+this.id).removeClass('error');

		$('#'+this.id+'Content').html(data.html);

		if (data.errorMessages != null && data.errorMessages.length > 0) {
			var messageString = '';
			for (var i = 0; i < data.errorMessages.length; i++) {
				messageString += data.errorMessages[i] + "\n";
			}

			alert(messageString);
		}
	}
}

var reviewOverlayWindowInstance = null;

function openReviewOverlay(productId, reviewUrl, button, e)
{
	if (reviewOverlayWindowInstance) reviewOverlayWindowInstance.cleanup();

	reviewOverlayWindowInstance = new ReviewOverlayWindow(productId, reviewUrl);
	return reviewOverlayWindowInstance.open(e, button);
}

function closeReviewOverlay()
{
	reviewOverlayWindowInstance.close();
}

function setReviewStars(number)
{
	$('#reviewRating').val(number);
	$('#reviewRatingList').removeClass().addClass('rating');

	switch (number) {
		case 1:
			$('#reviewRatingList').addClass('onestar');
			break;
		case 2:
			$('#reviewRatingList').addClass('twostar');
			break;
		case 3:
			$('#reviewRatingList').addClass('threestar');
			break;
		case 4:
			$('#reviewRatingList').addClass('fourstar');
			break;
		case 5:
			$('#reviewRatingList').addClass('fivestar');
			break;
	}
}

function AccountHelper()
{
	this.removeFromCollection = function(productId)
	{
		var requestUrl = '/collection/remove/' + productId + '/';

		$.ajax(
		{
			url: requestUrl
		,	type: 'post'
		,	data: { format: 'json' }
		,	cache: false
		,	timeout: 30 * 1000
		,	dataType: 'json'
		,	context: this
		,	success: function(data)
			{
				this.productRemoved(productId, data)
			}
		});
	}

	this.removeFromWishlist = function(productId)
	{
		var requestUrl = '/wishlist/remove/' + productId + '/';

		$.ajax(
		{
			url: requestUrl
		,	type: 'post'
		,	data: { format: 'json' }
		,	cache: false
		,	timeout: 30 * 1000
		,	dataType: 'json'
		,	context: this
		,	success: function(data)
			{
				this.productRemoved(productId, data)
			}
		});
	}

	this.productRemoved = function(productId, data)
	{
		$('#productRow' + productId).fadeOut('slow', function () {
			$(this).remove();
		});
	}

	this.toggleNotificationsPopup = function(productId)
	{
		$('#wishlistOptions-' + productId).find('div.notificationsPopup').toggle();

		return false;
	}

	this.toggleWishlistCommentPopup = function(productId)
	{
		$('#wishlistOptions-' + productId).find('div.wishlistCommentPopup').toggle();

		return false;
	}

	this.saveWishlistComment = function(productId)
	{
		var comment = $('#wishlistOptions-' + productId).find('textarea.commentBox').val();

		this.updateWishlistComment(productId, comment);

		return false;
	}

	this.deleteWishlistComment = function(productId)
	{
		$('#wishlistOptions-' + productId).find('textarea.commentBox').val('');

		this.updateWishlistComment(productId, '');

		return false;
	}

	this.updateWishlistComment = function(productId, comment)
	{
		var requestUrl = '/wishlist/save-comment/'  + productId + '/';

		this.XHR = $.ajax(
		{
			url: requestUrl
		,	type: 'post'
		,	data: { format: 'json', comment: comment }
		,	cache: false
		,	timeout: 30 * 1000
		,	dataType: 'json'
		,	context: this
		,	success: function(data, textStatus, XHR)
			{
				$('#wishlistOptions-' + productId).find('div.wishlistCommentPopup').hide();
				$('#wishlistOptions-' + productId).find('div.wishlistComment').replaceWith(data.comment).show();

				wishlistHelper.initialiseWishlistCommenting(productId);
			}
		,	error: function (XHR, textStatus, errorThrown)
			{
				alert('An error occurred: ' + textStatus + '\n\n' + 'Please click the Save button again to retry.');
			}
		});
	}

	this.toggleWishlist = function(productId)
	{
		var requestUrl = '/ajax/product/toggle-wishlist/product/' + productId + '/';

		$('#wishlistButton').addClass('loading')
							.html('Adding...');

		$.getJSON(requestUrl, function (data) {
			switch (data.response) {
				case 'added':
					var wishlistUrl = $('#wishlistUrl').val();

					$('#wishlistButton').replaceWith('<span class="button done">On your <a href="' + wishlistUrl + '">Wish List</a></span>');
					var wishlistTitle = '<a class="notificationLink" href="' + wishlistUrl + '">Change email notifications</a>';

					$('#wishlistTitle').html(wishlistTitle);
					break;
				default:
					break;
			}
		});
	}

	this.updateWishlistPriority = function(productId)
	{
		var priority = $('#wishlistOptions-' + productId).find('select.prioritySelect').val();

		var requestUrl = '/wishlist/save-priority/'  + productId + '/';

		this.XHR = $.ajax(
		{
			url: requestUrl
		,	type: 'post'
		,	data: { format: 'json', priority: priority }
		,	cache: false
		,	timeout: 30 * 1000
		,	dataType: 'json'
		,	context: this
		,	success: function(data, textStatus, XHR)
			{
				$('#wishlistOptions-' + productId).find('label.priorityLabel').html('Saved!').addClass('saved');
			}
		,	error: function (XHR, textStatus, errorThrown)
			{
				alert('An error occurred: ' + textStatus + '\n\n' + 'Please click the Save button again to retry.');
			}
		});
	}

	this.initialiseWishlistCommenting = function(productId)
	{
		var wishlistContainer = $('#wishlistOptions-' + productId);
		var noteLink = $(wishlistContainer).find('a.note');
		var comment = $(wishlistContainer).find('textarea.commentBox');
		var commentBox = $(wishlistContainer).find('div.wishlistComment');
		var commentForm = $(wishlistContainer).find('form.saveComment');
		var commentContainer = $(wishlistContainer).find('div.wishlistComment div.comment');

		if ($(comment).val().length > 0) {
			$(commentBox).show();
			$(noteLink).hide();
		}
		else {
			$(commentBox).hide();
			$(noteLink).show();
		}

		noteLink.click(function() {
			return wishlistHelper.toggleWishlistCommentPopup(productId);
		});

		commentForm.submit(function() {
			return wishlistHelper.saveWishlistComment(productId);
		});

		commentContainer.click(function() {
			return wishlistHelper.toggleWishlistCommentPopup(productId);
		});
	}

	this.initialiseWishlistNotifications = function(productId, productPage)
	{
		var wishlistContainer = $('#wishlistOptions-' + productId);
		var notificationsLink = $(wishlistContainer).find('a.notificationLink');
		var closeLink = $(wishlistContainer).find('div.notificationsPopup a.close');

		notificationsLink.click(function() {
			return wishlistHelper.toggleNotificationsPopup(productId);
		});

		closeLink.click(function() {
			return wishlistHelper.toggleNotificationsPopup(productId);
		});
	}

	this.initialiseWishlistNotificationsNotOnWishlist = function(productId)
	{
		var wishlistContainer = $('#wishlistOptions-' + productId);
		var notificationsLink = $(wishlistContainer).find('a.notificationLink');

		notificationsLink.click(function() {
			return toggleWishlist(productId);
		});
	}

	this.initialiseWishlistPriorityUpdates = function(productId)
	{
		var wishlistContainer = $('#wishlistOptions-' + productId);

		$(wishlistContainer).find('select.prioritySelect').change(function () {
			wishlistHelper.updateWishlistPriority(productId);
		});
	}
}
