// Add contains NC expression for case insensitive use of contains:
$.extend($.expr[":"], {
	"containsNC": function(elem, i, match, array) {
        return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
    }
});
var IE6 = /MSIE 6/i.test(navigator.userAgent);
$(document).ready(function() {
	// Global Variables
	window.cufonSelectors = 'h2:not(.nocufon), h3, .page_desc, .welcome_name, .ps_price, .prod_price, .order_total, .total_column';
	window.colorboxSettings = {
		opacity			: 0.75,
		innerWidth		: '75%',
		innerHeight		: '75%',
		initialHeight	: 40,
		initialWidth	: 40,
		onComplete		: function() {
			loadOperations();
			// Check if we need to perform any translations on our colorbox content
			var currentLanguage = $.cookie('language');
			if(currentLanguage) {
				translateContent(currentLanguage);	
			}
		}
	};
	
	// Function to run whenever content is loaded into the DOM
	function loadOperations() {
		if(!window.IE6) {
			// Do our text replacement
			Cufon.set('fontFamily', 'Myriad Pro').replace(window.cufonSelectors);
		}
		// Add first and last classes to our lists
		$('ul > li:first-child').addClass('first');
		$('ul > li:last-child').addClass('last');	
		// Add odd styles to our basket and saved items
		$('ul>li:odd, table tr:odd').addClass('odd');
		
		// Handle our dropdown menus
		$('ul.dropdown_menu').hide();
		$('.dropdown_wrap').hover(function() {
			$(this).children('ul.dropdown_menu').show();	
		}, function() {
			$(this).children('ul.dropdown_menu').hide();
		});		

		// Hide our advanced search fields
		$('#advanced_search_fields').slideUp(1); // NB This is needed for IE6 otherwise our category select is visible after it is prepopulated
		
		// Fix any heights where needed
		$('.fix_heights_container').each(function() {
			// Set a maximum height variable which we can update
			window.maxHeight = 0;
			var toFix = $(this).find('.fix_heights');
			// Now loop through each of our children whose heights should be identical
			toFix.each(function() {
				// Set the height to auto first incase we have already run this function once
				$(this).css('height', 'auto');
				var thisHeight = $(this).height();
				if(thisHeight > window.maxHeight) {
					window.maxHeight = thisHeight;
				}
			});
			// Finally set the height of all those to the largest height
			toFix.each(function() {
				$(this).css('height',window.maxHeight + 'px');
			});
		});
		
		// Handle any content toggling
		$('.toggle_content').each(function() {
			var content = $(this);
			// Check we havent assigned click events for this content
			if(content.data('toggleAssigned') !=1) {
				// Add some data to the node so we dont assign multiple events
				content.data({toggleAssigned : 1});	
				var controller = content.siblings('.toggle_control');
				if(content.hasClass('toggle_content_up')) {
					content.hide();
					controller.addClass('toggle_control_up');
				}
				controller.click(function() {
					content.slideToggle('fast', function() {
						controller.toggleClass('toggle_control_up');	
					});
				});
				controller.hover(function() {
					controller.addClass('hover');	
				},
				function() {
					controller.removeClass('hover');
				});
			}
		});
		
		// Loop through each box to do our fancy focus/blur events on
		$('#fast_search, #search_address_popup, #createList, .list_comment_field').each(function() {
			var thisBox = $(this);
			var inactive = thisBox.hasClass('not_inactive') ? false : true;
			if(inactive) {
				var thisVal = thisBox.val();
			} else {
				//console.log('data-initial-value');
				var thisVal = thisBox.attr('data-initial-value');
			}
			thisBox.data({'initValue' : thisVal});
			if(inactive) {
				thisBox.addClass('form_input_inactive');
			}
			thisBox.focus(function() {
					if($(this).val() == $(this).data('initValue')) {
						$(this).removeClass('form_input_inactive');
						$(this).val('');	
					}
				}
			).blur(function() {
					if($(this).val() == '') {
						$(this).addClass('form_input_inactive');
						$(this).val($(this).data('initValue'));	
					}
				}
			).parents('form:first').submit(function() {
				// Grab the initial value of this field stored in its data
				var initValue = thisBox.data('initValue');
				var curValue = thisBox.val();
				// If the current value is the same as its initial value then no term was enetered so empty the field
				if(curValue == initValue) {
					thisBox.val('');	
				}
				// Submit our form
				return true;
			});
		});
	}
	
	// Function to handle adding parameters to a given query string
	function appendQueryString(url, pairs) {
		// Make our pairs into a url string
		var parts = [];
		$.each(pairs, function(key, val) {
			parts[parts.length] = key + '=' + val;
		});
		// Now join all our parts together
		var queryString = parts.join('&');
		// Check whether we have an existing query string
		if(url.indexOf('?') > -1) {
			return url += '&' + queryString;	
		} else {
			return url += '?' + queryString;	
		}		
	}
	
	function getProductCategories(formWrapper) {
		// Cache our select boxes
		var categorySelect = formWrapper.find('select[name=xCategory]');
		var brandSelect = formWrapper.find('select[name=xBrand]');
		var prepopulateCategory = formWrapper.find('input[name=xCategory]').val();
		// Set our loading text
		categorySelect.html('<option class="option_heading" value="--">--Select a Category--</option><option value="">Loading categories...</option>');
		// Get our product categories in JSON format
		$.getJSON('/page.php?xPage=product_categories_lookup.html', {xBrand : brandSelect.val()}, function(data) {
			// Create a string to inject into our category select box
			var categoryHTML = '<option class="option_heading" value="--">--Select a Category--</option>';
			// Loop through each returned option
			$.each(data, function(i, option) {
				var optionClass = option.groupHeading == 1 ? ' class="option_heading"' : '';
				var optionSelector = option.optionValue == prepopulateCategory ? ' selected="selected"' : '';
				categoryHTML += '<option value="' + option.optionValue + '"' + optionClass + optionSelector + '>' + option.optionText + '</option>';
			});
			// Populate our category select with our HTML
			categorySelect.html(categoryHTML);
		});
	}

	
	function translateContent(language) {
		//console.log(language);
		// Remove all our cufon styling first
		if(!window.IE6) {
			$(window.cufonSelectors).each(function() {
				var txt = $(this).text();
				$(this).children('cufon').remove();
				$(this).text(txt);
			});
		}

		$('#content, #colorbox, .translate').translate('en', language, {
			not				: '.nt',
			fromOriginal	: true,
			complete		: function() {
				loadOperations();
				// Set a cookie so we can translate items on page load if necessary
				var cookieVal = language == 'en' ? null : language; 
				$.cookie('language', cookieVal);
			}
		});
	}

	// All information below this comment will be performed once on page load
	loadOperations();
	
	$('select[name=xBrand]').change(function() {
		var formWrapper = $(this).parents('form:first');
		var visibleField = formWrapper.find('select[name=xCategory]');
		var hiddenField = formWrapper.find('input[name=xCategory]');
		// Store the current category value so we can prepopulate the category again if it exists
		hiddenField.val(visibleField.val());
		getProductCategories(formWrapper);
	});
	$('select[name=xCategory]').each(function() {
		var formWrapper = $(this).parents('form:first');
		getProductCategories(formWrapper);
	});
	
	$('#search_advanced a').live('click', function() {	
		$('#advanced_search_fields').slideDown('fast');
		$(this).parent().html('Advanced Search');
		$('#search_basic').html('<a href="#">Basic Search</a>');
		$('#search_form_wrap').css('border', '1px solid #999999');
		return false;
	});
	$('#search_basic a').live('click', function() {
		$('#advanced_search_fields').slideUp('fast');
		$(this).parent().html('Basic Search');
		$('#search_advanced').html('<a href="#">Advanced Search</a>');
		$('#search_form_wrap').css('border', '1px solid #FFFFFF');
		return false;
	});
	$('#search_reset').click(function() {
		$('#fast_search').val('').trigger('blur');
		$('#fast_search_xBrand').val('--');
		$('#fast_search_xCategory').val('--');
		return false;
	});

	/*
	// Language Translation
	$('#stripe_languages a').click(function() {
		// Get the language to translate to using the href attribute
		var language = $(this).attr('href').substr($(this).attr('href').length - 2, 2);
		translateContent(language);
	});
	
	// Check if we need to perform any translations immediately
	var currentLanguage = $.cookie('language');
	if(currentLanguage) {
		translateContent(currentLanguage);	
	}
	*/
	
	$('.ps_wrap:odd').addClass('ps_wrap_odd');

	$('.show_terms').colorbox({
		opacity			: window.colorboxSettings.opacity,
		href			: function() {
			var thisHref = 'https://www.adventdata.co.uk/page.php?xPage=terms.html';
			return appendQueryString(thisHref, {'ajax' : '1'});
		},
		innerWidth		: '75%',
		innerHeight		: '75%',
		initialHeight	: window.colorboxSettings.initialHeight,
		initialWidth	: window.colorboxSettings.initialWidth,
		onComplete		: function() {
			window.colorboxSettings.onComplete();
		}
	});
	$('.view_order').colorbox({
		opacity			: window.colorboxSettings.opacity,
		href			: function() {
			var thisHref = $(this).attr('href');
			return appendQueryString(thisHref, {'ajax' : '1', 'requires_login' : '1'});
		},
		innerWidth		: '720px',
		innerHeight		: '650px',
		initialHeight	: window.colorboxSettings.initialHeight,
		initialWidth	: window.colorboxSettings.initialWidth,
		onComplete		: function() {
			window.colorboxSettings.onComplete();
		}
	});
	$('.address_popup').colorbox({
		opacity			: window.colorboxSettings.opacity,
		href			: function() {
			//var thisHref = $(this).attr('href');
			var thisHref = 'https://www.adventdata.co.uk/page.php?xPage=address_popup.html';
			return appendQueryString(thisHref, {'ajax' : '1', 'requires_login' : '1'});
		},
		innerWidth		: '500px',
		innerHeight		: '500px',
		initialHeight	: window.colorboxSettings.initialHeight,
		initialWidth	: window.colorboxSettings.initialWidth,
		onComplete		: function() {
			window.colorboxSettings.onComplete();
			// Setup our search address function
			$('#search_address_popup').keyup(function(e) {
				var colorbox = $('#cboxLoadedContent');
				var searchTerm = $(this).val();
				if(searchTerm != '') {
					// Hide all items to begin with
					$('li', colorbox).removeClass('visible').hide();
					// Not show those containing our search term
					$('li:containsNC(' + searchTerm + ')', colorbox).addClass('visible').show();
				} else {
					// No search term so show all items
					$('li', colorbox).addClass('visible').show();
				}
				
				// Now hide or show any parent uls depending on their content
				$('ul', colorbox).each(function() {
					// Check how many matching addresses for this list
					if($(this).children('li.visible').length) {
						// Show the list
						$(this).show();
						// Show the header
						$(this).prev('h3').show();
					} else {
						// Show the list
						$(this).hide();
						// Show the header
						$(this).prev('h3').hide();
					}
				});
				
			});
			$('.use_address').click(function() {
				var wrapper = $(this).parent('li');
				// Loop through each input field
				$('input', wrapper).each(function() {
					// Set the value of the equivalent form field to our selected value
					$('#chosen_address [name=' + $(this).attr('name') + ']').val($(this).val());
				});
				$.fn.colorbox.close();
				return false;
			});
		}
	});
	$('.itf_launcher').colorbox({
		opacity			: window.colorboxSettings.opacity,
		scrolling		: false,
		href			: function() {
			var thisHref = $(this).attr('href');
			return appendQueryString(thisHref, {'ajax' : '1'});
		},
		innerWidth		: '400px',
		innerHeight		: '430px',
		onComplete		: function() {
			window.colorboxSettings.onComplete();
			//$('#cboxLoadedContent, #cboxContent, #cboxWrapper, #colorbox').css({overflow : 'visible'});
			// Custom cufon replacement for our 'fast' text effect
			if(!window.IE6) {
				Cufon('.itf_wrap h2', {textShadow: '-3px 0px #CCCCCC, -6px 0px #DDDDDD, -9px 0px #DDDDDD'});
			}
		}
	});
	
	/*
	// Store the original height and width of each cart item before shrinking them
	$('.cart_table_full_img').each(function() {
		$(this).data({
				'initHeight'		:	$(this).height(),
				'initWidth'			:	$(this).width(),
				'initMarginLeft'	:	$(this).css('marginLeft').substr(0,2),
				'initMarginRight'	:	$(this).css('marginRight').substr(0,2)
			}
		).css({
				'height'		:	'0px',
				'width'			:	'0px',
				'marginLeft'	:	'0px',
				'marginRight'	:	'0px'
			}
		);
	});
	
	
	$('.cart_table_full').delegate('tr', 'mouseenter', function() {
		var thumbnail = $(this).find('img.cart_table_full_img');
		var newHeight = thumbnail.data('initHeight');
		var newWidth = thumbnail.data('initWidth');
		var newMarginLeft = thumbnail.data('initMarginLeft');
		var newMarginRight = thumbnail.data('initMarginRight');
		thumbnail.clearQueue().delay(200).show(0).animate({
			'height'		:	newHeight + 'px',
			'width'			:	newWidth + 'px',
			'marginLeft'	:	newMarginLeft + 'px',
			'marginRight'	:	newMarginRight + 'px'
		}, 'fast');
	}).delegate('tr', 'mouseleave', function() {
		var thumbnail = $(this).find('img.cart_table_full_img');
		thumbnail.clearQueue().delay(1000).animate({
				'height'		:	'0px',
				'width'			:	'0px',
				'marginLeft'	:	'0px',
				'marginRight'	:	'0px'
		}, 'medium', function() {
			$(this).hide();
		});
	});
	*/

	var productImage = $('#product_image');
	if(productImage.width() > 328) {
		productImage.css('width', '328px');
		//console.log('resized product image');
	}
	
	$('#fast_search_form').submit(function() {
		if($('#advanced_search_fields').is(':hidden')) {
			$('#fast_search_xBrand').val('--');
			$('#fast_search_xCategory').val('--');
		}
		return true;
	});
	/*
	function restyleBasket() {
		// Grab our lists to use as a context
		var lists = $('ul.small_products_list');
		// Remove any existing styles first incase we are resetting
		$('li', lists).removeClass('odd').removeClass('first').removeClass('last');
		$('li:odd', lists).addClass('odd');
		$('li:first', lists).addClass('first');
		$('li:last', lists).addClass('last');
	}
	function updateBasketTotals() {
		// Update our basket lines
		var lines = $('#basket_wrap .small_products_list li');
		var noLines = lines.length;
		$('#basket_wrap .basket_items').text(noLines + ' line(s)');
		// Calculate our basket total
		window.basketTotal = 0;
		$(lines).each(function() {
			var quantity = Number($(this).children('.small_product_quantity').text());
			var price = Number($(this).children('.small_product_price').text().substring(1));
			var productTotal = quantity * price;
			window.basketTotal += productTotal;
			console.log(quantity + ' x ' + price + ' = ' + productTotal);
		});
		console.log('BASKET TOTAL ' + window.basketTotal.toFixed(2));
		$('#basket_wrap .basket_total').html('&pound;' + window.basketTotal.toFixed(2));
	}
	function setQuantity(productID, quantity, callback) {
		$('#basket_' + productID).children('.small_product_quantity').text(quantity);
		if($.isFunction(callback)) {
			callback();	
		}
	}
	function getProductAttributes(e) {
		var container = e.parents('li:first');
		var productID = container.attr('id').substring(7);
		var quantityField = container.children('.small_product_quantity');
		var quantity = Number(quantityField.text());
		return {
			'productID'	:	productID,
			'quantity'	:	quantity
		};
	}
	$('.small_products_add').click(function() {
		var attributes = getProductAttributes($(this));
		setQuantity(attributes.productID, attributes.quantity + 1, function() {
			updateBasketTotals();
			// The quantity has been updated in the db so update our cart view
			//quantityField.text(newQuantity);
		});
		return false;
	});
	$('.small_products_remove').click(function() {
		var thisLink = $(this);
		var attributes = getProductAttributes(thisLink);
		var newQuantity = attributes.quantity - 1;
		setQuantity(attributes.productID, newQuantity, function() {
			if(newQuantity == 0) {
				var container = thisLink.parents('li:first');
				container.slideUp('fast', function() {
					container.remove();
					// Reset our colour styles
					restyleBasket();
					updateBasketTotals();
				});
			} else {
				updateBasketTotals();
			}
		});
		return false;
	});
	*/
	
});

