document.write('<style type="text/css">');
document.write('.show { display:inline }');
document.write('.hide, .filters div.collapse ul { display:none }');
document.write('.filters div.collapse h3, .filters div.expand h3 { cursor:pointer }');
document.write('</style>');

/* 
--------------------------------------------------------------------------
GENERAL SITE FUNCTIONS
--------------------------------------------------------------------------*/
var cnet = {
	
	domready: function() {
		cnet.colorbox();
		cnet.displayCaptcha();
		cnet.followBar();
		cnet.searchBar();
		cnet.searchFilterToggle();
		cnet.tabbedBoxes();
		cnet.toolTips();
		cnet.userProductRating();
		cnet.pageLoadLightBox();
	},
	
	//handle links which open in a lightbox
	colorbox: function() {
		
		//bind colorbox to these selectors
		//even if these selectors don't currently exist in the DOM, they are still bound to this function when they are added later
		$('a.log-in, a.register, a.log-out, a.forgot-password, a.facebook-merge, a.fb-log-in').live('click', function(e) {
			e.preventDefault();
			$.colorbox({
				href: $(this).attr('href'),
				initialHeight: 30,
				initialWidth: 30,
				overlayClose: false,
				onLoad:function() {
					$('#cboxLoadedContent').empty();
					$('#cboxLoadingOverlay').show();
				},
				onComplete: function() {
					var $form = $('#colorbox form');
					switch($form.attr('id')) {
						case 'log-in':
							member.validateLogin($form);
							break;
						case 'registration':
							var captchaKey = $('#captcha_key').val();
							member.showRecaptcha(captchaKey, 'recaptcha_widget');
							member.validateRegistration($form);
						  break;
						case 'forgot-password':
							member.validateForgotPassword($form);
							break;
					}
				}
			}); 
		});
		
		//reviews image gallery links
		$('a[rel="lightbox[gallery]"]').colorbox();
		
		//reviews video sharing options
		$("a.share-video").colorbox({ href:$(this).attr('href'), inline:true, width:"480" });
		
	},
	
	displayCaptcha: function() {
		$('#recaptcha_widget').ready(function () {
 			var captchaKey = $('#captcha_key').val();
			member.showRecaptcha(captchaKey, 'recaptcha_widget');
		});
	},

	displayLightbox: function(url, data) {
		if (url.length > 0) {
			$.colorbox({
				href: url,
				data: data,
				initialHeight: 30,
				initialWidth: 30,
				overlayClose: false
			});
		}
	},
	
	//used to display a lightbox on page load
	pageLoadLightBox: function() {

		var lightbox = $.query.get('light-box');
		
		if (lightbox) {
			$.colorbox({
				href: '/member/lightbox/' + lightbox + '/'
			});
		}
		
	},

	closeLightbox: function() {
		$.fn.colorbox.close();
	},

	createAlert: function(parameters) {
		if (typeof(parameters)!='undefined')
		{
			alert_params = parameters;
		}

		if (member.checkLoggedIn() !== true)
		{
			// Call function option to login
			$('a.log-in').trigger('click');
		}
		else if (member.checkLoggedIn() === true)
		{
			cnet.displayLightbox('/member/lightbox/create-alert/', alert_params);
		}
	},
	
	//controls position of follow bar during page scroll
	followBar: function() {
		var $follow = $('#follow');
		
		if ($follow.length && !($.browser.msie == true && parseInt($.browser.version) < 7) ) {
			
			var showBar = $.cookie('follow-bar-state') || true;
			
			if (showBar && $.cookie('follow-bar-closes') && $.cookie('follow-bar-closes') >= 5) {
				showBar = false;
			}
					
			if (showBar == true) {
				
				$follow.css('display', 'block');
				
				$(window).scroll(function () {
					var documentHeight = $(document).height();
					var scrollPosition = $(window).height() + $(window).scrollTop();
					var scrollBottom = documentHeight - scrollPosition;
					var footerHeight = $('#rbFooter').outerHeight() + parseInt($('#rbWrap').css('padding-bottom'));
					if (scrollBottom < footerHeight) {
						$follow.css('position', 'absolute');
						$follow.css('bottom', footerHeight);
					} else {
						$follow.css('position', 'fixed');
						$follow.css('bottom', 0);
					}
				});
				
				//user can close the follow bar and this remains persistent for the session
				//if user closes the follow bar 5 times in total, closure should be permanent 
				$follow.find('.close').click(function() {
					$follow.remove();
					$.cookie('follow-bar-state', false, { path:'/', domain:'cnet.co.uk' }); //expires end of session
					var numCloses = $.cookie('follow-bar-closes');
					numCloses = (numCloses == null) ? 1 : (parseInt(numCloses) + 1);
					$.cookie('follow-bar-closes', numCloses, { path:'/', domain:'cnet.co.uk', expires:365 }); //expires in 365 days
					return false;
				});
				
			}
			
		}
		
	},
	
	searchBar: function() {
		
		$('#universalSearchBox').click(function() {
			clearSearch();
		});
		
		$('#universalSearch').submit(function() {
			clearSearch();
			Omniture.trackSearch(this, $('#universalSearchBox').val());
		});
		
		function clearSearch() {
			if ($('#universalSearchBox')[0].defaultValue == $('#universalSearchBox').val()) {
				$('#universalSearchBox').val('');
			}
		}
		
	},
	
	//toggle dimension groups in search navigation
	searchFilterToggle: function() {
		
		var $searchFilters = $('#search-filters');
		
		$('#search-filters .group').first().removeClass('collapse').addClass('expand');
		
		if ($searchFilters.length) {
			$('#search-filters div.expand h3, #search-filters div.collapse h3').click(function() {
				$group = $(this).parent('div');
				if ($group.hasClass('expand')) {
					$group.removeClass('expand').addClass('collapse');
				} else {
					$group.removeClass('collapse').addClass('expand');
				}
			});
		}
		
	},
	
	//ajax load more dimension filters in search navigation
	searchFilterUpdate: function(dimensionId, url) {
	
		$target = $('#dim-' + dimensionId);
		
		var $loader = $('<img/>', {
			'class': 'mb-5',
			'src': '/images/search/ajax-loader.gif',
			'alt': 'Loading filters'
		});
		
		var $error = $('<li/>', {
			'text': 'An error occurred and we were unable to update the filters. Please refresh and try again'
		});
		
		$.ajax({
			url: url,
			dataType: 'html',
			beforeSend: function() {
				$target.find('ul').hide().before($loader);
			},
			error: function() {
				$loader.remove();
				$target.find('ul').show().html($error);
			},
			success: function(data) {
				$target.html(data);
			}
		});
		
	},
	
	tabbedBoxes: function() {
		
		var $topStories = $('#top-stories');
		if ($topStories.length) {
			$topStories.tabs();
		}
		
		var $relatedReviews = $('#related-reviews');
		if ($relatedReviews.length) {
			$relatedReviews.tabs();
		}
		
	},
	
	//add tooltips to ratings sliders
	toolTips: function() {
		$('.rating-slider').toolTips();
	},

	//handle user interaction with ratings sliders
	userProductRating: function() {
		
		var $myRating = $('.my-rating');
		
		if ($myRating.length) {
			var $currentRating = $myRating.find('.current-rating');
			var ratingSet;
			$myRating.find('.rating-slider li a').bind({
				'click': function(e) {
					e.preventDefault();
					rating = $(this).text();
					ratingSet = true;
					$currentRating.css('width', rating);
					if ($('#comment-submit .my-rating').length) {
						$('#comment-submit .current-rating').css('width', rating*10 + '%');
						//sets value of hidden rating field in user review form
						$('#rating').val(rating);
						if ($(this).parent().parent().parent().attr('id') == 'rating-top') {
							$('html, body').animate({'scrollTop': $('#comment-submit').offset().top});
						}
					}
				},
				'mouseenter': function() {
					$currentRating.css('width', 0);
				},
				'mouseleave': function() {
					if (ratingSet) {
						$currentRating.css('width', rating*10 + '%');
					}
				}
			});
		}
		
	}
	
};

$(document).ready(function() {
    cnet.domready();
});

/* 
--------------------------------------------------------------------------
Photo gallery plugin
--------------------------------------------------------------------------
*/
(function($) {
	
	$.fn.photoGallery = function(options) {
		
		var options = $.extend({}, $.fn.photoGallery.defaults, options);
		
		return this.each(function() {
			
			var $gallery = $(this),
			
			$caption = $gallery.find(options.caption),
			
			$counter = $gallery.find(options.counter),
			
			currentIndex = $counter.text() - 1,
			
			$imgHolder = $gallery.find(options.imgHolder).bind(
				'click', { next: true }, function(e) {
					handleClick(e);
				}
			).bind({
				'mouseover': function() {
					$(this).css('cursor', 'pointer');
				},
				'mouseout': function() {
					$(this).css('cursor', 'default');
				}
			}),
			
			$nextBtn = $gallery.find(options.nextBtn).bind(
				'click', { next: true }, function(e) {
					handleClick(e);
				}
			),
			
			$prevBtn = $gallery.find(options.prevBtn).bind(
				'click', { prev: true }, function(e) {
					handleClick(e);
				}
			),
			
			handleClick = function(e) {
				if (e) { e.preventDefault(); }
				imageToShow = e.data.prev ? getPrevPhoto() : getNextPhoto();
				showImage(imageToShow);
			},
			
			getNextPhoto = function() {
				(currentIndex < options.imgSrc.length - 1) ? currentIndex++ : currentIndex = 0;
				return options.imgSrc[currentIndex];
			},
			
			getPrevPhoto = function() {
				(currentIndex == 0) ? currentIndex = options.imgSrc.length - 1 : currentIndex--;
				return options.imgSrc[currentIndex];
			},
			
			showImage = function(imageToShow) {
				$imgHolder.attr('src', imageToShow);
				$caption.html(options.imgCaptions[currentIndex]);
				$counter.text(currentIndex + 1);
			}
						
		});
		
	};
	
	$.fn.photoGallery.defaults = {
		caption: 'div.caption',
		counter: 'span.counter',
		imgHolder: 'div.figure img',
		imgSrc: [],
		imgCaptions: [],
		nextBtn: 'div.slideshow-nav .next',
		prevBtn: 'div.slideshow-nav .prev'
	};

})(jQuery);

/* 
--------------------------------------------------------------------------
Tabs plugin
--------------------------------------------------------------------------
*/
(function($) {
	
	$.fn.tabs = function(options) {
		
		var options = $.extend({}, $.fn.tabs.defaults, options);
		
		return this.each(function() {
						
			var $module = $(this),
				$tabs = $module.find(options.tabs),
				$panels = $module.find(options.panels);
						
			$tabs.each(function(i) {
								
				var $tab = $(this);
				
				$tab.click(function(e) {
					e.preventDefault();
					$tab.addClass(options.selectedTabClass).siblings().removeClass(options.selectedTabClass);
					$panels.hide().eq(i).show();
				});
				
			});
			
		});
		
	};
	
	$.fn.tabs.defaults = {
		panels: 'div.panel',
		selectedTabClass: 'ui-tabs-selected',
		tabs: 'ul.ui-tabs-nav li'
	};

})(jQuery);

/* 
--------------------------------------------------------------------------
Tool tips plugin
--------------------------------------------------------------------------
*/
(function($) {
	
	$.fn.toolTips = function(options) {
		
		var options = $.extend({}, $.fn.toolTips.defaults, options);
		
		//create tool tip element and attach to DOM
		if (!$('.tool-tip').length) {
			var $tip = $('<div/>', { 'class': 'tool-tip' }).appendTo($('body')),
			$tipTitle = $('<div/>', { 'class': 'tip-title' }).appendTo($tip),
			$tipText = $('<div/>', { 'class': 'tip-text' }).appendTo($tip);
		}
				
		return this.each(function() {
						
			//go through each element with the tool tip class
			$('.' + options.tooltipClass).each(function() {
		
				var $this = $(this),
					title = $this.attr('title'),
					tipContent = title.split('::'),
					
					//delay showing of tooltip to prevent accidental mouseovers
					setTimer = function() {
						$this.showTipTimer = setInterval(function() {
							showTip();
						}, options.showDelay);
					},
				
					stopTimer = function() {
						clearInterval($this.showTipTimer);
					},
					
					//offset tool tip depending on mouse cursor position
					setTip = function(y, x) {
						var yTip = (y + 10) + 'px'; 
						var xTip = (x + 20) + 'px'; 
						$tip.css({
							'top': yTip,
							'left': xTip
						}); 
					},
					
					showTip = function() {
						$tip.show();
						stopTimer();
					};
				
				$this
				
					.mouseover(function(e) {
						//remove title from element to prevent browsers showing default tooltip
						$this.attr('title', '');
						if (tipContent[1]) {
							$tipTitle.text(tipContent[0]).show();
							$tipText.text(tipContent[1]);
						} else {
							$tipTitle.hide();
							$tipText.text(tipContent[0]);
						}
						setTip(e.pageY, e.pageX);
						setTimer();
					})
					
					.mousemove(function(e) {
						setTip(e.pageY, e.pageX);
					})
					
					.mouseout(function() {
						//add title back to element
						$this.attr('title', title);
						$tip.hide();
						stopTimer();
					});
				
			});
			
		});
		
	};
	
	$.fn.toolTips.defaults = {
		tooltipClass: 'tooltip',
		showDelay: 250
	};
	
})(jQuery);

