function SmoothScroll() {
	$('.scroll').click(function() {
	  if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
	  && location.hostname == this.hostname) {
		var $target = $(this.hash);
		$target = $target.length && $target
		|| $('[name=' + this.hash.slice(1) +']');
		if ($target.length) {
		  var targetOffset = $target.offset().top;
		  $('html,body')
		  .animate({scrollTop: targetOffset}, 1000);
		 return false;
		}
	  }
	});
}

function DropDownMenu () {
	
	var display_timeout = 0;
	$("li.has-subnav").hover(function () {
		$("li.has-subnav").removeClass('subnav-active');							   
		if(display_timeout != 0) { clearTimeout(display_timeout); }
		var this_element = this;
		$(this_element).addClass('subnav-active');
	},
		function () {
			if(display_timeout != 0) { clearTimeout(display_timeout); }
			var this_element = this;
			$(this_element).removeClass('subnav-active');
		}
	);	
}

function alertPopUp(popUpAlert){
	
	$('embed, object, select').css({ 'visibility' : 'hidden' });
	
	$('body').append('<div id="overlay"></div>');
	
	var arrPageSizes = ___getPageSize()
	var arrPageScroll = ___getPageScroll();

	$('#overlay').css({
		position:			'absolute',
		top:				0,
		left:				0,
		'z-index':			9000,
		display:			'none'			
	});
	
	$('#overlay').css({
		backgroundColor:	'#000',
		opacity:			0.5,
		width:				arrPageSizes[0],
		height:				arrPageSizes[1],
		display:			'none'			
	}).fadeIn(800);
	
	popUpAlert.css({'display': 'block'});
	
	var windowWidth = $(window).width() / 2;	
	var windowHeight = $(window).height() / 2;
	var xPos = (windowWidth - popUpAlert.width() / 2);
	var arrPageScroll = ___getPageScroll()
	var yPos = (windowHeight - popUpAlert.height() / 2) + (arrPageScroll[1]);
	popUpAlert.css({'left': xPos + 'px',
							'top': yPos + 'px'});
							
	$(window).scroll(function(){
		var arrPageScroll = ___getPageScroll()
		yPos = (windowHeight - popUpAlert.height() / 2) + (arrPageScroll[1]);
		popUpAlert.css({'left': xPos + 'px',
							'top': yPos + 'px'})
	});
	
	$('#overlay, .alertPopUp .button.close').click(function(){
		_finish(popUpAlert);
		return false;	
	})
	
}

function ___getPageSize() {
	var xScroll, yScroll;
	if ($(window).innerHeight && $(window).scrollMaxY) {	
		xScroll = $(window).innerWidth + $(window).scrollMaxX;
		yScroll = $(window).innerHeight + $(window).scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
};	
			
function ___getPageScroll() {
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
};

function _finish(popUpAlert) {
	$('#overlay').fadeOut(function() { $('#overlay').remove(); });
	popUpAlert.hide();
	// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
	$('embed, object, select').css({ 'visibility' : 'visible' });
}

function invitationCreatorTemplatePreview() {
	$('#TemplateID').change(function() {
		if ($('#BasicDetails .theme'))
			$('#BasicDetails .theme').remove();
		$.post('/invitationCreator/AjaxImagePreview?TemplateID=' + $(this).val(), function(data) { $('.formControls').before(data); }, "text");
	});
}
function formPasteDisable() {
	$("input.disablePaste").bind("paste", function(e) {
		return false;
	});
}
function HandleFeedbackTypeChange() {
	var value = $("#TypeOfFeedback").val();

	if (value == "Product/Packaging") {
		$("#fieldwrapper_Barcode").show();
		$("#fieldwrapper_BestBeforeDate").show();
		$("#fieldwrapper_AnyOtherCodes").show();
		$("#fieldwrapper_PricePaid").show();
		$("#fieldwrapper_ProductDetail").show();
		$("#alertinfo_AnyOtherCodes").show();
		$("#alertinfo_Barcode").show();
	} else {
		$("#fieldwrapper_Barcode").hide();
		$("#fieldwrapper_BestBeforeDate").hide();
		$("#fieldwrapper_AnyOtherCodes").hide();
		$("#fieldwrapper_PricePaid").hide();
		$("#fieldwrapper_ProductDetail").hide();
		$("#alertinfo_AnyOtherCodes").hide();
		$("#alertinfo_Barcode").hide();
	}
}

function ContactFormCustom() {
	if ($("#TypeOfFeedback").size() == 1) {
		$("#TypeOfFeedback").change(function() {
			HandleFeedbackTypeChange();
		});
		HandleFeedbackTypeChange(); // Do initial set up
	}
}

/*
function Accordian() {
	var togglers = $('.openingTimes h3');
	var elements = ".openingTimes .timeTable";

	$(elements).hide();
	$(elements + ':first').show()
	$('.openingTimes h3:first').addClass('active');
	togglers.click(
	function() {
		$('.openingTimes h3').each(function(){ $(this).removeClass("active"); })
		var checkElement = $(this).next();
			if((checkElement.is(elements)) && (checkElement.is(':visible'))) {
			checkElement.slideUp(500);
			$(this).removeClass('active');
			return false;
		}
		if((checkElement.is(elements)) && (!checkElement.is(':visible'))) {
			$(elements + ':visible').slideUp(500);
			checkElement.slideDown(500);
			$(this).addClass('active');
			return false;
		}
	});
}
*/
function Accordian() {
	var togglers = $('#seasonalTimes h3');
	var elements = "#seasonalTimes .timeTable";

	$(elements).hide();
	$('#seasonalTimes h3:first').addClass('active');
	togglers.click(
	function() {
		$('#seasonalTimes h3').each(function(){ $(this).removeClass("active"); })
		var checkElement = $(this).next();
			if((checkElement.is(elements)) && (checkElement.is(':visible'))) {
			checkElement.slideUp(500);
			$(this).removeClass('active');
			return false;
		}
		if((checkElement.is(elements)) && (!checkElement.is(':visible'))) {
			$(elements + ':visible').slideUp(500);
			checkElement.slideDown(500);
			$(this).addClass('active');
			return false;
		}
	});
}

$(document).ready(function(){
	
	SmoothScroll();
	DropDownMenu();
	invitationCreatorTemplatePreview();
	// PNG Fix
	
	$(document).pngFix();
	
	var volatile = $("input[type=text]")
	volatile.focus(function(event){
        if ($(this).val() == $(this).attr("title") ){        
            $(this).val("");
        }}, volatile.blur(function(event){
            if ($(this).val() == "" ){        
                $(this).val($(this).attr("title"));
            }
        }
    ));

	// Custom inputs

	$('input').customInput();

	$('.contact .fullWidth select').selectmenu({style:'dropdown', width: '298px', maxHeight: 200 });
	$('.contact .dateSelect select').selectmenu({style:'dropdown', width: '92px', maxHeight: 200 });

	// Video Player

	$('#customVideoPlayer').flash({
		src: '/_images/flash/YoutubePlayer.swf',
		width:650,
		height: 400,
		flashvars:	{
			videoID:"yAJn3CD2atU", 
			videoQuality:"hd1080", 
			videoBackgroundColor:"0x666666",
			strokeColor:"0x999999",
			controlColor:"0x333333",
			controlHoverColor:"0xed1c24",
			defaultVol:30
		}
	});
	
	// Homepage Main Carousel
	
	var titleArray = [];
	var imageArray = [];
	var linksArray = [];

	$('#homeCarousel ul.slides li').each(function(index) {	
		titleArray.push($(this).find('img').attr('alt'));
		imageArray.push($(this).attr('rel'));
		linksArray.push($(this).children('a').attr('href'));
	 });

	$('#homeCarousel ul.slides').show();

	$("#homeCarousel ul.slides").carouFredSel({
		width: 448,
		height: 248,
		items: {
			visible: 1,
			width: 448,
			height: 248
		},
		scroll: {
			duration: 0
		},
		auto: 3000,
		pagination: {
			container: "#homeCarousel ul.slideNav",
			keys: true,
			anchorBuilder: function(nr) {
				var str  = '<li>';
					str += '<a href="'+linksArray[nr - 1]+'"><img src=';
					str += imageArray[nr - 1];
					str += ' width="77" height="42" alt="" />'
					str += titleArray[nr - 1];
					str += '</a>';
					str += '</li>';
				return str;				
			}
		}	
	});
		
	$('#homeCarousel ul.slideNav li').mouseover(function(){
		var position = $(this).index();
		$(this).addClass('selected')
		$("#homeCarousel ul.slides").trigger("slideTo", position);
		$("#homeCarousel ul.slides").trigger("pause");
	});
	
	$('#homeCarousel ul.slideNav li').mouseout(function(){
		$("#homeCarousel ul.slides").trigger("play");
	});
	
	$('#homeCarousel ul.slideNav li a').click(function(){
		var URL = $(this).attr('href');
		window.location.href = URL
	});
	
	// Homepage Pod Carousel
	
	$("#slideShow ul.slides").carouFredSel({
		width: 272,
		height: 115,
		items: {
			visible: 1,
			width: 272,
			height: 115
		},
		scroll: {
			duration: 300,
			easing: "linear"
		},
		auto: false,
		prev: {
			button: ".previous a",
			key: "left"
		},
		next: {
			button: ".next a",
			key: "right"
		}
	});	
	
    //Opening Times Toggle
	
	Accordian();
	
	//Popup Triggers
	
	$('.bookmark').click(function(){
		alertPopUp($('#bookmarkAlert'));
		return false;
	});
	

	$('#printInvites').click(function(e) {
		var piAlert = $("#inviteAlert");
		piAlert.html('<h2>Invitations Sent</h2><p>Your invitations have been emailed to the email addresses you entered. Your guests should receive them shortly.</p><a class="button" href=""><span>Close</span></a>');
		alertPopUp(piAlert);
		$("#inviteAlert a.button").click(function(e) { e.preventDefault(); _finish(piAlert) });
	})

	$('.coolButton').click(function(e) {
		var nodeRef = $(this);
		var addUrl = nodeRef.attr('href');

		e.preventDefault();
		$.ajax({
			type: "GET",
			url: addUrl,
			data: "ajax=true",
			success: function(htmlResponse) {
				$("#coolListAlert").html(htmlResponse);
				alertPopUp($("#coolListAlert"));
				nodeRef.remove();
			}
		});
	});
	
	$('.inviteAlert').click(function(){
		alertPopUp($('#inviteAlert'));
		return false;
	});
	
	$('.contactPhone').click(function(){
		alertPopUp($('#contactPhone'));
		return false;
	});

	$('.contactPost').click(function(){
		alertPopUp($('#contactPost'));
		return false;
	});
	formPasteDisable();
	ContactFormCustom();
});

