var curr_quick_look;


$(function() {
	$('.product').livequery(function(e) {
		var product = $(this);
		product.find('.add-to-basket-button').click(function(e) {
			if (attributesSelected(product.find('.attributes')) == false) {
				e.preventDefault();
			}
		});
	});
});


function attributesSelected(selector) {
	var attributesOk = true;
	var idName;

	$(selector).find('select.required, input[type=text].required, textarea.required').each(function() {
		if ($(this).attr('id') && $(this).attr('id').match(/attribute_option_[0-9]+/)) {

			idInfo = $(this).attr('id').split("_");
			idName = idInfo[2];
		}

	    if (!$(this).val()) {
			attributesOk = false;

			if (idName) {
				$('.attribute_error_' + idName).show();
			} else {
				$(this).closest('.attribute').find('.error').show();
			}
		} else {
			if (idName) {
				$('.attribute_error_' + idName).hide();
			} else {
				$(this).closest('.attribute').find('.error').hide();
			}
		}

	});

	return attributesOk;
}


$(function() {

	$('a[rel*=prettyPhoto]').livequery(function() {
		$('a[rel*=prettyPhoto]').lightBox({
			imageLoading:  '/templates/' + templates_dir + '/_js/jquery-plugins/lightbox/images/lightbox-ico-loading.gif', // (string) Path and the name of the loading icon
			imageBtnPrev:  '/templates/' + templates_dir + '/_js/jquery-plugins/lightbox/images/lightbox-btn-prev.gif',    // (string) Path and the name of the prev button image
			imageBtnNext:  '/templates/' + templates_dir + '/_js/jquery-plugins/lightbox/images/lightbox-btn-next.gif',    // (string) Path and the name of the next button image
			imageBtnClose: '/templates/' + templates_dir + '/_js/jquery-plugins/lightbox/images/lightbox-btn-close.gif',   // (string) Path and the name of the close btn
			imageBlank:    '/templates/' + templates_dir + '/_js/jquery-plugins/lightbox/images/lightbox-blank.gif',       // (string) Path and the name of a blank image (one pixel)
			fixedNavigation: true
		});
	});
	
	
	$('.tabs').livequery(function() {
		$(this).tabs();
	});

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

		$('#popupinfoheader').html($(this).attr('title'));

		$.get($(this).attr('href'), function(data) {
			$('#popupinfo .scrollingcontent').html(data);
			$('#popupinfo ul.tabs').tabs('select', 2);
			initPopup('#popupinfo'); 


		}); 

	});


	/*
	 * Make sure all attributes are selected, and error if not.
	 *
	 */
	$('#quicklook_addtobasket').livequery('submit', function(e) {

		if ($(this).attr('id') == 'quicklook_addtobasket') {
			divId = '#popupattributes';
		} else {
			divId = '#attributes';
		}

		var errors = [];
		$(divId + ' .errors').hide();
		$(divId + ' select').each(function() {
			if ($(this).is('select')) {
				if (!$(this).val()) {
					errors.push($(this).attr('name').replace(/[^\d]/g, ''));
				}
			} 
		}); 
		
		$(divId + ' div.attribute.radio').each(function() {
			if (!$(this).find('input]:checked:enabled').length) {
				errors.push($(this).attr('name').replace(/[^\d]/g, ''));
			}
		});
		
		if (errors.length) {
			e.preventDefault();
			for(var i=0;i<errors.length;i++) {
				$('*[name="attributes['+errors[i]+']"]').addClass('error_select');
			}
			$.get('/products/attribute-errors/', { action: 'checkattributes', errors: errors.join(',') }, function(responseText) {
				$('.errors').html(responseText);
				$('#attributes .errors, #popupattributes .errors').show();
			});

		}
	});
	
	/*
	 * Image rollovers.  Any image with class "rollover" will have _on 
	appended to the filename (excluding extension) on over, and removed 
	on blur.
	 *
	 */

	$('img.rollover:not(.active), input.rollover:not(.active)').livequery(function() {
		$(this).hover(
			function () {
				$(this).attr('src', $(this).attr('src').replace(/\.([^\.]*)$/, '_on.$1'));
			},
			function() {
				$(this).attr('src', $(this).attr('src').replace(/_on\.([^\.]*)$/, '.$1'));
			}
			);
		});
	
	/*
	 * Quicklook
	 *
	 */
	
	$('#productgrid li, #productlist li, #productwindow li, #productselling li, #crosssell li, #previouslyviewed li').livequery(function() {
		$(this).hover(
			function() {
				$(this).find('.quicklookbutton').fadeIn(250);
			},
			function() {
				$(this).find('.quicklookbutton').fadeOut(250);
			}
		);
	});


	$('.quicklookbutton').click(function(e) {
		e.preventDefault();
		// quick look behaviour goes here
	});

	$('.closeminibasket').livequery('click', function(e) {
		e.preventDefault();
		$('#minibasketadded').fadeOut(200, function() {
			$('#mini_basket').hide("slide", { direction: "up" }, 1000);
			$('#minibasketdefault').show();
		});

	});


	$('#quicklook_addtobasket, form.add-to-basket-ajax').livequery('submit', function(f) {

			f.preventDefault();


			allFields = '';
			if ($(this).hasClass('add-to-basket')) {
			$('#attributes select, #attributes input:radio:checked').each(function(i) {
				allFields += $(this).attr('name') + "=" + $(this).val() + "&";
				});

			productId = $(this).find('input[name=product_id]').val();
			productQuantity = $(this).find('input[name=product_quantity]').val();
			// productId = $('#product_id').val();
			// productQuantity = $('#product_quantity').val();

			} else {
			$('#popupquicklook select, #popupquicklook input:radio:checked').each(function(i) {
				allFields += $(this).attr('name') + "=" + $(this).val() + "&";
				});
			productId = $('#ql_product_id').val();
			productQuantity = $('#ql_product_quantity').val();
			}

			// popupattributes


			$('#minibasketdefault').hide();
			$('#minibasketadded').show();
			$.post('/basket', { ajax: true, quicklook: true, product_id: productId, product_quantity: productQuantity, attributes: allFields }, function (responseJson) {
            
				disablePopup('#popupquicklook');
				$('#mini_basket').html(responseJson[0]);
				$('#mini_basket').show("slide", { direction: "up" }, 1000);
				$('#minibasketitems').html(responseJson[1]);
				$('.checkoutbutton').show();
				$.scrollTo($('#toplinks'));
            
			}, 'json');



	});

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

		if ($('#mini_basket').is(':visible')) {
			$('#mini_basket').hide("slide", { direction: "up" }, 1000);
			$('#minibasketadded').hide();
			$('#minibasketdefault').show();
		}
		curr_quick_look = $(this).attr('rel');
		$.get('/products/', { ajax: true, quick_view: $(this).attr('rel') }, function (responseJson) {
			$('#popupquicklook').html(responseJson[0]);
			initPopup('#popupquicklook');
			$('.tooltip').tooltip({ showURL: false });
			if (initAttributes) initAttributes();
			$('#tabs').tabs();


			
			setTimeout("$('#attributes .image a:first').each(function() { if ($(this).parent().find('.selected').length == 0) { $(this).click(); } });", 500);
			
		}, 'json');
		
	});
	
	/*
	 * .fielddescriptionlink tooltips
	 *
	 */
	$('.tooltip').livequery(function() {
		$(this).tooltip({ showURL: false });
	})
	
	/*
	 * Quicklook images
	 *
	 */
	$('#quicklookimages a').livequery('click', function(e) {
		e.preventDefault();
		$('#quicklookimages img:first').attr('src', $(this).attr('href'));
	});
	
});



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

			allFields = '';

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

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

				$('#review_form .error').removeClass('error');
				$('.infobubble').hide();
				$('.infobubble .error-msg').html('').hide();

				$('#review_errors').hide();
				$('#review_correct').hide();
				$('#review_info').hide();

				if (responseJson.errors) {
					$('#review_errors').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();
					if (x.match(/duplicate/)) {	
						$('#review_errors_list').html(responseJson.errors[x]);
					}
				}

				} else if (responseJson.info) {
					$('#review_info').html(responseJson.info);
					$('#review_info').show();

				} else {
					$('#review_correct').html(responseJson.correct);
					$('#review_correct').show();
				}

			}, 'json');
	});
}



function showReviewForm (reviewId) {

	var reviewSection = (("https:" == document.location.protocol) ? "i-want-https" : "i-want-no-https");

	$.get('/products/reviews', { ajax_popup: true, product_id: $('#product_id').val(), review_id: reviewId, reviewSection: true }, function (data) {
		$('#popupwritereview_content').html(data);
		initPopup('#popupwritereview'); 
		updateReviewForm();
	});
}

			$(function() {
				$('.askquestion').click(function(e) {
					e.preventDefault();
					$('#customer-questions_form').show();
				});

				$('.showanswer').click(function(e) {
					e.preventDefault();
						
					if ($(this).parent().parent().find('.qanswers').is(':visible')) {
						$(this).parent().parent().find('.qanswers').hide("slide", { direction: "up" }, 1000);
					} else {

					$('.qanswers').hide("fast", function() {
					});
						$(this).parent().parent().find('.qanswers').show("slide", { direction: "up" }, 1000);
					}
				});

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

					if ($(this).html() == 'Show all answers') {
						$('.qanswers').show("slide", { direction: "up" }, 1000);
						$(this).html('Hide all answers');
					} else {
						$('.qanswers').hide("slide", { direction: "up" }, 1000);
						$(this).html('Show all answers');
					}

				});

				$('.opennewwindow').livequery('click', function(e) {
					e.preventDefault();
					window.open($(this).attr('href'));
				});
			});


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

			$('#popupemail_signup_content').removeClass('errorbox, correctbox');

			if (!$('#email_signup').val().match(/^[^@\s<&>]+@([-a-z0-9]+\.)+[a-z]{2,}$/i)) {
				$('#popupemail_signup_content').addClass('errorbox');
				$('#popupemail_signup_content').html('Your e-mail address is invalid');
				initPopup('#popupemail_signup');
			} else {

			$.post('/newsletter', { ajax: true, submit_email_signup: true, email_signup: $('#email_signup').val() }, function (responseJson) {
				initPopup('#popupemail_signup');
				if (responseJson.errors) {
					$('#popupemail_signup_content').addClass('errorbox');
					$('#popupemail_signup_content').html(responseJson.errors);
				} else {
					$('#popupemail_signup_content').addClass('correctbox');
					$('#popupemail_signup_content').html(responseJson.correct);
				}
				}, 'json');

			}

		});
});

$(function() {
	$('a.viewmore').click(function(e) {
		e.preventDefault();
		$(this).prev('ul').find('li.hiddenfilter').slideDown();
		$(this).hide();
		$(this).next('.viewless').show();
		});
	$('a.viewless').click(function(e) {
		e.preventDefault();
		$(this).prev().prev('ul').find('li.hiddenfilter').slideUp();
		$(this).prev('.viewmore').show();
		$(this).hide();
	});
}); 	
