var curr_quick_look;


$(function() {
/*
 * Deal with text area and input text-box character counters.
 */
        $('.char_counter').each(function() {
                $('#'+$(this).attr('target')).livequery('keydown keyup', function() {
                        referers = $('[target="'+$(this).attr('id')+'"]');
                        remaining_length = $(this).attr('maxlength') - $(this).val().length;

                        referers.html(remaining_length);
                });
        });
        $('.char_counter').keydown();

	$('.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 processingPopupStart() {
        if (!$('#popupprocessing').get(0)) {
                $('body').append($('<div id="popupprocessing" class="popup"><div class="popupcontent"><h3>Please wait...</h3><p>Your request is being processed...</p></div>'));
        }
        initPopup('#popupprocessing', true, true);
}

function processingPopupStop() {
        disablePopup('#popupprocessing');
}

$(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() {
		$('.tabs').tabs({ select: function(event, ui){ window.location = ui.tab.href; } });
	});

	$('.popupinfo').live('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('mouseover mouseout', function(event) {
        if (event.type == 'mouseover') {
            $(this).attr('src', $(this).attr('src').replace(/\.([^\.]*)$/, '_on.$1'));
        } else {
		    $(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();

		var lastIndex = $('#productgrid > li').index($('#productgrid > li:last'));
		var thisIndex = $('#productgrid > li').index($(this).closest('li'));
		var prevIndex = thisIndex-1;
		var nextIndex = thisIndex+1;

		if (!thisIndex) {
			/**
			 * first instance
			 */
			prevIndex = lastIndex;
		}

		if (thisIndex == lastIndex) {
			nextIndex = 0;
		}

		var previousItemID = $('#productgrid > li:eq('+prevIndex+')').find('a.quicklook').attr('rel');
		var nextItemID = $('#productgrid > li:eq('+nextIndex+')').find('a.quicklook').attr('rel');

	//	alert('Previous item id: '+previousItemID+' Next item id: '+nextItemID);

		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'), quick_view_previous: previousItemID, quick_view_next: nextItemID }, function (responseJson) {
			$('#popupquicklook').html(responseJson[0]);
			initPopup('#popupquicklook');
			$('.tooltip').tooltip({ showURL: false });
			if (initAttributes) initAttributes();
			$('#tabs').tabs();



			setTimeout("preSelectAttributes();", 350);

		}, '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 showTab(tabID)
{
    $('.tabs').find('a').removeClass('ui-state-active');
    $('.tabs').find('li').removeClass('ui-tabs-selected');
    $('.tabs').find('li').removeClass('ui-state-active');
    $('#'+tabID).parent().find('.tab_box:visible, .ui-tabs-panel:visible').hide();
    $('#'+tabID).show();
    $('.tabs').find('a[href="#'+tabID+'"]').closest('li').addClass('ui-state-focus');
    $('.tabs').find('a[href="#'+tabID+'"]').closest('li').addClass('ui-tabs-selected');
    $('.tabs').find('a[href="#'+tabID+'"]').closest('li').addClass('ui-state-active');
    $(document).scrollTop(0, 0);
}



function showReviewForm (reviewId) {

	var params = { ajax_popup: true, product_id: $('#product_id').val(), review_id: reviewId, reviewSection: true }
	var reviewSection = (("https:" == document.location.protocol) ? "i-want-https" : "i-want-no-https");
	params[reviewSection] = true;

	$.get('/products/reviews', params, function (data) {
		$('#popupwritereview_content').html(data);
		initPopup('#popupwritereview');
	});
}

$('#review_form').livequery('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() + "&";
		});

		var params = { ajax: true, all_fields: allFields, product_id: $('#product_id').val(), review_id: $('#hidden_review_id').val() }
		var reviewSection = (("https:" == document.location.protocol) ? "i-want-https" : "i-want-no-https");
		params[reviewSection] = true;

		$.get('/products/reviews', params, 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() {
				$('.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, .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 {

			var params = { ajax: true, submit_email_signup: true, email_signup: $('#email_signup').val() }
			var httpsOrNot = (("https:" == document.location.protocol) ? "i-want-https" : "i-want-no-https");
			params[httpsOrNot] = true;

			$.post('/newsletter', params, function (responseJson) {
				initPopup('#popupemail_signup');
				if (responseJson.errors) {
					$('#popupemail_signup_content').addClass('errorbox');

					errors = '';

					for (x in responseJson.errors) {
						errors = responseJson.errors[x];
					}

					$('#popupemail_signup_content').html(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();
	});

    if ($('.ad-gallery').length)
    {
        $('.ad-gallery').adGallery(
        {
            loader_image: 'loader.gif',
            width: 600, // Width of the image, set to false and it will read the CSS width
            height: 400, // Height of the image, set to false and it will read the CSS height
            thumb_opacity: 0.7, // Opacity that the thumbs fades to/from, (1 removes fade effect)
            start_at_index: 0, // Which image should be displayed at first? 0 is the first image
            animate_first_image: false, // Should first image just be displayed, or animated in?
            animation_speed: 400, // Which ever effect is used to switch images, how long should it take?
            display_next_and_prev: true, // Can you navigate by clicking on the left/right on the image?
            display_back_and_forward: false, // Are you allowed to scroll the thumb list?
            scroll_jump: 0, // If 0, it jumps the width of the container
            slideshow:
            {
                enable: false
            }
        });
    }

    $('.contentGalleryLink').click(function()
    {
        var catID = $(this).attr('rel');
        $('.galleryCategoryContainer').slideUp('normal', function()
        {
            $('#galleryCategory_'+catID).slideDown();
        });
        return false;
    });


    if ($('#productPricePromoTime').length)
    {
        $('#productPricePromoTime').epiclock({mode: EC_COUNTDOWN, target: $('#productPricePromoEndDate').html(), onTimer: function()
        {
            window.location = window.location;
        }}).clocks(EC_RUN);
    }
});

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

    $(selector).each(function()
    {
	    $(this).find('select.required').each(function()
        {
		    if ($(this).attr('id') && $(this).attr('id').match(/attribute_option_[0-9]+/))
            {
    			idInfo = $(this).attr('id').split("_");
			    idName = idInfo[2];
		    }

            if ($('.attribute_error_'+idName).length)
            {
                $('.attribute_error_'+idName).hide();
            }
            $(this).removeClass('error_select');
            $(this).closest('div').find('.error').hide();

    	    if (!$(this).val())
            {
			    attributesOk = false;
			    if (idName)
                {
				    $('.attribute_error_' + idName).show();
    			}
                else
                {
				    $(this).closest('div').find('.error').show();
    			}
    		}
            else
            {
			    if (idName)
                {
				    $('.attribute_error_' + idName).hide();
			    }
                else
                {
				    $(this).closest('.attribute').find('.error').hide();
    			}
    		}
    	});
    });

	return attributesOk;
}

/**
 * This function take a string block of text/HTML and an array of data and merges the two.
 * @param string text
 * @param array data The data to be merged
 */
function mergeHtmlBlock(text, data) {
	// Replace the script tag place holders
	text = text.replace(/\/\*TEMPLATE SCRIPT/ig, '');
	text = text.replace(/TEMPLATE SCRIPT\*\//ig, '');
	// jQuery thinks it's being clever when it URL encodes HTML for you, but not always,
	// so here we must undo this damage if it is found.
	text = text.replace(/\%7b/ig, '{');
	text = text.replace(/\%7d/ig, '}');
	for (var_name in data) {
		text = text.replace(new RegExp('{'+var_name+'}', 'g'), data[var_name]);
	}
	return text;
}

$('.template_search_input').livequery('keyup', function(e) {
		$.getJSON('/products/search/s:'+$(this).val(), { ajax: true, items_per_page: '5', order_by: 'product_price DESC', search: $(this).val() }, function (responseJson) {
			if(responseJson[0] > 0) {
			$('.template_quicksearch_container').show().html(responseJson[1]);
			} else {
			$('.template_quicksearch_container').hide();
			}
			});
		});

