(function($){

	// simplifies prototypal inheritance
	if (typeof Object.create !== 'function') {
		function F() {}
		Object.create = function(o) {
			F.prototype = o;
			return new F();
		};
	}

	// proxy method taken from jQuery 1.4
	if (typeof $.proxy !== 'function') {
		$.extend({
			proxy: function( fn, proxy, thisObject ) {
				if ( arguments.length === 2 ) {
					if ( typeof proxy === "string" ) {
						thisObject = fn;
						fn = thisObject[ proxy ];
						proxy = undefined;

					} else if ( proxy && !jQuery.isFunction( proxy ) ) {
						thisObject = proxy;
						proxy = undefined;
					}
				}

				if ( !proxy && fn ) {
					proxy = function() {
						return fn.apply( thisObject || this, arguments );
					};
				}

				// Set the guid of unique handler to the same of original handler, so it can be removed
				if ( fn ) {
					proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
				}

				// So proxy can be declared as an argument
				return proxy;
			}
		});
	}
	
	$.mainOffersSlider = {
		itemIndex: 0, /* must be decalred on each new object as not to intnterfere with other carousel on page (must have own count) */
		itemsPerPage: 3,
		itemsPerTransition: 3,
		numberedLinks: true,
		speed: 600,
		init: function($el) {
			if (!$el.length) {return false;}
			this.$container = $el;
			this.setUp();
		},
		setUp: function() {

			this.$mask = $('<div class="mask" />');
			this.$runner = this.$container.find('ul').wrap(this.$mask);
			this.$items = this.$runner.children();
			this.noOfItems = this.$items.length;
			//this.noOfPages = Math.ceil((this.noOfItems - this.itemsPerPage + 1) / this.itemsPerTransition); 
			this.noOfPages = Math.ceil((this.noOfItems - this.itemsPerPage) / this.itemsPerTransition) + 1;
			
			if (this.noOfItems <= this.itemsPerPage) {return false;}
			
			this.insertNumberedLinks();
			this.insertNextPrevBtns();
			this.buttonStatus();
			
			this.$noLinksContainer.find('a:not(.next, .prev)').click($.proxy(this, 'numberedLinksHandler'));
			this.$nextBtn.click($.proxy(this, 'nextHandler'));
			this.$prevBtn.click($.proxy(this, 'prevHandler'));
		
		},
		insertNumberedLinks: function() {
	
			// insert numbered links
			var links = [];
			this.$noLinksContainer = $('<ol class="numbers" />').appendTo(this.$container);
			for (var i = 0; i < this.noOfPages; i++) {
				links[i] = '<li><a href="#item--' + i + '">' + (i + 1) + '</a></li>'; // using double hyphen as IE sticks full URL in place so error can occur if href is split by single '-', prob should use a somthing better than double hyphen
			}
			this.$noLinksContainer.append(links.join(''));
		
		},
		insertNextPrevBtns: function() {
			
			// insert next and prev
			this.$nextBtn = $('<li><a href="#" class="next">Next</a></li>').appendTo(this.$noLinksContainer);
			this.$prevBtn = $('<li><a href="#" class="prev">Prev</a></li>').prependTo(this.$noLinksContainer);
			
		},
		numberedLinksHandler: function(e) {
			this.itemIndex = $(e.target).attr('href').split('--')[1] * this.itemsPerTransition;
			this.slide();
			return false;
		},
		nextHandler: function() {
			this.itemIndex = this.itemIndex + this.itemsPerTransition;
			this.slide();
			return false;
		},
		prevHandler: function() {
			this.itemIndex = this.itemIndex - this.itemsPerTransition;
			this.slide();
			return false;
		},
		buttonStatus: function() {
		
			if (this.numberedLinks) {
				// highlight numbered link
				this.$noLinksContainer.find('a:not(.next, .prev)').removeClass('active').eq(Math.ceil(this.itemIndex / this.itemsPerTransition)).addClass('active');
			}
			
			// highlight next and prev
			this.$nextBtn.add(this.$prevBtn).removeClass('dis');
			if (this.itemIndex === (this.noOfItems - this.itemsPerPage)) {
				this.$nextBtn.addClass('dis');
			}
			
			if (this.itemIndex === 0) {
				this.$prevBtn.addClass('dis');
			}
		},
		slide: function() {
		
			// check whether there are enough items to slide to
			if (this.itemIndex > (this.noOfItems - this.itemsPerPage)) {
				// go to last panel - items per transition
				this.itemIndex = this.noOfItems - this.itemsPerPage;
			}
			else if (this.itemIndex < 0) {
				// go to first
				this.itemIndex = 0;
			}
			
			var $nextItem = this.$items.eq(this.itemIndex),
			pos = $nextItem.position();
			
			this.$runner.stop().animate({left: -pos.left}, this.speed);
			
			this.buttonStatus();
		}
	}

	// create mini slider object from carouselSlider object
	$.miniOffersSlider = Object.create($.mainOffersSlider);
	$.extend($.miniOffersSlider, {	
		itemIndex: 0,
		itemsPerPage: 1,
		itemsPerTransition: 1,
		numberedLinks: false,
		speed: 300,
		setUp: function() {
			this.$runner = this.$container.find('ul');
			this.$items = this.$runner.children();
			this.$mask = this.$container.find('div.mask');
			this.noOfItems = this.$items.length;
			this.noOfPages = Math.ceil((this.noOfItems - this.itemsPerPage + 1) / this.itemsPerTransition);
			
			if (this.noOfItems <= this.itemsPerPage) {return false;}

			this.insertNextPrevBtns();
			this.buttonStatus();
		
			this.startInterval();
			this.$container.hover($.proxy(this, 'stopInterval'), $.proxy(this, 'startInterval'));
			
			this.$nextBtn.click($.proxy(this, 'nextHandler'));
			this.$prevBtn.click($.proxy(this, 'prevHandler'));
		},
		insertNextPrevBtns: function() {
			this.$nextBtn = $('<a href="#" id="next">Next</a>').appendTo(this.$mask);
			this.$prevBtn = $('<a href="#" id="prev">Prev</a>').appendTo(this.$mask);
		},
		intervalHandler: function() {
			this.itemIndex = this.itemIndex + this.itemsPerTransition;
			if (this.itemIndex > (this.noOfItems - this.itemsPerPage)) {
				this.itemIndex = 0;
			}
			this.slide();
		},
		startInterval: function() {
			this.interval = setInterval($.proxy(this, 'intervalHandler'), 6000);
		},
		stopInterval: function() {
			clearInterval(this.interval);
		}
	});
	
	$.fn.homeBgSwitcher = function() {
		var $bg = $(this);
		var $thumbs = $('#inn-thumbnails').show().find('ul > li > a'); // cache 
		var $nextThumb = $thumbs.filter(':first').addClass('sel'); // store first thumb
		
		// function to switch bg and strapline
		var switchBg = function($nextThumb) {
			var url = $nextThumb.attr('href');
			var sID = $nextThumb.attr('title');
			
			// switch opacity
			$thumbs.removeClass('sel'); $nextThumb.addClass('sel');
			// enable strapline
			$('#inn-strapline').find('ul > li').hide();
			$('#strapline-' + sID).show();
			
			// fadeOut bg-home
			$bg.stop().fadeTo(250, 0, function() {
				// change home-bg div with url
				$(this).css({
					backgroundImage: 'url(' + url + ')'
				}).fadeTo(250, 1);
			});
			
			
			/* IE has caching issue with load() event! */
			/*// load new image, fadeout, switch image then fadeIn
			$('<img />')
				.attr('src', url)
				.load(function() {
					// add + remove selected classes
					$thumbs.removeClass('sel'); $nextThumb.addClass('sel');
					// set strapline (h2) to title
					$('h2#strapline').text(title);
					
					// fadeOut bg-home
					$bg.stop().fadeTo(250, 0, function() {
						// change home-bg div with url
						$(this).css({
							backgroundImage: 'url(' + url + ')'
						}).fadeTo(250, 1);
					});
				});*/
		};
		
		$thumbs.click(function() {
			// get url of background image
			$nextThumb = $(this);
			
			// run switch function
			switchBg($nextThumb);
			
			return false;
		});


		var interval = function() {
			$nextThumb = $nextThumb.parent().next().children();
		
			// check if there is a nextthumb
			if (!$nextThumb.length) {
				$nextThumb = $thumbs.filter(':first');
			}
			
			// run switch function
			switchBg($nextThumb);
		};
		
		// set interval timer
		var switchTimer = setInterval(interval, 10000);
		
		// stop interval on thumb:hover
		$thumbs.parent().parent().hover(function() {
			clearInterval(switchTimer); // remove interval timer
		}, function() {
			switchTimer = setInterval(interval, 10000); // restart interval timer
		});
	}
	
	$.fn.faderWidget = function() {
		
		var $container = $(this); // switcher container
		var $panelsContainer = $('#panels', $container); // panels ul
		var $panels = $panelsContainer.children('li'); // panels
		var $readMore = $('.read-more', $panels); // read more link
		var $tabsContainer = $('#tabs', $container); // tabs ul
		var $tabs = $tabsContainer.find('a'); // tabs
		
		// insert masking DIV
		$($panelsContainer).wrap('<div id="mask"></div>');
		
		var $mask = $('#mask', $container) // masking div
		var maskHeight = $mask.height(); // get height of masking div
		
		// add sel class to first tab
		$tabs.filter(':first').addClass('sel');
		
		// set css properties on li items (panels)
		$panels.css({
			position: 'absolute',
			top: 0,
			left: 0
		});
		
		// remove css top property on ul (panelsContainer) (it's applied to mask when JS is enabled)
		$panelsContainer.css({
			top: 0
		});
		
		// append first panel to end of list
		$panelsContainer.append($panels.filter(':first-child'));
		
		// bind click event to tabs
		$tabs.click(function() {
		
			var $newTab = $(this);
			
			// remove and add sel class
			$newTab.parent().siblings().children().removeClass('sel');
			$newTab.addClass('sel');
			
			// get href, removing '#'
			panelId = $newTab.attr('href').split("#")[1];
			
			// check if selected panel is not current (last in list)
			var currentPanel = $panels.filter(':last-child').attr('id'); // get current panel ID
			
			if (panelId !== currentPanel) {
			
				// reset mask height if different to original height
				if ($mask.height() > maskHeight ) {
					$panels.filter(':last-child').find('.read-more').click(); // hide last read more text
				}
				
				// hide, append and fadeIn panel
				$panels
					.filter('[id=' + panelId + ']')
						.hide()
						.appendTo($panelsContainer)
						.fadeIn(450);
			}
			
			return false;
		});
		
		$panels.find('.read-more').toggle(function() {
			//var height = $(this).parent().parent().parent();
			var height = $(this).parents('li').outerHeight(); // watch this!
		
			$mask.stop().animate({
				height: height
			}, 450, 'swing');
			
			$(this).text('Read less');
			
			return false;
		}, function() {	
			
			$mask.stop().animate({
				height: maskHeight
			}, 450, 'swing');
			
			$(this).text('Read more');
		
			return false;
		});
	}
	
	// Modified read more script (only for break ideas )
	$.fn.readMoreDropDown = function() {
	
		var $container = $(this); // switcher container
		var $panelsContainer = $('#panels', $container); // panels ul
		var $panels = $panelsContainer.children('li'); // panels
		var $readMore = $('.read-more', $panels); // read more link

		// insert masking DIV
		$($panelsContainer).wrap('<div id="mask"></div>');
		
		var $mask = $('#mask', $container) // cache masking div
		var maskHeight = $mask.height(); // get height of masking div
		
		// remove positioning on panels as is now shifted to mask for animation
		$panelsContainer.css({top:0});
		
		// bind click function to expand mask to reveal read-more content
		$readMore.toggle(function() {
			//var height = $(this).parent().parent().parent();
			var height = $(this).parents('li').outerHeight(); // watch this!
		
			$mask.stop().animate({
				height: height
			}, 450, 'swing');
			
			$(this).text('Read less');
			
			return false;
		}, function() {	
			
			$mask.stop().animate({
				height: maskHeight
			}, 450, 'swing');
			
			$(this).text('Read more');
		
			return false;
		});
	}
	
	$.fn.tooltip = function(options) {
		var defaults = {
		  	background: '#181818',
			color: '#CBA546',
			rounded: 'false'
		  },
		  settings = $.extend({}, defaults, options);

		  return this.each(function() {
		  	var $anchor = $(this); // cache current anchor
			var title = this.title;
			
			if ($anchor.is('a') && $anchor.attr('title') != '') {
				this.title = ''; // remove browser default tooltip
				
				// prevent default action
				$anchor.click(function() {
					return false;
				});
				
				// bind hover event
				$anchor.hover(function(e) {
					// mouse over
					$('<div class="tooltip-container"></div>')
						.appendTo('body')
						.text(title)
						.hide()
						.css({
							'position': 'absolute',
							'backgroundColor': settings.background,
							'color': settings.color,
							'top': e.pageY + 10,
							'left': e.pageX + 20
						})
						.fadeIn(350);
						
					if (settings.rounded) {
						$('.tooltip-container').addClass('rounded');
					}
					
				}, function() {
					// mouse out
					$('.tooltip-container').fadeOut(350, function() {
						$(this).remove();
					}); 
				});
			}
			
			$anchor.mousemove(function(e) {
				$('.tooltip-container')
					.css({
						'top': e.pageY + 10,
						'left': e.pageX + 20
					});
			});
			
		});
	};
	
	
	/** object methods **/
	$.fn.dynamicInputLabels = function() {
	
		var inputFocus = function($input) {
			
			// IE doesn't set a define .defaultValue on inputs inserted into DOM with JS
			// so class must be added and checked instead of defaultValue
			if ($input.hasClass('dummy')) {
				$input.prev('input').show().focus().end().hide();
			}
			
			if ($input.val() === $input[0].defaultValue) {
				$input.val('');
			}
		};
		
		var inputBlur = function($input) {
		
			if ($input.is(':password') && $input.val() === '') {
				$input.next('input').attr('value', $input[0].defaultValue).show().end().hide();
			}
			
			if ($input.val() === '') {
				$input.val($input[0].defaultValue);
			}
		};
	
		return this.each(function() {

			var $thisInput = $(this).prev('label').hide().end();
			
			if ($thisInput.is(':password')) {
						
				value = $thisInput.attr('value');

				$('<input type="text" value="' + value + '" class="text dummy" />').insertAfter($thisInput)
					.focus(function() {
						inputFocus($(this));
					}).blur(function() {
						inputBlur($(this));
					});
				
				$thisInput.hide();
				
			}

			$thisInput.focus(function() {
				inputFocus($thisInput);
			});
			
			$thisInput.blur(function() {
				inputBlur($thisInput);
			});
			
		});
	};
})(jQuery);


jQuery(document).ready(function($) {

	$('body').addClass('js-enabled');

	$.mainOffersSlider.init($('#latest-offers-main'));
	$.miniOffersSlider.init($('#latest-offers-mini'));
	
	// run fader widget
	$('#tabbed-content-fade').faderWidget();
	
	// run read more drop down (only for break ideas page - inns detals page is done within faderWidget)
	$('#tabbed-content').readMoreDropDown ();
	
	// run homepage bg switcher
	$('#home-bg').homeBgSwitcher(); // only called on homepage
	
	// run tooltip
	$('a.tooltip').tooltip();

	
	// show password + confirm password inputs if remember me is checked (personal info page)
	var $form = $('#personalDetails'); // cache form
	var $checkbox = $form.find('#RememberMe');
	
	// insert container around password inputs and set height to 0
	var $passwordInputs = $form.find('#ConfirmPassword, #NewPassword').parent();
	
	$passwordInputs.wrapAll('<div class="clearfix" id="pwd-container">'); // wrap div
	
	var $pwdContainer = $('#pwd-container').css({
		overflow: 'hidden',
		position: 'relative'
	}); // cache containing div
	
	var height = $pwdContainer.height(); // store original height

	$pwdContainer.height(0); // set height to 0
	
	// bind check event
	$checkbox.click(function() {
		if ($(this).is(':checked')) {
			// show password inputs
			//$passwordInputs.slideDown(250);
			$pwdContainer.animate({
				height: height
			}, 250);
		}
		else {
			// hide password inputs
			//$passwordInputs.slideUp(250);
			$pwdContainer.animate({
				height: 0
			}, 250);
		}
	});
	
	// focus/blur invite input labels
	var $inviteInputs = $('#friendInvite input[type=text]');
	if ($inviteInputs.length)
		$inviteInputs.dynamicInputLabels();
	
});
