
/* !--- Details --- */
/* -----------------------------------------------------------------------------------------------------------------

 Site Javascript
 Author: Lee Powell

 ------------------------------------------------------------------------------------------------------------------- */



// Define Namespace
SITE = {};

(function($)
{ 

// First make sure we can debug using console
if( !window.console )
{
	window.console = {};
	
	methods = ['trace', 'log', 'info', 'debug', 'warn', 'error'];
	
	for( var key in methods )
	{
		window.console[methods[key]] = function(msg){};
	};
};

// CSS Hook
$('body').addClass('js');

SITE.data = {
	debug: false
};


/* !--- Document Ready --- */
/* ----------------------------------------------------------------------------------------------------------------- */
	
$(function(){
	SITE.init($);
});


/* !--- Initialise --- */
/* ----------------------------------------------------------------------------------------------------------------- */

SITE.init = function()
{
	SITE.bindEvents();
	
	if( SITE.browserData.flash.enabled )
	{
		$('body').addClass('flash');
	}
	
	// fake logo home link
	var $homelink = $('<a>')
	.attr('id', 'home-link')
	.attr('href', '/');
	$('#header .inner-wrap-2 .inner').append($homelink);
	
	
	// dynamic init - based on body id
	var bodyId = $('body').attr('id');
	
	if( bodyId && SITE.sections[bodyId+'Init'] )
	{
		SITE.sections[bodyId+'Init']();
	}
	
	// init modules
	if( $('#nav-content-sub').length > 0 )
	{
		SITE.functions.navContentSubInit();
	}
	
	if( $('#article-header').length > 0 )
	{
		SITE.functions.articleHeaderInit();
	}
	
	if( $('#photo-header-swap').length > 0 )
	{
		SITE.functions.photoHeaderInit();
	}
	
	if( $('#comments-list').length > 0 )
	{
		SITE.functions.commentsListInit();
	}

	if ( $('#discrete-dieter').length > 0)
	{
		SITE.functions.dieterInit();
	}
}


/* -----------------------------------------------------------------------------------------------------------------

 Section Specific

 ------------------------------------------------------------------------------------------------------------------- */
 

SITE.sections = {


/* !--- Home --- */
/* ----------------------------------------------------------------------------------------------------------------- */
	
homeInit: function()
{
	// set up homepage promos
	if( typeof _promos == 'undefined' ) return;

	var $promos = $('#promos');
	var $promosFrame = $('#promos-frame');
	
	// remove non-javascript image
	$('img', $promos).remove();
	
	$promosFrame.attr('href', _promos[0].uri);
	
	// create our carousel container
	var $carousel = $('<ul id="carousel"></ul>');
	var $carouselNav = $('<ul id="nav-carousel" class="nav"></ul>');
	
	// array for our carousel navigation items
	var btnGoArray = [];
	
	// build up the list of promo items
	$.each(_promos, function(i, v)
	{													
		$carousel.append('<li class="promo-'+i+'"><img src="'+v['src']+'" alt="'+v['alt']+'" width="327" height="471" /></li>');
		$carouselNav.append('<li class="promo-'+i+( i == 0 ? ' current' : '' )+'">'+(i+1)+'</li>');
		btnGoArray.push('#nav-carousel .promo-'+i);
	});
	
	$carouselNav.append('<li class="promo-prev">Previous</li><li class="promo-next">Next</li>');
	
	// build structure and insert into dom
	$promos.prepend('<div id="carousel-wrap"></div>');
	
	$('#carousel-wrap').append($carousel).after($carouselNav);
	
	var $current = $('li:eq(0)', $carouselNav).addClass('current');
	
	var $carouselNav = $('#nav-carousel');
			
	// set up carousellite
	$('#carousel-wrap').jCarouselLite({
		circular: true,
		visible: 1,
		scroll: 1,
		start: 0,
		auto: 8500,
		speed: 0,
		btnNext: '#nav-carousel .promo-next',
		btnPrev: '#nav-carousel .promo-prev',
		btnGo: btnGoArray,
		beforeStart: function(a) {
			var bg = $(a).find('img').attr('src');
			
			$('#carousel-wrap').css({
				backgroundImage: "url("+bg+")"
			});
			
			$(a).parent().fadeTo(500, 0);
		},
		afterEnd: function(a) {
			$current.removeClass('current');
						
			var $this = $(a);
			
			$this.parent().fadeTo(500, 1);
			
			// get class to determine the uri we need to use in the _promos array
			var theClass = $this.attr('class');
			
			// set the anchor href
			var promoId = theClass.split('-')[1];
			
			$promosFrame.attr('href', _promos[promoId].uri);
			
			// set the current nav item
			$current = $('li.'+theClass, $carouselNav);
			$current.addClass('current');
		}
	});
},


/* !--- Products --- */
/* ----------------------------------------------------------------------------------------------------------------- */

productsInit: function()
{
	// Products Landing
	
	if( $('body').hasClass('landing') )
	{
		if( typeof _ranges == 'undefined' ) return;
		 
		var $sections = $('.section');
	
		var i = 0;
		
		for( var k in _ranges ){
			(function()
			{
				var t = k;
				(function(){
					setTimeout(function()
					{
						setupCarousel(t);
					}, i);
				})();
				i = i+2000;
			})();		
		}
		
		function setupCarousel(target)
		{
			var $this = $('#'+target);
			
			var $sectionImg = $('.section-img', $this);
			
			var targetHref = $sectionImg.attr('href');
			
			$('.section-img', $this).replaceWith('<div id="'+target+'-carousel-wrap"></div>');
			
			var $wrap = $('#'+target+'-carousel-wrap');
			
			var $ul = $('<ul id="'+target+'-carousel" class="carousel"></ul>');
			
			for( var v in _ranges[target] )
			{
				$ul.append('<li><a href="'+targetHref+'" class="section-img"><img src="'+_ranges[target][v]+'" alt="" /></a></li>');
			}
			
			$wrap.append($ul);
			
			$wrap.jCarouselLite({
				circular: true,
				visible: 1,
				scroll: 1,
				start: 0,
				auto: 10000,
				speed: 0,
				beforeStart: function(a) {
					var bg = $(a).find('img').attr('src');
										
					$('#'+target+'-carousel-wrap').css({
						backgroundImage: "url("+bg+")"
					});
					
					$(a).parent().fadeTo(500, 0);
				},
				afterEnd: function(a) {								
					var $this = $(a);
					
					$this.parent().fadeTo(500, 1);				
				}
			});
		}
	}
},


/* !--- Shop --- */
/* ----------------------------------------------------------------------------------------------------------------- */
	
shopInit: function()
{
	$('#security-code').click(
		function(e)
		{
			window.open($(this).attr('href'), 'popup', 'width=480, height=320');
			e.preventDefault();
			return false;
		}
	);
	
	if( $('body').hasClass('landing') && (typeof itemCost !== 'undefined') )
	{		
		var quantities = $('.quantity');
		var shopTotal = $('#shop-total-cost');
		
		quantities.change(
			function()
			{
				var total = 0;
				
				quantities.each(
					function(e)
					{
						var $this = $(this);
						var quantity = $this.val();
						var target = $this.attr('name').split('-')[1];
						var cost = itemCost[target].unitcost;
						
						total += (quantity * cost);
					}
				);
				
				shopTotal.text(total.toFixed(2));
			}
		);
		
		// Trigger a change, for browsers that store select states between refreshes e.g. Firefox
		$(quantities[0]).change();
	}	
},


/* !--- Recipes --- */
/* ----------------------------------------------------------------------------------------------------------------- */
	
recipesInit: function()
{
	var $body = $('body');
	
	// Recipe Landing
		
	if( $body.hasClass('landing') )
	{				
		// recipe matrix
		var $matrix = $('#recipe-matrix');
		var $matrixNav = $('#nav-horizontal');
		var $matrixNavAnchors = $('a', $matrixNav);
		var $sections = $('.section', $matrix);
		var $categories = $('.category', $matrix);
		
		// hide all sections except the first
		$sections.not(':eq(0)').hide();
		
		// track the current section being displayed
		var $currentSection = $sections.eq(0);
		
		// track the current matrix nav item
		var $currentMatrixNav = $matrixNavAnchors.eq(0).closest('li').addClass('current');
							
		// remove category titles as we don't need them - housekeeping...
		$('h3.js-hide', $matrix).remove();
		
		// set up handler for maxtrix navigation
		$matrixNavAnchors.each(
			function()
			{
				var $this = $(this);
				var target = $this.attr('href').split('#')[1];
				var theParent = $this.closest('li');
				
				$this.click(
					function(e)
					{
						$currentSection.hide();
						$currentSection = $('#'+target).show();
						
						$currentMatrixNav.removeClass('current');
						theParent.addClass('current');
						$currentMatrixNav = theParent;
						
						e.preventDefault();
						return false;
					}
				);
			}
		);
		
		// set up each sections sub-nav and assign handlers to the list items to show/hide categories
		$sections.each(
			function()
			{
				var $this = $(this);
				
				var $cats = $('.category', $this);
				var $currentCat = $cats.eq(0);
				
				if( $cats.length < 2 ) return false;
				
				var $nav = $('<ul>').addClass('section-nav').addClass('nav');
				
				// create section nav from category titles - then remove the titles...
				$cats.each(
					function(i, val)
					{
						var $cat = $(this);
						var $title = $('.title', $cat);
						
						var $li = $('<li>');
						
						if( i == ($cats.length-1) )
						{
							$li.addClass('last');
						}
						
						var $a = $('<a>')
							.attr('href', '#')
							.text( $title.text() )
							.click(function(e)
							{
								var $this = $(this);
								
								$currentCat.hide();
								$cat.show();
								$currentCat = $cat;
								
								$currentSubNav.removeClass('current');
								$this.addClass('current');
								$currentSubNav = $this;
								
								e.preventDefault();
								return false;
							});
						
						$nav.append($li.append($a));
						
						$title.remove();
					}
				)
				.not($currentCat).hide();
				
				$this.prepend($nav);
				
				var $currentSubNav = $('.section-nav a', $this).eq(0).addClass('current');
			}
		);
		
		// split category lists into 2 sets, this is for the design approach only, 
		// and potential issues with floating the li's
		$categories.each(
			function()
			{
				var $this = $(this);
				
				var $recipes = $('.recipes', $this);
				var $items = $('li', $recipes);
				
				var l = $items.length;
				
				if( l > 1 )
				{
					var length = Math.ceil(l / 2);
					
					var parts = new Array();
					parts[0] = $items.slice(0, length);
					parts[1] = $items.slice(length);						
					
					for(var i in parts)
					{
						var $ul = $('<ul>')
						.addClass('recipes')
						.addClass('s3')
						.addClass('column');
						
						$.each( parts[i], function(x, v)
						{
							$ul.append(v);
						});
						
						$this.append($ul);
					}						
					
					$recipes.remove();
				}
			}
		);
	}
	
	// Recipe Detail
	
	if( $body.hasClass('detail') )
	{
		$print = SITE.functions.getPrintButton();
		
		$print.attr('id', 'recipe-print');
		
		$('#extra-links .wrap-2').append($print);
	}
},


/* !--- Contact --- */
/* ----------------------------------------------------------------------------------------------------------------- */

contactInit: function()
{
	$('dd').each(function(){
		var $this = $(this);
		
		var $div = $this.find('div').hide();
		
		var $handle = $('<a>')
		.text('show')
		.attr('href', '#')
		.addClass('toggle')
		.addClass('imr')
		.click(handleFAQ);
		
		$this.append($handle);
	});
	
	$('dt').click(handleFAQ);
	
	function handleFAQ(e)
	{
		if( this.tagName.toLowerCase() == 'dt' )
		{
			var $target = $(this).next('dd');
		}
		else if( this.tagName.toLowerCase() == 'a' )
		{
			var $target = $(this).parent('dd');
		}
		
		var $handle = $('.toggle', $target);
		var $div = $('div', $target);
		
		$div.slideToggle(function(){
			$handle.text( ( $handle.text() == 'show' ) ? 'hide' : 'show' ).toggleClass('open');
		});
		e.preventDefault();
		return false;
	}
},


/* !--- Ryvita News --- */
/* ----------------------------------------------------------------------------------------------------------------- */
	
ryvitaNewsInit: function()
{
	var $body = $('body');
	
	/* Your Recipe Form - Liven Up Your Lunch & Stand Alone */
	
	if( $('#yourrecipe-form').length > 0 )
	{			
		SITE.functions.addAnotherInit( $('#yourrecipe-ingredients'), $('#yourrecipe-ingredients li'), $('#yourrecipe-form'), 3 );
	}
	
	/* Member Get Member */
	
	if( $body.hasClass('mgm') )
	{			
		SITE.functions.addAnotherInit( $('#mgm-friends'), $('#mgm-friends .friend'), $('#mgm-form'), 4 );
	}
	
	/* Crunch Cafe Event */ 
	
	if( $body.hasClass('event') )
	{
		// map
		SITE.functions.googleMapEventInit();
		
		// print button
		var $printBtn = SITE.functions.getPrintButton();
		$('#event-share-print .column-2').append($printBtn);
		
		// gallery
		$('.event-gallery .gallery-items').each(
			function()
			{
				var $galleryItems = $(this);
				
				$galleryItems.wrap('<div class="gallery-wrap"></div>');
				
				$galleryWrap = $galleryItems.parent();
				
				$galleryPrev = $('<a>').text('Previous').addClass('gallery-prev').addClass('gallery-nav').attr('href', '#').attr('title', 'View previous');
				$galleryNext = $('<a>').text('Next').addClass('gallery-next').addClass('gallery-nav').attr('href', '#').attr('title', 'View next');
				
				$galleryWrap.append($galleryPrev).append($galleryNext);
														
				$galleryWrap.jCarouselLite(
					{
						visible: 1,
						circular: true,
						start: 0,
						auto: 8500,
						speed: 0,
						btnNext: $('.gallery-next', $galleryWrap),
						btnPrev: $('.gallery-prev', $galleryWrap),
						beforeStart: function(li){
							var $this = $(li);
							var $img = $('img:eq(0)', $this);
							var $content = $('.content', $this);
							$galleryWrap.css('background', 'url("'+$img.attr('src')+'") no-repeat');
							$this.parent().fadeTo('500', 0);
						},
						afterEnd: function(li){
							var $this = $(li);
							$this.parent().fadeTo('500', 1);
						}
					}
				);
			}
		);			
	}
},

/* !--- About --- */
/* ----------------------------------------------------------------------------------------------------------------- */
	
yourrecipeInit: function()
{
	SITE.functions.addAnotherInit( $('#yourrecipe-ingredients'), $('#yourrecipe-ingredients li'), $('#yourrecipe-form'), 3 );
}

}


/* !--- Site Functions --- */
/* ----------------------------------------------------------------------------------------------------------------- */

SITE.functions = {
	googleMapEventInit: function()
	{
		if(typeof mapSettings !== 'undefined' && mapSettings.mapType){
			var coords = new google.maps.LatLng(mapSettings.latitude, mapSettings.longitude);
			var mapType;
			switch(mapSettings.mapType){
				case 'map':
					mapType = google.maps.MapTypeId.ROADMAP;
					break;
				case 'terrain':
					mapType = google.maps.MapTypeId.TERRAIN;
					break;
				case 'satellite':
					//fallthrough
				default:
					mapType = google.maps.MapTypeId.SATELLITE;
					break;
			}
			var opts = {
					zoom: parseInt(mapSettings.zoom),
					center: coords,
					mapTypeId: mapType
			};
		
			var map = new google.maps.Map(document.getElementById('event-map-'+mapSettings.target), opts);
			
			//add pointer
			var marker = new google.maps.Marker({
				position: coords,
				map: map	
			});
		
			//add overlay
			var infoWin = new google.maps.InfoWindow({
				content: '<div id="overlayContainer">' + mapSettings.content + '</div>',
				maxWidth: 300,
				maxHeight: 300
			});
			
			
		
			//add overlay to marker
			google.maps.event.addListener(marker, 'click', function(){infoWin.open(map, marker);});
		}
	},
	
	navContentSubInit: function()
	{
		var $navArticles = $('#nav-content-sub');
		var $sections = $('#nav-content-sub > li');
		
		$sections.each(
			function()
			{
				var $this = $(this);
				
				var $sub = $this.find('.second-level');
				
				if( $sub.length > 0 )
				{
					if(!$sub.hasClass('current')){
						$sub.hide();
						$this.addClass('closed');
					}
					
					var $section = $('span.section', $this);
				
					$section.click(
						function()
						{
							$sub.slideToggle();
							$this.toggleClass('closed');
						}
					);
				}					
			}
		);	
	},
	
	articleHeaderInit: function()
	{
		/* print functionality */
		var $printBtn = SITE.functions.getPrintButton();
		$printBtn.attr('id', 'article-print');
		$('#social-links .comments').before($printBtn).before(' ');
		
		if( $.browser.msie && $.browser.version <= 7 )
		{
			$('#article-print').before(' ');
		}
	},
	
	addAnotherInit: function($target, $items, $container, displayDefault)
	{
		if( typeof displayDefault == 'undefined' ) displayDefault = 2;
				
		$items.each(
			function(i, val)
			{
				if( i < displayDefault ) return;
				
				var $this = $(this);
					
				if( $('input', $this).val() == "" )
				{
					$this.hide();
				}
			}
		);
		
		resizeForIE();
		
		// Add another ingredient handle
		var $addHandle = $('<div id="item-add">Add another</div>');
		
		$addHandle.bind('click', addItem);
		
		$target.find('ol:eq(0)').after($addHandle);

		function addItem(e)
		{	
			var $hidden = $items.filter(':hidden');
			
			if( $hidden.length == 0 ) return;
			if( $hidden.length == 1 ) $addHandle.hide();
			
			$hidden.eq(0).fadeIn('fast');

			resizeForIE();
			
			e.preventDefault();
			return false;
		}
		
		// fixes odd bug in IE6 with submit button not retaining position when new ingredients are added
		function resizeForIE()
		{
			if( $.browser.msie && $.browser.version <= 6 )
			{
				$container.css('height', $container.height());
			}
		}
	},
	
	photoHeaderInit: function()
	{
		// PHOTO HEADER
		
		if( _photoHeaderData.length < 2 ) return;
		
		// preload the large images
		var imgs = [];
		for( var i in _photoHeaderData )
		{
			imgs.push(_photoHeaderData[i].imgLargeUrl);
		}
		SITE.utils.preloadImages(imgs);
	
		// setup variables needed
		var $ph = $('#photo-header');
		var $phContent = $('.content-wrap', $ph);
		var $phImg = $('.photo', $ph);
		var $phSwap = $('#photo-header-swap');
		var $phItems = $('li', $phSwap);
		
		// set up wrap for fade effect
		$phImg.wrap('<div id="photo-header-image-wrap"></div>');
		$phWrap = $('#photo-header-image-wrap');
		$phWrap.css('background', 'url('+_photoHeaderData[0].imgLargeUrl+')');
		
		// clone first list item and update attributes - _photoHeaderData[0] and the default photo header item are assumed to be idential
		var $firstItem = $($phItems[0]).clone().addClass('first-child').prependTo($phSwap);
			
		$firstItem.addClass('current')
		.find('.title span').text(_photoHeaderData[0].title).end()
		.find('img').attr('src', _photoHeaderData[0].imgSmallUrl).attr('alt', _photoHeaderData[0].title).end()
		.find('a').attr('href', _photoHeaderData[0].url);
		
		// get our list items again, as the new item has been added
		$phItems = $('li', $phSwap);
		
		// track 'current' list item 
		var $current = $firstItem;
		
		// assign swap item anchor event handler			
		$('a', $phItems).click(
			function(e)
			{
				var $this = $(this);
				var $parent = $this.parent();
				var i = $phItems.index($parent);
				
				$current.removeClass('current');
				$parent.addClass('current');
				$current = $parent;
				
				var item = _photoHeaderData[i];
				$phContent.html(item.html);
				
				$phImg
				.css('opacity', 0)
				.attr('src', item.imgLargeUrl)
				.attr('alt', item.title)
				.clearQueue()
				.animate({ opacity: 1 }, 300, function()
				{
					$phWrap.css('background', 'url('+item.imgLargeUrl+')');
				});
				
				resetPhotoHeaderRotate();
								
				e.preventDefault();
				return false;
			}
		);
		
		// Auto rotation of photo header
		var photoHeaderInterval, photoHeaderTrack;
		
		function startPhotoHeaderRotate()
		{
			photoHeaderTrack = $phItems.index($current);
			
			photoHeaderInterval = setInterval(function(){
				var target = photoHeaderTrack+1;
				
				target = (target < $phItems.length) ? target : 0;
							
				$($phItems[target]).find('a').trigger('click');

				photoHeaderTrack = target;				
			}, 5000);
		}
		
		function stopPhotoHeaderRotate()
		{
			clearInterval(photoHeaderInterval);
		}
		
		function resetPhotoHeaderRotate()
		{
			stopPhotoHeaderRotate();
			startPhotoHeaderRotate();
		}
		
		startPhotoHeaderRotate();
	},

	dieterInit: function () {
	
		var data = {

					'recipe-1': {
									imageThumb: 	'media/dContent/dieter/images/Ryvita-Mozzarella-thumb.jpg',
									imageMain: 		'media/dContent/dieter/images/Ryvita-Mozzarella.jpg',
									calories: 		'85',
									tastyText: 		'Place under the grill for a minute – a little bit of indulgence with no extra calories. Or simply add a drizzle of pesto',
									healthyText: 	'Choose thinner slices of reduced fat mozzarella and more generous slices of tomato. Mmmm juicy!',
									recipe: 		{
														title: 			'Reduced fat mozzarella, tomato and basil on Dark Rye Ryvita',
														subtitle: 		'Classic Italian flavours meet crunchy RYVITA® Only 85 calories per slice',
														ingredients: 	['25g reduced fat mozzarella', '40g fresh tomato', 'a few leaves of fresh basil', '1 slice RYVITA® Dark Rye Crispbread' ],
														method: 		'Slice the mozzarella and tomato and arrange your RYVITA®, alternating the two. Tear up a few basil leaves and scatter them on top.',
														packshot: 		'media/dContent/dieter/images/bg-recipe-dark-rye.png'
									}
								},

					'recipe-2': {
									imageThumb: 	'media/dContent/dieter/images/Ryvita-Salmon-thumb.jpg',
									imageMain: 		'media/dContent/dieter/images/Ryvita-Salmon.jpg',
									calories: 		'92',
									tastyText: 		'Add a drizzle of sweet chilli sauce for extra zing',
									healthyText: 	'Swap some of the smoked salmon for slices of cucumber and a squeeze of lemon.',
									recipe: 		{
														title: 			'Smoked salmon, low fat cream cheese and rocket on Dark Rye Ryvita',
														subtitle: 		'A salmon sensation with the extra kick of peppery rocket. Delicious at just 92 calories per slice',
														ingredients: 	['23.5g smoked salmon', '15g low fat cream cheese', 'a few leaves of rocket', '1 slice RYVITA® Dark Rye Crispbread' ],
														method: 		'Smooth the cream cheese over your RYVITA®;. Drape over the smoked salmon and finish with a few leaves of rocket.',
														packshot: 		'media/dContent/dieter/images/bg-recipe-dark-rye.png'
									}
								},

					'recipe-3': {
									imageThumb: 	'media/dContent/dieter/images/Ryvita-Tuna-thumb.jpg',
									imageMain: 		'media/dContent/dieter/images/Ryvita-Tuna.jpg',
									calories: 		'60',
									tastyText: 		'Sprinkle on a few capers or some rocket leaves for that extra kick.',
									healthyText: 	'Swap some of the tuna for tomatoes and extra cucumber.',
									recipe: 		{
														title: 			'Tuna and low fat mayo with cucumber and spring onions on Ryvita Crackerbread',
														subtitle: 		'A great mix of textures and flavours make up this tasty tuna lunch for just 60 calories per slice',
														ingredients: 	['25g tuna', '5g low fat mayonnaise', '20g cucumber', 'a sprinkle of sliced spring onion', '1 slice RYVITA® Original Crackerbread' ],
														method: 		'Cut the cucumber into slices and layer it on the Ryvita Crackerbread. Mix the tuna with the low fat mayonnaise and spoon it on top of the cucumber. Garnish with spring onion.',
														packshot: 		'media/dContent/dieter/images/bg-recipe-crackerbread.png'
									}
								},

					'recipe-4': {
									imageThumb: 	'media/dContent/dieter/images/Ryvita-cheese-thumb.jpg',
									imageMain: 		'media/dContent/dieter/images/Ryvita-Cheese.jpg',
									calories: 		'102',
									tastyText: 		'Experiment with a different reduced fat cheese like Red Leicester.',
									healthyText: 	'Swap some of the reduced fat cheese with some freshly sliced tomatoes.',
									recipe: 		{
														title: 			'Reduced fat cheddar cheese and pickle on Ryvita Crackerbread',
														subtitle: 		'An old favourite gets a light and crispy update with RYVITA® Crackerbread. Only 102 calories per slice',
														ingredients: 	['20g reduced fat cheddar cheese', '20g pickle', 'a couple of slices of apple', '1 slice RYVITA® Original Crackerbread' ],
														method: 		'Slice the cheese and arrange it onto the Ryvita Crackerbread. Finish with pickle and the apple slices.',
														packshot: 		'media/dContent/dieter/images/bg-recipe-crackerbread.png'
									}
								}

			};	

		// bind selector clicks to update data
		$('#dd-recipe-selector ul a').click(function () {
		
			updateData($(this).attr('id'));

			return false;

		});


		$('#prev, #next').click(function () {

			// get prev/next item and update data to this

			var dd_selector = $('#dd-recipe-selector'),
				index = dd_selector.find('li.selected').index(),
				newId = '',
				limit = 0,
				operator = index - 1;

			
			if ($(this).attr('id') === 'next') {

				// update variables if clicking next, not previous
				limit = 3;
				operator = index + 1;

			}

			if (index !== limit) {

				// if we're not at the limit of the carousel						
				newId = dd_selector.find('li:eq(' + operator + ')').find('a').attr('id');

				updateData(newId);

			}

			return false;

		});


		function updateData (id) {
			
			// Get data from config variable and update page with content
			var _this = this,
				dData = data[id];

				if (!(dData == undefined)) {

					// highlight link
					var dd_selector = $('#dd-recipe-selector');
					dd_selector.find('li.selected').removeClass('selected');
					$('#' + id).parent().addClass('selected');
						
					// load new image
					$('#img-large').attr('src', dData.imageMain);

					// update calories
					$('#calories p span').text(dData.calories);

					// update recipe details
					var dd_recipe = $('#recipe');

					dd_recipe.find('h2').text(dData.recipe.title).attr('class', id);
					dd_recipe.find('h3').text(dData.recipe.subtitle);
					dd_recipe.find('#ingredients').find('ul').remove()
					dd_recipe.find('#ingredients').append(getIngredientsList(dData.recipe.ingredients));
					dd_recipe.find('#method p').text(dData.recipe.method);
					
					$('.template-f #packshot').attr('src', dData.recipe.packshot);

					// update tasty/healthy text
					$('#tasty p').text(dData.tastyText);
					$('#healthy p').text(dData.healthyText);

				}

		}

		function getIngredientsList(items) {
			
			var i_html = '<ul>';

			for (var i = 0; i < items.length; i++) {
				
				i_html += '<li>' + items[i] + '</li>';

			}

			i_html += '</ul>';

			return i_html;

		}

		function getParameterByName(name)
		{
			name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
			var regexS = "[\\?&]" + name + "=([^&#]*)";
			var regex = new RegExp(regexS);
			var results = regex.exec(window.location.href);
			if(results == null)
			return "";
			else
		    return decodeURIComponent(results[1].replace(/\+/g, " "));
		}

		// finally on load if querystring parameter has been passed
		// then load corresponding page
		var r = getParameterByName('r');

		if (r != '') {
			
			updateData(r);

		}
			
	},
	
	commentsListInit: function()
	{
		$('a.report').colorbox(
		{
			href: function(){
				return '/media/site/helpers/comment-reporting.php'+$(this).attr('href');
			},
			width: 680,
			opacity: 0,
			close: 'Close',
			onComplete: function()
			{ 
				SITE.functions.commentsReportFormInit($(this));
			}
		});
	},
	
	commentsReportFormInit: function(el)
	{
		var $this = el;
		
		$('#comment-report-form').submit(
			function(e)
			{	
				if( $.trim($('#comment-report').val()) !== "" )
				{
					var $cb = $('#cboxLoadedContent');
					var $cbc = $('#content-colorbox');
					
					$cbc.hide();
					$cb.addClass('loading');
					
					$.post(
						'/media/site/helpers/comment-reporting.php',
						{
							reportId: $('input[name="reportId"]').val(),
							type: $('input[name="type"]').val(),
							report: $('#comment-report').val()
						},
						function(data, txt, xhr)
						{
							$('#content-colorbox').html(data);
							$cb.removeClass('loading');
							$cbc.show();
						},
						'html'
					);
				}
				else
				{
					$('#comment-report').addClass('error');
				}
							
				e.preventDefault();
				return false;
			}
		);
	},
	
	getPrintButton: function()
	{
		var $print = $('<a>')
		.text('Print')
		.attr('href', '#')
		.addClass('print')
		.click(
			function(e)
			{
				window.print();
				e.preventDefault;
				return false;
			}
		);
		
		return $print;
	}
}


/* !--- Bind Events --- */
/* ----------------------------------------------------------------------------------------------------------------- */

SITE.bindEvents = function()
{
	$('a[rel="external"]').live('click keypress', SITE.utils.newWindow);
}


/* !--- Browser Data --- */
/* ----------------------------------------------------------------------------------------------------------------- */

SITE.browserData = function()
{
	// Device - TO DO
	// --------------------------------------------------------------------------------------------------------------
	var uagent = navigator.userAgent.toLowerCase();
	
	// Touch devices
	// Check for touch devices to work around mouse events, user-agent sniffing, not ideal...
	
	// iPhone 1.1.1 - uagent detect & orientationchange
	// iPhone 2.0+ - touchstart
	
	var device = {
		mobile: false,
		desktop: false
	};
	
	var devices = ['iphone', 'ipod', 'ipad', 'android', 'blackberry', 'symbian', 'series60'];
	
	for( i in devices )
	{
		if( uagent.match(devices[i]) )
		{
			touchDevice = devices[i];
			break;
		}
	}

	// Flash
	// --------------------------------------------------------------------------------------------------------------
	var flash = {
		enabled: false,
		minor: 0,
		major: 0,
		release: 0
	};
	
	if( typeof swfobject == 'undefined' )
	{
		console.log('Failed to detect Flash player due to swfobject library missing');
	}
	
	// swfobject library and getFlashPlayerVersion available
	else if( swfobject.getFlashPlayerVersion )
	{
		var v = swfobject.getFlashPlayerVersion();
		
		if( v.major > 0 )
		{
			flash.enabled = true;
			flash.minor = v.minor;
			flash.major = v.major;
			flash.release = v.release;
		}
	}

	// Internet Explorer
	// --------------------------------------------------------------------------------------------------------------
	var ie = ( $.browser.msie ) ? $.browser.version : false;
	
	return {
		device: device,
		ie: ie,
		flash: flash
	}
	
}();


/* !--- Utilities --- */
/* ----------------------------------------------------------------------------------------------------------------- */

SITE.utils = function()
{
	function printProps(obj, objName)
	{
		var output = '';
	
		for(var prop in obj)
		{
			output += objName + "." + prop + " = " + obj[prop] + "\n" ;
		}
		
		return output;
	}
	
	function newWindow(e)
	{
		if( e.type == 'click' || e.type == "keypress" && e.keyCode == 13 )
		{
			var url = $(this).attr('href');
			
			var newWindow = window.open( url, '_blank' );
			
			newWindow.focus();
			
			e.preventDefault();			
		}
	}
	
	function preloadImages(imgs)
	{
		$.each(imgs, function(i, image)
		{
			var img = $('<img>').attr('src', image);		
		});
	}
		
	return {
		printProps: printProps,
		newWindow: newWindow,
		preloadImages: preloadImages
	};
	
}();

})(jQuery);




// begin new JS

$(document).ready(function(){
		
		setupYourRecipeForm();				
});


// (copied from old site)
function setupYourRecipeForm()
{
	var displayDefault = 2;
		
	$('#share-recipe-form').each(
		function()
		{
			var $this = $(this);
			
			var $ingredients = $('#share-recipe-ingredients', $this);
			
			$('li:gt('+displayDefault+')', $ingredients).each(
				function(i, val)
				{
					var $this = $(this);
					
					if( $('input', $this).val() == "" )
					{
						$this.hide();
					}
				}
			);
			
			// Add another ingredient handle
			var $addHandle = $('<div id="ingredient-add">Add another</div>');
			
			// slight modifictation
			$addHandle.css('cursor', 'pointer');
			
			$addHandle.bind('click', addIngredient);
			
			$ingredients.find('ol').after($addHandle);
	
			function addIngredient(e)
			{	
				var $hidden = $('li:hidden', $ingredients);
				
				if( $hidden.length == 0 ) return;
				if( $hidden.length == 1 ) $addHandle.hide();
				
				$hidden.eq(0).fadeIn('fast');
				
				// fixes odd bug in IE6 with submit button not retaining position when new ingredients are added
				if( $.browser.msie && $.browser.version <= 6 ) $this.css('height', $this.height());
				
				e.preventDefault();
				return false;
			}
		}
	);
}







