function populateProductPreviewBox(data, target, template, show_next, page) {
	// 'data.length' is not present for some reason in some browsers, so counting manually
	count = 0;
	for (key in data) {
		count++;
	}
	$(target+' .items > .details_recently_item').remove();
	for (key in data) {
		cur_product = data[key];
		$(target+' .details_container .items').append(mergeHtmlBlock(template, cur_product));
	}
	if (show_next) {
		$(target+' .details_next_button a').show();
	}
	else {
		$(target+' .details_next_button a').hide();
	}
	if (page == 1) {
		$(target+' .details_previous_button a').hide();
	}
	else {
		$(target+' .details_previous_button a').show();
	}
}

$(document).ready(function(){

	$('#wishlist').click(function(e) {
		e.preventDefault();
		initPopup('#popupwishlist');

		$.get('/wishlist', { ajax: true, product_id: $('#product_id').val() } , function (responseJson) {

			if (responseJson.errors) {
				$('#popupwishlist .errorbox').html(responseJson.errors);
				$('#popupwishlist .errorbox').show();

			} else if (responseJson.correct) {
				$('#popupwishlist .correctbox').html(responseJson.correct);
				$('#popupwishlist .correctbox').show();
			}

		}, 'json');
	});

	$('.askquestion').click(function(e) {
		e.preventDefault();

		if ($(this).hasClass('popupquestion')) {
			initPopup('#customer-questions-popup');

		} else {
			$('#customer-questions_form').show();
		}
	});

	$('.remindstockpopup').livequery('click', function(e) {
		e.preventDefault();

		initPopup('#popupremindstock');

	});

	$('#remind_stock').livequery('submit', function(e) {

		e.preventDefault();

		$.post('/products/remindstock', { ajax: true, product_id: $('#product_id').val(), variation_id: $('#variation_id').val(), reminder_email_address: $('#reminder_email_address').val() }, function (responseJson) {

					$('.errorbox').hide();
					$('.correctbox').hide();
					$('.infobubble .error-msg').hide();
					$('.error').removeClass('error');

					if (responseJson.errors) {
						$('.remindstock_error').show();
						for (x in responseJson.errors) {
							$('#' + x).parent().addClass('error');
						//	$('#' + x).parent().find('.infobubble .error-msg').html(responseJson.errors[x]);
						//	$('#' + x).parent().find('.infobubble .error-msg').show();
						}
					} else {
						$('.remindstock_correct').show();
					}

		}, 'json');


	});

	$('#customer-questions_form').livequery('submit', function (e) {
		e.preventDefault();

		$.post('/products/customer-questions', { ajax: true, product_id: $('#product_id').val(), customer_name: $('#customer_name').val(), customer_location: $('#customer_location').val(), customer_email: $('#customer_email').val(), customer_question_title: $('#customer_question_title').val(), customer_question: $('#customer_question').val() }, function (responseJson) {

				$('.errorbox').hide();
				$('.correctbox').hide();
				$('.infobubble .error-msg').hide();
				$('.error').removeClass('error');

				if (responseJson.errors) {
					$('#customer-questions_error').show();
					for (x in responseJson.errors) {
						$('#' + x).parent().addClass('error');
						$('#' + x).parent().find('.infobubble .error-msg').html(responseJson.errors[x]);
						$('#' + x).parent().find('.infobubble .error-msg').show();
					}
				} else {
					$('#customer-questions_correct').show();
				}

		}, 'json');
	});

	$('#emailtofriend').click(function(e) {
		e.preventDefault();

		$.get('/products/emailtofriend', { ajax_popup: true }, function (data) {
			$('#popupemailtofriend_content').html(data);
			initPopup('#popupemailtofriend');

			$('#emailtofriend_form').submit(function(e) {
				e.preventDefault();

				allFields = '';

				$('#emailtofriend_form input[type=text], #emailtofriend_form textarea').each(function(i) {
					allFields += $(this).attr('name') + "=" + $(this).val() + "&";
				});

				$.get('/products/emailtofriend', { ajax: true, all_fields: allFields, product_id: $('#product_id').val() }, function (responseJson) {

					$('.errorbox').hide();
					$('.correctbox').hide();
					$('.infobubble .error-msg').hide();
					$('.error').removeClass('error');

					if (responseJson.errors) {
						$('#emailtofriend_error').show();
						for (x in responseJson.errors) {
							$('#' + x).parent().addClass('error');
							$('#' + x).parent().find('.infobubble .error-msg').html(responseJson.errors[x]);
							$('#' + x).parent().find('.infobubble .error-msg').show();
						}
					} else {
						$('#emailtofriend_correct').show();
					}

				}, 'json');
			});
		});
	});

	$('.writereview').click(function(e) {
		e.preventDefault();
		showReviewForm();
	});

	$('#leaveamessage').click(function(e) {
		e.preventDefault();

		$.get('/products/leaveamessage', { ajax_popup: true }, function (data) {
			$('#popupleaveamessage_content').html(data);
			initPopup('#popupleaveamessage');

		});
	});

	var previously_viewed_current_page = 1;
	$('#details_previously .details_next_button a').click(function() {
		previously_viewed_current_page++;
		$.ajax({
			type: 'GET',
			url: '/ajax/Ajax_Products/getRecentlyViewed',
			data: {
				'argument[]': [ $('#product_id').val(), 0, previously_viewed_current_page ]
			},
			success: function(data) {
				populateProductPreviewBox(data['data'], '#details_previously', $('#recentlyViewedTemplate').html(), data['more'], previously_viewed_current_page);
			},
			dataType: 'json'
		});
		return false;
	});

	$('#details_previously .details_previous_button a').click(function() {
		if (previously_viewed_current_page > 1) {
			previously_viewed_current_page--;
			$('#details_previously .details_next_button a').show();
		}
		if (previously_viewed_current_page == 1) {
			$('#details_previously .details_previous_button a').hide();
		}
		$.ajax({
			type: 'GET',
			url: '/ajax/Ajax_Products/getRecentlyViewed',
			data: {
				'argument[]': [ $('#product_id').val(), 0, previously_viewed_current_page ]
			},
			success: function(data) {
				populateProductPreviewBox(data['data'], '#details_previously', $('#recentlyViewedTemplate').html(), data['more'], previously_viewed_current_page);
			},
			dataType: 'json'
		});
		return false;
	});

	var upsells_current_page = 1;
	$('#details_upsells .details_next_button a').click(function() {
		upsells_current_page++;
		$.ajax({
			type: 'GET',
			url: '/ajax/Ajax_Products/getUpsells',
			data: {
				'argument[]': [ $('#product_id').val(), 0, upsells_current_page ]
			},
			success: function(data) {
				populateProductPreviewBox(data['data'], '#details_upsells', $('#recentlyViewedTemplate').html(), data['more'], upsells_current_page);
			},
			dataType: 'json'
		});
		return false;
	});

	$('#details_upsells .details_previous_button a').click(function() {
		if (upsells_current_page > 1) {
			upsells_current_page--;
			$('#details_upsells .details_next_button a').show();
		}
		if (previously_viewed_current_page == 1) {
			$('#details_upsells .details_previous_button a').hide();
		}
		$.ajax({
			type: 'GET',
			url: '/ajax/Ajax_Products/getUpsells',
			data: {
				'argument[]': [ $('#product_id').val(), 0, upsells_current_page ]
			},
			success: function(data) {
				populateProductPreviewBox(data['data'], '#details_upsells', $('#recentlyViewedTemplate').html(), data['more'], upsells_current_page);
			},
			dataType: 'json'
		});
		return false;
	});

	$('#leaveamessage_form, .leaveamessage_form').livequery('submit', function(e) {
		e.preventDefault();

		allFields = '';

		$('#leaveamessage_form input[type=text], #leaveamessage_form textarea, .leaveamessage_form input[type=text], .leaveamessage_form textarea').each(function(i) {
			allFields += $(this).attr('name') + "=" + $(this).val() + "&";
		});

		$.get('/products/leaveamessage', { ajax: true, all_fields: allFields, product_id: $('#product_id').val() }, function (responseJson) {

			$('.errorbox').hide();
			$('.correctbox').hide();
			$('.infobubble .error-msg').hide();
			$('.error').removeClass('error');

			if (responseJson.errors) {
				$('#leaveamessage_error, .leaveamessage_error').show();
				for (x in responseJson.errors) {
					$('#' + x).parent().addClass('error');
					$('#' + x).parent().find('.infobubble .error-msg').html(responseJson.errors[x]);
					$('#' + x).parent().find('.infobubble .error-msg').show();
				}
			} else {
				$('#leaveamessage_correct, .leaveamessage_correct').show();
			}

		}, 'json');
	});

	$('#printpage').click(function(e) { e.preventDefault(); window.print(); })

	$('#review_title').livequery('keydown', function() {
		remainingLength = 60 - $('#review_title').val().length;
		$('#review_title_characters').html(remainingLength);
	});

	$('img[alt=Review Helpful]').parent().click(function(e) {
		e.preventDefault();
		$('.thanksnothelpful, .thankshelpful').hide();
		$(this).parent().parent().find('.thankshelpful').fadeIn();

		ratingId = $(this).parent().parent().attr('id').replace("reviewid", "");

		var info = $(this).parent().parent().find('.user_ratings');
		var info_parent = $(this).parent().parent().find('.user_ratings_info');

		$.get('/products/reviews', { ajax: true, review_id: ratingId, user_review_rating: '1' }, function (responseJson)  {
			info.html(responseJson);
			info_parent.fadeIn();
		}, 'json');

	});

	$('img[alt=Review Not Helpful]').parent().click(function(e) {
		e.preventDefault();
		$('.thanksnothelpful, .thankshelpful').hide();
		$(this).parent().parent().find('.thanksnothelpful').fadeIn();

		var info = $(this).parent().parent().find('.user_ratings');
		var info_parent = $(this).parent().parent().find('.user_ratings_info');

		ratingId = $(this).parent().parent().attr('id').replace("reviewid", "");
		$.get('/products/reviews', { ajax: true, review_id: ratingId, user_review_rating: '0' }, function (responseJson)  {
			info.html(responseJson);
			info_parent.fadeIn();

		}, 'json');
	});


	$('p input, p select, p textarea').focus(function() {
		$(this).parent().find('.infobubble .error-msg').not(':regex("^$")').parent().fadeIn(250);
	});
	$('p input, p select, p textarea').blur(function() {
		$(this).parent().find('.infobubble .error-msg').not(':regex("^$")').parent().fadeOut(100);
	});



	$('p input, p select, p textarea').focus(function() {
		$(this).parent().find('.infobubble').fadeIn(250);
	});
	$('p input, p select, p textarea').blur(function() {
		$(this).parent().find('.infobubble').fadeOut(100);
	});

	$('a.freegiftbutton').click(function(e) {
		e.preventDefault();
		$('#freegifts').slideDown();
	});
	$('#freegifts a').click(function(e) {
		e.preventDefault();
		$('#freegiftchosen span').html($(this).find('img').attr('alt'));
		$('#freegiftselector').hide();
		$('#freegiftchosen').show();
		$('#freegifts').slideUp();

	});

	$('.free_gift_add').livequery('click', function(e) {
		parent = $(this).parent();

		if(parent.find('.attribute_required') && parent.find('.attribute_required').val() == '') {
			parent.find('.attributes_error').html('Attribute Required');
			$(this).attr('checked', '');
		}
		else {
			$('#free_product_id').val($(this).val());
		}
	});

	initAttributes = function() {
		$('#attributes input[type=radio]').click(function() {
			$.post('?', { updateattributes: true, name: $(this).attr('name'), value: $(this).val() }, function(responseJson) {
				$('#attributes').replaceWith(responseJson.attributes);
				$('#product_images_dynamic').replaceWith(responseJson.images);
				$('.tooltip').tooltip({ showURL: false });
				$('.ourprice').html(responseJson.selected_variation_price);
//				$("a[rel^='prettyPhoto']").prettyPhoto({theme: 'dark_rounded'});
				initAttributes();
			}, 'json');
		});

		$('#attributes select').change(function() {
			$.post('?', { updateattributes: true, name: $(this).attr('name'), value: $(this).val() }, function(responseJson) {
				$('#attributes').replaceWith(responseJson.attributes);
				$('#product_images_dynamic').replaceWith(responseJson.images);
				$('.tooltip').tooltip({ showURL: false });
				$('.ourprice').html(responseJson.selected_variation_price);
//				$("a[rel^='prettyPhoto']").prettyPhoto({theme: 'dark_rounded'});
				initAttributes();
			}, 'json');
		});

		$('#attributes .image').each(function() {
			$(this).append('<span class="image_text">' + $(this).find('input[type=radio]:checked').parent().text() + '</span>');
			var attribute_id = $(this).attr('id').replace(/[^\d]/g, '');
			$(this).find('label').each(function() {
				var radioButtonLabel = $(this);
				$('<a href="#" class="tooltip" rel="nofollow" title="' + $(this).text() + '"><img src="/images/ac_product_attributes_data/attribute_image/resizeandpad:50:50/' + $(this).find('input[type=radio]').val() + '" alt="' + $(this).text() + '" /></a>').insertAfter(radioButtonLabel).click(function(e) {
					e.preventDefault();
					radioButtonLabel.find('input[type=radio]').attr('checked', 'checked').click();
				}).addClass(radioButtonLabel.find('input[type=radio]').is(':checked') ? 'selected' : '');
				radioButtonLabel.hide();
			});
		});

		$('#attributes .image a:first').each(function() {
			if ($(this).parent().find('a.selected').length == 0) {
			//	$(this).click();
			}
		});

		var attributesComplete = true;
		$('#attributes input[type=radio]').each(function() {
			if (!$('input[name="' + $(this).attr('name') + '"]:checked').val()) {
				attributesComplete = false;
			}
		});
		if (attributesComplete) {
			$('#add-to-basket').show();
		} else {
			$('#add-to-basket').hide();
		}
	}

	initAttributes();



});


