
var web_path='/';
var selectedDate = null;

RegExp.escape = function(text) {
	return text.replace(/[-[\]{}()*+?.,\\^$|#]/g, "\\$&");
}




function selectSkirmishVariant() {

	// text to match on
	var dateString = selectedDate.format('dS mmmm');
	//var optionText = (dateString);
							
	// set option by text value
	//$('#_variant_box_0 option[text=' + optionText + ']').attr('selected', 'selected');

	var dateString 		= selectedDate.format('dS mmmm');
	var timeString 		= $('.time-picker:visible').val();
	var sessionString 	= ' (' + $('#session-length').val() +')';

	// text to match on, create a regular expression because the ending price adjustment can change in the future. eg (+$23.00)
	var optionText = RegExp.escape(dateString + ' - ' + timeString + sessionString);

	// set option by text value, yes its shonk but they'll match up ok
	$('#_variant_box_1 option').each(function(){
		var currentText = $(this).text();
		var pattern = new RegExp(optionText);

		if(currentText.match(pattern)){
			$(this).attr('selected', 'selected');
		}
	});
	
	UpdatePriceByVariants(true);
}


function selectCorrectVariant() {
	
	// use the current selected date and current selected time to update 
	// the hidden varient select box. matching on the actual field value which
	// is a little shonk but as norm.. time does not permit a correct think of better ways
	var dateString = selectedDate.format('dS mmmm');
	
	var timeString = $('.time-picker:visible').val();
	
	// text to match on
	var optionText = (dateString + ' - ' + timeString);
	
	// set option by text value, yes its shonk but they'll match up ok
	$('#_variant_box_2 option[text=' + optionText + ']').attr('selected', 'selected');
	
	// ok now we need to handle duration times. Need time and weekend switch to work out
	var todayIsWeekend = (selectedDate.getDay() == 6 || selectedDate.getDay() == 0);
	
	// on a weekday there is only 2 durations.. Weekend have different durations depending on start times
	var durations = ['1 Hour', '1.5 Hours'];
	if (todayIsWeekend) {
		switch (timeString) {
			case '9:00am':durations = ['1.5 Hours'];break;
			case '1:30pm':durations = ['1 Hour'];break;
			case '11:00am': case '3:00pm':durations = ['Half Hour'];break;
		}
	}
	
	// clear and update the fake duration dropdown with correct values.
	$('#duration').children().remove();
	for (duration in durations) {
		$('#duration').children().end().append('<option>' + durations[duration] + '</option>') 
	}
	
	// update duration varient hidden selected (default one from store mod)
	selectDurationVariant();
	
	// update the number of available stock
	UpdatePriceByVariants(true);
}


function selectDurationVariant() {
	var selectedDuration = $('#duration').val();
	
	// matching by text is still ok here, just match on start because the varient puts (+33.00) or whateva for 
	// the price. This allows them to change price etc and we dont need to code to a varient.
	// @note this doesnt need to use it now , price isnt displayed
	$('#_variant_box_1 option').each(function() {
		if ($(this).text().match(new RegExp('^' + selectedDuration))) {
			$(this).attr('selected', 'selected');
		}
	});
	
	// family tickets are only available for 1 and 1.5 hour rides. 
	// disable family checkbox and reset ticket type if its not those durations
	var familyOk = ($.inArray(selectedDuration, ['1 Hour', '1.5 Hours']) == -1);
	$('#family-ticket').attr('disabled', familyOk);

	if (familyOk) {
		$('#_variant_box_3').val(0);
		$('#family-ticket').attr('checked', false);
	}
	
	updateTicketVariant();
	UpdatePriceByVariants(true);
}


function updateTicketVariant() {
	var selectedDuration = $('#duration').val();
	if ($('#family-ticket:checked').length == 1) {
		
		// first check that we've got enough stock.
		if ($('#_item_stock_box').text() < 4) {
			alert('Sorry there are not enough horses for a family ticket at that ride time.');
			$('#family-ticket').attr('checked', '');
			return false;
		}
		
		// family is checked so set the hidden dropdown value to be correct.
		var optionText = selectedDuration + ' - Family Ticket';
		$('#_variant_box_3 option[text=' + optionText + ']').attr('selected', 'selected');
		
		// disable the qty field and set to 4 (2 kids, 2 adults)
		$('#add_qty').attr('disabled', 'disabled').val(4);
		
	} else {
		
		$('#_variant_box_3').val(0);
		$('#add_qty').attr('disabled', '').val(1);
	}
	
	UpdatePriceByVariants(true);
}


function setupLaserSkirmish() {

	// update the button so its green
	$('#store-item-booking-form-btn input').attr('src', web_path + 'images/pictures/large/system-files/book-now.png')
	
	// she doesnt want booking for the current day so we'll go for tomorrow.
	selectedDate = new Date();
	selectedDate.setTime(selectedDate.getTime( ) + (1000*3600*24));
	
	
	var familyCheckbox = '<br><br><table class="family-ticket" style="border-bottom:none; margin-bottom:0;"><tr><td><input checked="checked" disabled="disabled" type="checkbox" name="camo-hire" id="camo-hire"></td><td><label for="camo-hire"><b>Camo Hire</b><br><small> (Camo hire free with 2 hour session)</label></td></tr></table>';
	
	// add in weekend times and weekdays times
	$('#_variant_box_0').parent().append('<div class="store-item-variant-name">Select Session</div>');
	$('#_variant_box_0').parent().append('<div class="store-item-variant-select"><select class="session-picker" id="session-length"><option>2 hours</option><option>15 minutes</option></select></div>');
	$('#_variant_box_0').parent().append('<div class="store-item-variant-name">Select Time</div>');
	$('#_variant_box_0').parent().append('<select class="time-picker" id="long-times"><option>10:00am</option><option>2:00pm</option></select>');
	$('#_variant_box_0').parent().append('<select class="time-picker" id="short-times"><option>10:00am</option><option>11:00am</option><option>12:00pm</option><option>2:00pm</option><option>3:00pm</option><option>4:00pm</option></select>');
	$('#_variant_box_0').parent().append(familyCheckbox);
	
	//Hide Date title because it is handled by the calendar
	$('div.store-item-variant-name').each(function(){
		if($(this).html() == 'Time'){
			$(this).hide();
		} else if ($(this).html() == 'Laser Skirmish - Camo Hire') {
			$(this).hide();
		}
		
	});
	
	// hide Date variant dropdown because it is handled by the calendar
	$('#_variant_box_0').hide();
	$('#_variant_box_1').hide();

	// hide Date variant dropdown because it is handled by the calendar
	$('#short-times').hide();
	
	// As 2 hour session is the default, we should set the default camo option to "Free Camo Hire" 
	$('#_variant_box_0')[0].selectedIndex = 2;
	
	// attach on change to the session and time pickers to ste selectedTime variable
	// If 15 minutes is selected, show the short session times, else show the long session times
	$('.session-picker').change(function() {
		var session = $('.session-picker').val();

		if(session == '15 minutes'){
			$('#long-times').hide();
			$('#short-times').show();
			$('#camo-hire').attr('disabled', '');
			$('#camo-hire').attr('checked', '');
			$('#_variant_box_0')[0].selectedIndex = 0; // if they change to 15 mins, then the camo hire variant should change to none
			//$('#short-times option[text=' + time + ']').attr('selected', 'selected');
		} else {
			$('#short-times').hide();
			$('#long-times').show();
			$('#camo-hire').attr('checked', 'checked');
			$('#camo-hire').attr('disabled', 'disabled');
			$('#_variant_box_0')[0].selectedIndex = 2; // if changed back to 2 hours, then the camo hire variant should change to free
			
			//$('#long-times option[text=' + time + ']').attr('selected', 'selected');
		}

		//alert('Please reselect a session starting time');
		selectSkirmishVariant();
	});
	
	// attach onchange to the camo hire checkbox to set the camo hire dropdown values.
	$('#camo-hire').change(function() { 
		if ($(this).is(':checked')) {
			// set camo varient to include suit. 
			$('#_variant_box_0')[0].selectedIndex = 1
		} else {
			$('#_variant_box_0')[0].selectedIndex = 0
		}
		
		UpdatePriceByVariants(false);
	});
	
	

	$('.time-picker').change(function() {
		selectSkirmishVariant();
	});

	// Initialise datepicker and set hidden variant select value
	$( "#datepicker" ).datepicker({ 
		minDate: "+1D", 
		maxDate: "+20D",
		dateFormat: 'dd-mm-yy',
		onSelect: function(dateText, inst) { 

			var bits 	= dateText.split('-');
			var day 	= bits[0];
			var month = bits[1]-1; // js date works 0 - 11.
			var year 	= bits[2];

			selectedDate = new Date(year, month, day);
			selectSkirmishVariant();
		},

		beforeShowDay: function(date){
			var day = date.getDay();

			var datenumber = date.getDate();
			var month = date.getMonth();

			if(day==1 || day==2){
				return [false, ''];
			} else if(datenumber==25 && month==11){
				return [false, '']; // Christmas Day
			} else if(datenumber==25 && month==3){
				return [false, ''];	// Anzac Day
			} else {
				return [true,''];
			}
		}
	});
	
	
	// update the varient dropdown (only because we've defaulted to the 2hr session and the vairnent holds the 15 min by default
	selectSkirmishVariant();
}


function submitAddToCart() {
		
		var item_id = $('#item_id').val();
		var qty = $('#add_qty').val();
		
		// get date and turn into date object
		dateText = $('#datepicker').val();
		var bits 	= dateText.split('-');
		var day 	= bits[0];
		var month	= bits[1]-1; // js date works 0 - 11.
		var year 	= bits[2];
		
		selectedDate = new Date(year, month, day);

		switch(item_id) {
			// Laser Skirmish
			case '4':
				var isWeekDay = (selectedDate.getDay() == 3 || selectedDate.getDay() == 4 || selectedDate.getDay() == 5);
				if(isWeekDay && qty<4){
					alert('Only bookings of 4 or more are accepted on Wednesday, Thursday and Friday. Please contact our office for more information.');
					return false;
				}
				
				if(qty>=10){
					alert('Please call our office - PH: 1300 666 559 - for bookings of 10 or more people');
					return false;
				} else {
					return true;
				}
				
			break;
		}
		
		return true;
		
}

/**
 * custom method to update the price field on adventure park as its all wahck the 
 * store js simply wont accomodate it
 */
function updateAdventurePrice() {
	
	// base values , zero out the price
	var price			= 0;
	var variantPrices	= variant_list[1];
	var basePrice		= parseInt(orig_price);
	
	// get variant prices
	var prices = {
		children :	variantPrices[0],
		concession: variantPrices[1],
		adults:		variantPrices[2],
		family:		variantPrices[3]
	}

	// get the qtys
	var tickets = {
		adults:		parseInt($('#adults').val()),
		children:	parseInt($('#children').val()),
		concession: parseInt($('#concession').val()),
		family:		($('#family-ticket').is(':checked') ? 1 : 0)
	}
	
	// ok, lets total up the price
	for (ticket in tickets) {
		// we need a qty, no point otherwise
		if (tickets[ticket] > 0) {
			var priceAdjust = parseInt(prices[ticket]);
			price += (basePrice + priceAdjust) * tickets[ticket];
		}
	}

	$('.price').text(price + '.00');
}






/**
 * Global Onload Method
 * 
 * currently this sets up the tell a friend popup in a lightbox as well as sets up the bookmark site link.
 */
$(function() {
	
	
	// disable all the varient dropdowns on the shopping cart page. We dont want them to be able to change 
	// beacuse the tricky js limits certian things on the bookings page. These dropdowns contain all varients
	// but we only sometimes 
	$('.carttable SELECT').attr('disabled', 'disabled');
	
	$('form[name=addtocartform]').submit(submitAddToCart); 
	
	
	// New Logic Based on Item ID hidden field
	if($('#item_id').length > 0) {

		var item_id = $('#item_id').val();

		switch(item_id) {
			// Horse Riding
			case '1':

				// being its the only page with a datepicker im going to handle other shit for the item page here.
				if ($('#datepicker').length > 0) {

					selectedDate = new Date();
					var todayIsWeekend = (selectedDate.getDay() == 6 || selectedDate.getDay() == 0);
					
					$('#_variant_box_0').change(function(){
						UpdatePriceByVariants(false);
					});
					
					// add in weekend times and weekdays times
					var weekdaySelect  = '<select class="time-picker custom" id="weekday-times" name="weekday-times"><option>10:00am</option><option>1:30pm</option></select>';
					var weekendSelect  = '<select class="time-picker custom" id="weekend-times" name="weekend-times"><option>9:00am</option><option>11:00am</option><option>1:30pm</option><option>3:00pm</option></select>';
					var durationSelect = '<select class="duration-picker custom" id="duration" name="duration"></select>';
					var familyCheckbox = '<table class="family-ticket"><tr><td><input type="checkbox" name="family-ticket" id="family-ticket"></td><td><label for="family-ticket"><b>Family Ticket</b><br><small> (2 Adults + 2 Children 10 to 15 years)</label></td></tr></table>';
					
					// add fake duration dropdown
					$('#_variant_box_1').parent().append(durationSelect);
					
					// add fake start time dropdown.
					$('#_variant_box_2').parent().append(weekdaySelect + weekendSelect);
					
					// ad family checkbox
					$('#_variant_box_3').parent().append(familyCheckbox);
					
					
					// hide varient for duration & start date/time
					$('#_variant_box_1').hide();
					$('#_variant_box_2').hide();
					$('#_variant_box_3').hide();
					
					// as it will alwayse pick th ecurrent day set the correct time drop down to display
					if (todayIsWeekend) {
						$('#weekday-times').hide();
					} else {
						$('#weekend-times').hide();
					}
					
					// attach on change to the time pickers to the selectedTime variable
					$('.time-picker').change(function() {
						selectCorrectVariant();
					});
					
					// attach change to the duration picker
					$('.duration-picker').change(function() {
						selectDurationVariant();
					});
					
					// attach change to the family pass checkbox
					$('#family-ticket').change(function() {
						updateTicketVariant();
					})
					
					
					
					// attach onsubmit to form to check the quantity and then check if there are enough available for the selected time
					$('form[name=addtocartform]').submit(function() {
						if (parseInt($('input[name=add_qty]').val()) > parseInt($('#_item_stock_box').text())) {
							alert('Sorry but there are not enough available horses for the selected Time');
							$('input[name=add_qty]').focus().select();
							return false;
						}
					});
					
					//$('#store-item-booking-form-qty').parent().append('<div class="ticket_row"><div class="ticket_label">Adults:</div><div class="ticket_qty"><input name="qty_adults" value="1"></div></div>');
					//$('#store-item-booking-form-qty').parent().append('<div class="ticket_row"><div class="ticket_label">Children:</div><div class="ticket_qty"><input name="qty_children" value="0"></div></div>');
					//$('#store-item-booking-form-qty').hide();
					

					$( "#datepicker" ).datepicker({ 
						minDate: 0, 
						maxDate: "+20D",
						dateFormat: 'dd-mm-yy',
						onSelect: function(dateText, inst) { 
							
							var bits 	= dateText.split('-');
							var day 	= bits[0];
							var month = bits[1]-1; // js date works 0 - 11.
							var year 	= bits[2];
							
							selectedDate = new Date(year, month, day);
							var isWeekend = (selectedDate.getDay() == 6 || selectedDate.getDay() == 0);
							
							if (isWeekend) {
								// show weekend times
								$('#weekday-times').hide();
								$('#weekend-times').show();
							} else {
								// show weekday times
								$('#weekday-times').show();
								$('#weekend-times').hide();
							}
							
							// update the hidden select
							selectCorrectVariant();
						},
						
						beforeShowDay: function(date){
							
							var datenumber = date.getDate();
							var month = date.getMonth();
							
							// Do not display Christmas and Anzac Day on calendar 						
							if(datenumber==25 && month==11){
								return [false, '']; // Christmas Day
							} else if(datenumber==25 && month==3){
								return [false, ''];	// Anzac Day
							} else {
								return [true,''];
							}
						}
					});
				}
				
				// call this - needs to update the duration field as it starts off
				selectCorrectVariant();
				
			break;
			
			
			// Thunderegg Fossiking
			case '2':
				if ($('#datepicker').length > 0) {
				
					//Hide Date title because it is handled by the calendar
					$('div.store-item-variant-name').each(function(){
						if($(this).html() == 'Date' || $(this).html() == 'Ticket Type'){
							$(this).hide();
						}
					});
					
					
					
					// hide Date variant dropdown because it is handled by the calendar
					$('#_variant_box_0').hide();
					
					// Hide ticket variant as it is handled by the qty fields
					$('#_variant_box_1').hide();
					
					// Add custom qty fields for adults and children
					$('#store-item-booking-form-qty').parent().append('<div class="ticket_row"><div class="ticket_label">Adults:</div><div class="ticket_qty"><input name="qty_adults" value="1"></div></div>');
					$('#store-item-booking-form-qty').parent().append('<div class="ticket_row"><div class="ticket_label">Children:</div><div class="ticket_qty"><input name="qty_children" value="0"></div></div>');
					
					//Hide the standard qty field
					$('#store-item-booking-form-qty').hide();
					
					//Hide the Ticket Price Updater
					$('#store-item-booking-form-price').hide();
					
					$( "#datepicker" ).datepicker({ 
						minDate: 0, 
						maxDate: "+20D",
						dateFormat: 'dd-mm-yy',
						onSelect: function(dateText, inst) { 
							
							var bits 	= dateText.split('-');
							var day 	= bits[0];
							var month = bits[1]-1; // js date works 0 - 11.
							var year 	= bits[2];
							
							selectedDate = new Date(year, month, day);
							
							// text to match on
							var dateString = selectedDate.format('dS mmmm');
							var optionText = (dateString);
													
							// set option by text value
							$('#_variant_box_0 option[text=' + optionText + ']').attr('selected', 'selected');
						},
						
						beforeShowDay: function(date){
							
							var datenumber = date.getDate();
							var month = date.getMonth();
							
							// Do not display Christmas and Anzac Day on calendar 						
							if(datenumber==25 && month==11){
								return [false, '']; // Christmas Day
							} else if(datenumber==25 && month==3){
								return [false, ''];	// Anzac Day
							} else {
								return [true,''];
							}
						}
					});
				}
			break;
			
			//Adventure Parc
			case '3':
				if ($('#datepicker').length > 0) {
				
					//Hide Date title because it is handled by the calendar
					$('div.store-item-variant-name').each(function(){
						if($(this).html() == 'Date' || $(this).html() == 'Ticket Type'){
							$(this).hide();
						}
					});
					
					// hide Date variant dropdown because it is handled by the calendar
					$('#_variant_box_0').hide();
					
					// Hide ticket variant as it is handled by the qty fields
					$('#_variant_box_1').hide();
					
					//Hide the standard qty field
					$('#store-item-booking-form-qty').hide();
					
					//Hide the Ticket Price Updater
					$('#store-item-booking-form-price').hide();
					
					// Add custom qty fields for adults and children
					familyCheckbox = '<table class="family-ticket"><tr><td><input type="checkbox" name="qty[448]" value="1" id="family-ticket"></td><td><label for="family-ticket"><b>Family Ticket</b><br><small> (2 Adults + 2 to 3 Children)</label></td></tr></table>';
					$('#store-item-booking-form-qty').parent().append(familyCheckbox);
					
					$('#store-item-booking-form-qty').parent().append('<div class="ticket_row"><div class="ticket_label adults">Adults :</div><div class="ticket_qty"><input id="adults" class="qty" name="qty[451]" value="0"></div></div>');
					$('#store-item-booking-form-qty').parent().append('<div class="ticket_row"><div class="ticket_label children">Children:</div><div class="ticket_qty"><input id="children" class="qty" name="qty[449]" value="0"></div></div>');
					$('#store-item-booking-form-qty').parent().append('<div class="ticket_row"><div class="ticket_label">Concession:</div><div class="ticket_qty"><input id="concession" class="qty" name="qty[450]" value="0"></div></div>');
					
					// add onchange to family ticket
					$('#family-ticket').change(function() {
						updateAdventurePrice();
						if ($(this).is(':checked')) {
							$('.adults').text('Extra Adults:');
							$('.children').text('Extra Children:');
						} else {
							$('.adults').text('Adults:');
							$('.children').text('Children:');
						}
					});
					
					
					
					// custom price display junk below
					// @todo append spot to hold the price
					$('#store-item-booking-form-qty').parent().append('<div class="custom-price">Total Price: $<span class="price">0.00</span></div>');
					
					// now lets set up price updater (use qty class)l
					$('.qty').change(updateAdventurePrice);
					
					
					$( "#datepicker" ).datepicker({ 
						minDate: 0, 
						maxDate: "+20D",
						dateFormat: 'dd-mm-yy',
						onSelect: function(dateText, inst) { 
							
							var bits 	= dateText.split('-');
							var day 	= bits[0];
							var month = bits[1]-1; // js date works 0 - 11.
							var year 	= bits[2];
							
							selectedDate = new Date(year, month, day);
							
							// text to match on
							var dateString = selectedDate.format('dS mmmm');
							var optionText = (dateString);
													
							// set option by text value
							$('#_variant_box_0 option[text=' + optionText + ']').attr('selected', 'selected');
						},
						
						beforeShowDay: function(date){
							
							var datenumber = date.getDate();
							var month = date.getMonth();
							
							// Do not display Christmas and Anzac Day on calendar 						
							if(datenumber==25 && month==11){
								return [false, '']; // Christmas Day
							} else if(datenumber==25 && month==3){
								return [false, ''];	// Anzac Day
							} else {
								return [true,''];
							}
						}
					})
				}

			break;
			
			//Laser Skirmish
			case '4':
				if ($('#datepicker').length > 0) {
					setupLaserSkirmish();
				}
			break;
		}
	}
	
	
	
	
	
	
	// Full Sized Background Image
	$("#background_image").fullBg();
	
	// Slide menu
	$('#menu').slideMenu(); 
	
	$('.topnav').supersubs({ 
    	minWidth:    10,   // minimum width of sub-menus in em units 
    	maxWidth:    20,   // maximum width of sub-menus in em units 
    	extraWidth:  1  
	}).superfish({
		animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation 
        speed:       'fast',                          // faster animation speed 
        autoArrows:  false                           // disable generation of arrow mark-up 
	});

	if ($.fancybox && $('#gmap').length >= 1) {
		$('#gmap').fancybox({
                'autoScale'             : false,
                'scrolling'             : 'no',
                'centerOnScroll'        : true,
                'overlayOpacity'        : 0.5,
                'overlayColor'          : '#000',
                'showNavArrows'         : false,
                'width'                 : 640,
                'height'                : 480,
                'transitionIn'          : 'elastic',
                'transitionOut'         : 'elastic',
                'type'                  : 'iframe'
        });


	}
	
	
	// attach fancybox to the send to friend link in the footer if both exist
	if ($.fancybox) // && $('#tellAFriend').length >= 1) {
	{
		$('#tellAFriend,#emailThisItem').fancybox({
			'autoScale'			: false,
			'scrolling'			: 'no',
			'centerOnScroll'	: true,
			'overlayOpacity'	: 0.5,
			'overlayColor'		: '#000', 
			'showNavArrows'   : false,
			'width'           : 480,
			'height'          : 310,
			'transitionIn'		: 'elastic',
			'transitionOut'   : 'elastic',
			'type'				: 'iframe'
		});
	}

	$('a.store-variant-link').fancybox({
		'autoScale'			: false,
		'scrolling'			: 'vertical',
		'centerOnScroll'	: true,
		'overlayOpacity'	: 0.5,
		'overlayColor'		: '#000', 
		'showNavArrows'   : false,
		'width'           : 640,
		'height'          : 400,
		'transitionIn'		: 'elastic',
		'transitionOut'   : 'elastic',
		'type'				: 'iframe',
		'titleShow'       : false
	});

	$('a#password-recovery-link').fancybox({
		'autoScale'			: false,
		'scrolling'			: 'vertical',
		'centerOnScroll'	: true,
		'overlayOpacity'	: 0.5,
		'overlayColor'		: '#000', 
		'showNavArrows'   : false,
		'width'           : 500,
		'height'          : 250,
		'transitionIn'		: 'elastic',
		'transitionOut'   : 'elastic',
		'type'				: 'iframe',
		'titleShow'       : false
	});

	// attach jquery bookmark plugin to the bookmark site link.
	if ($('#bookmarkSite').length >= 1) {
		$('#bookmarkSite').jFav();
	}
	

	// Init home page slider; if not on home page then do nothing.
	if ($('div#home-slideshow').length >= 1) {
		$('div#home-slideshow').cycle({
			fx: 'scrollLeft',
			timeout: 5000,
			speed: 700,
			pager: '#home-slideshow-pager',
			pagerAnchorBuilder: function(num, img){
				return '<a href="#">&nbsp;</a>';
			}
		});
	}


	if ($('#subscribe_fld input').length>=1) {
		$('#subscribe_fld input').focus(function() { 
			if ($(this).val() == 'Email address') {$(this).val('');}}).blur(function() {if ($(this).val() == '') {$(this).val('Email address');}});
	}
	
	if ($('#search_fld input').length>=1) {
		$('#search_fld input').focus(function() { 
			if ($(this).val() == 'Search') {$(this).val('');}}).blur(function() {if ($(this).val() == '') {$(this).val('Search');}});
	}

	
	$('#store-item-thumbnails a').fancybox({
		'centerOnScroll'	: true,
		'overlayOpacity'	: 0.5,
		'overlayColor'		: '#000', 
		'transitionIn'		: 'elastic',
		'transitionOut'   : 'elastic'
	});

});

function SlideFeaturedItemsUp()
{
	$('#store-featured-items').animate(
	{
		'scrollTop': '+=230px'
	}, 250);
	setTimeout('SlideFeaturedItemsDown()', 5250);
}

function SlideFeaturedItemsDown()
{
	$('#store-featured-items').animate(
	{
		'scrollTop': '-=230px'
	}, 250);
	setTimeout('SlideFeaturedItemsUp()', 5250);
}

/*This function adds the page to a bookmark.*/

function addToFavourites()
{
	title = document.title;
	url = location.href;

	if (window.sidebar) // Mozilla Firefox Bookmark
	{
		window.sidebar.addPanel(title, url,"");
	}
	else if (window.external) // IE Favorite
	{
		window.external.AddFavorite( url, title); 
	}
	else if (window.opera && window.print) // Opera Hotlist
	{
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	}
}

/**
 * This is a jquery plugin that I use to preload a bunch of images, its easy to use, just call 
 * 
 * $.preLoadImages("image1.jpg", "image2.jpg")
 * 
 */
(function($) {
	var cache = [];
	// Arguments are image paths relative to the current page.
	$.preLoadImages = function() {
		var args_len = arguments.length;
		for (var i = args_len; i--;) {
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			cache.push(cacheImage);	
		}
	};
})(jQuery);




/* EMAIL FUNCTIONS NEED TO BE PUT INTO AN OVERLAY - REMOVE WHEN DONE */
/*function email_this_item(i) {
	var win, ht;
	ht=310;
	win=window.open(web_path+'pages/email_this_page.php?item='+escape(i)+'&use_lb', 'email_this_item','resizable,width=480,height='+ht+',left=200,top=120,status');
}

function email_this_page(i) {
	var win, ht;
	ht=310;
	win=window.open(web_path+'pages/email_this_page.php?page='+escape(i)+'&use_lb', 'email_this_item',
	                'resizable,width=480,height='+ht+',left=200,top=120,status');
}*/


function changePerPage(osel) {

	var val = osel[osel.selectedIndex].value;
	url = new Url(location.href);
	url.setVar('perpage', val);
	url.go();

}

function changeOrder(osel) {
   var val = osel[osel.selectedIndex].value;
   url = new Url(location.href);
   url.setVar('order', val);
   url.go();
}

function toggleDirection(dir) {
   var set = (dir == 'ASC') ? 'DESC' : 'ASC';
   url = new Url(location.href);
   url.setVar('dir', set);
   url.go();
} 

function showHide(element) 
{
	if (jQuery(element).css('display') == "none")
	{
		jQuery(element).slideDown(200);
	}
	else
	{
		jQuery(element).slideUp(200);
	}
}

function over(obj) {
	// first lets see if the src of this image is blank.gif and if its IE6 - Based on these conditions
	// we know that its a png fix so we need to alter the method of changing the image background as oposed
	// to the image source.
	var filename = obj.src.substring(obj.src.lastIndexOf('/')+1);

	// first lets check to see if its IE6 and if the image in a png file
	if(filename == 'blank.gif' && $.browser.msie && $.browser.version == '6.0') {
		var newFilter = (obj.style.filter.replace('.png', '-over.png'));
		obj.style.filter = newFilter;
	} else {
		obj.src=obj.src.replace('.gif', '-over.gif');
		obj.src=obj.src.replace('.jpg', '-over.jpg');
		obj.src=obj.src.replace('.png', '-over.png');
	}
}
 
function out(obj) {
	var filename = obj.src.substring(obj.src.lastIndexOf('/')+1);
	if(filename == 'blank.gif' && $.browser.msie && $.browser.version == '6.0') {
		obj.style.filter = obj.style.filter.replace('-over', '');
	} else {
		obj.src=obj.src.replace('-over', '');
	}
}


/**
* Switch item tabs on the item detail page.
*/

function SwitchItemTab(tab_num)
{
	var sp=200;

	if (tab_num<=0)
		return;

	// Update tabs

	// if using only A tags for tabs
	//$('#store-item-tabs .store-tab-a-over').addClass('store-tab-a');
	//$('#store-item-tabs .store-tab-a-over').removeClass('store-tab-a-over');
	//$('#store-item-tabs #store-info-tab'+tab_num).addClass('store-tab-a-over');

	// using DIV enclosing other DIVs and A tags
	$('#store-item-tabs div.store-hdr-tab-over').removeClass('store-hdr-tab-over');
	$('#store-item-tabs div#store-info-tab'+tab_num).addClass('store-hdr-tab-over');

	// Show/hide content

	$('#store-item-tabs-body .store-tab-body').each(function()
	{
		if (this.style.display=='block')
		{
			//$(this).slideUp(sp);
			$(this).hide();
		}
	});

	//setTimeout(function() { $('#store-item-tabs-body #store-info-tab-body'+tab_num).slideDown(sp); }, sp);
	$('#store-item-tabs-body #store-info-tab-body'+tab_num).show();
	$('#store-item-tabs-body #store-info-tab-body'+tab_num).css('display','block');
}

/**
* Questions & Reviews
*/

var review_tab_num=0, question_tab_num=0;

function SwitchItemReviewsTab()
{
	SwitchItemTab(review_tab_num);
}

function SwitchItemQuestionsTab()
{
	SwitchItemTab(question_tab_num);
}

/**
* Set up the images on the item detail page. Add fancy box, 
* carousel, etc.
*/

var item_detail_current_img='';

function SetupItemDetailImages()
{
	var str;

	str="a.store-image-thumbnails-link";
	if ($("a.store-image-thumbnails-link").length<=0)
		str=str+', #store-item-large-image a';

	$(str).fancybox(
	{
		"transitionIn"	   :  "fade",
		"transitionOut"   :  "fade",
		"overlayOpacity"	:  0.8,
		"overlayColor"		:  "#000",
		"zoomSpeedIn"		:  300,
		"zoomSpeedOut"    :  300,
		"speedIn"         :  300,
		"speedOut"        :  300,
		"changeSpeed"     :  300
	});

	$("#store-item-large-image a").click(function()
	{
		var n=0, use_n=-1;

		if ($("a.store-image-thumbnails-link").length<=0)
			return;

		$("a.store-image-thumbnails-link").each(function()
		{
			var tmp_href=''+this.href;

			tmp_href=tmp_href.substring(tmp_href.indexOf('/images/pictures/'))

			if (use_n>=0)
				;
			else if (item_detail_current_img=='' && n==0)
			{
				use_n=n;
			}
			else if (item_detail_current_img==tmp_href)
			{
				use_n=n;
			}
			n++;
		});

		if (use_n<0)
			use_n=0;
		else
			$("a.store-image-thumbnails-link").eq(use_n).click();
		
		return false;
	});

	$("#store-item-thumbnails a").click(function()
	{
		var the_img=$(this).attr("href"); //children("img")[0].src;

		if ($("#store-item-large-image img").attr("src")!=the_img)
		{
			$("#store-item-large-image img").animate(
			{
				opacity: 0.05
			}, 200, 
			function()
			{
				$("#store-item-large-image img").attr("src", the_img);
				//alert( $("#store-item-large-image img").css('height') );

				setTimeout(function()
				{
					$("#store-item-large-image img").animate(
					{
						opacity: 1.0
					}, 200);
				}, 50);
			});
		}

		$("#store-item-large-image a").attr("href", the_img);

		item_detail_current_img=''+the_img;
		item_detail_current_img=escape(item_detail_current_img.substring(item_detail_current_img.indexOf('/images/pictures/')));

		return false;
	});

	$('#store-images-carousel').jcarousel(
	{
		scroll: 4
	});
}


function CalcQuickPostage(in_amt, item_id)
{
	var pcode='', amt=0.00, ptype='';

	if ($('#calc_postage_type1').attr('checked'))
		ptype=$('#calc_postage_type1').attr('value');
	else if ($('#calc_postage_type2').attr('checked'))
		ptype=$('#calc_postage_type2').attr('value');
	else
		return;

	if (in_amt=='')
		in_amt=$('#_item_price_box').html();

	amt=parseFloat(in_amt);
	pcode=''+$('#calc_postage_postcode').attr('value');
	if (pcode=='')
		return;
	if (pcode.length>4)
		pcode=pcode.substring(0,4);

	$('#store-item-postage-result').slideDown(100);
	$('#store-item-postage-result').html('<img src="'+web_path+'images/pictures/large/system-files/progress-bar.gif">');

	$.get(web_path+'products/'+
	   '?_auto_calc_postage&amt='+escape(amt)+
		'&item_id='+escape(item_id)+
		'&pcode='+escape(pcode), 
		'&postage_type='+escape(ptype), 
	function(data)
	{
		if (data!='')
		{
			var str=''+data;
			if (str.indexOf('error:')>=0)
				;
			else
				data='Delivery to '+escape(pcode)+': <b>'+data+'</b>';
			$('#store-item-postage-result').html(data);
			$('#store-item-postage-result').slideDown(100);
		}
		else
		{
			$('#store-item-postage-result').html('');
			$('#store-item-postage-result').slideUp(100);
		}
	});
}


