$(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();
		}
	});

	$('#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'); 

		});
	});

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

				allFields = '';

				console.log($(this));

				$('#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();
		
	});
	
	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 });
//				$("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/' + $(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();

    $('.sizelist').find('a').click(function()
    {
        $('.sizelist').find('a').removeClass('selected');
        $(this).addClass('selected');
        $(this).closest('ul').prev('select').val($(this).attr('href'));
        $('#product_quantity').attr('disabled', '');

        var allFields = '';
        $('#productdescription').find('#attributes select').each(function(i)
        {
		    allFields += $(this).attr('name') + "=" + $(this).val() + "&";
		});

		$.post('?', { ajax: true, attributes: allFields, product_id: $('#product_id').val() }, function (responseJson)
        {
				variation_stock = responseJson.variation_stock > 5 ? '5': responseJson.variation_stock;

				if (variation_stock > 0) {
					$('#product_quantity').removeAttr('disabled');
				} else {
					$('#product_quantity').attr('disabled', 'disabled');
				}

				 var saveOptions = '';


				 for (i = 0; i < variation_stock; i++) {
				 	saveOptions += '<option value="' + (i+1) + '">' + (i+1) + '</option>';
				}

				// $('.code').html(responseJson.variation_reference);
				//		$('.ourprice').html(responseJson.variation_price);

				$('#product_quantity').html(saveOptions);

	    }, 'json');

        return false;
    });
	
    /**
     * product images (prev/next)
     */
    $('#thumbs').find('li.next').find('a').click(function()
    {
        var visibleList = $('#thumbs').find('ul.productthumbs').filter(function()
        {
            return ($(this).find('img:visible').length ? true : false);
        }).each(function()
        {
            var nextList = $(this).next('ul.productthumbs').filter(function()
            {
                return ($(this).find('img:hidden').length ? true : false);
            });
            if (nextList.length)
            {
                $(this).find('img').fadeOut('normal', function()
                {
                    nextList.each(function()
                    {
                        $(this).find('img').fadeIn();

                        var fadeNextButton = false;
                        var nextPrevList = $(this).prev('ul.productthumbs').filter(function()
                        {
                            return ($(this).find('img:hidden').length ? true : false);
                        });

                        if (nextPrevList.length)
                        {
                            fadeNextButton = true;
                        }

                        var nextNextList = $(this).next('ul.productthumbs').filter(function()
                        {
                            return ($(this).find('img:hidden').length ? true : false);
                        });

                        if (!nextNextList.length)
                        {
                            if (fadeNextButton)
                            {
                                $('#thumbs').find('li.next').fadeOut('normal', function()
                                {
                                    $('#thumbs').find('li.previous').fadeIn();
                                });
                            }
                            else
                            {
                                $('#thumbs').find('li.next').fadeOut();
                            }
                        }
                        else
                        {
                            if (fadeNextButton)
                            {
                                $('#thumbs').find('li.previous').fadeIn();
                            }
                        }
                    });
                });
            }
        });
        return false;
    });
    
    $('#thumbs').find('li.previous').find('a').click(function()
    {
        var visibleList = $('#thumbs').find('ul.productthumbs').filter(function()
        {
            return ($(this).find('img:visible').length ? true : false);
        }).each(function()
        {
            var nextList = $(this).prev('ul.productthumbs').filter(function()
            {
                return ($(this).find('img:hidden').length ? true : false);
            });
            if (nextList.length)
            {
                $(this).find('img').fadeOut('normal', function()
                {
                    nextList.each(function()
                    {
                        $(this).find('img').fadeIn();

                        var fadeNextButton = false;
                        var nextPrevList = $(this).next('ul.productthumbs').filter(function()
                        {
                            return ($(this).find('img:hidden').length ? true : false);
                        });

                        if (nextPrevList.length)
                        {
                            fadeNextButton = true;
                        }

                        var nextNextList = $(this).prev('ul.productthumbs').filter(function()
                        {
                            return ($(this).find('img:hidden').length ? true : false);
                        });

                        if (!nextNextList.length)
                        {
                            if (fadeNextButton)
                            {
                                $('#thumbs').find('li.previous').fadeOut('normal', function()
                                {
                                    $('#thumbs').find('li.next').fadeIn();
                                });
                            }
                            else
                            {
                                $('#thumbs').find('li.previous').fadeOut();
                            }
                        }
                        else
                        {
                            if (fadeNextButton)
                            {
                                $('#thumbs').find('li.next').fadeIn();
                            }
                        }
                    });
                });
            }
        });

        return false;
    });

});


