/*  GENERAL
These scripts provide javascrip functionality to enhance the UX. 
Functions here should be overridng default behaviours with a javasciprt alternative.
*/

// Initial setup
jQuery(function () {
	deepFooter();
	deepFooterLinks();
	mealsMenuShowHide();
	changePostcode();
	faqs();
	externalLinks();
	seo_allProds()
	landing_imgs();
	notify_fix();
	basketInit();
	productListing();
	initShowMore();
	jQuery.ajaxSetup({ timeout: 7000, cache: false });
	setupCycler('.imagesRotator');
	hideMessage();
	recommendedProducts();
	textBoxSwap();
	selectAddress();
	removeHover();
});

/* Generic page functionality */

function textBoxSwap() {
	//text-box focus-swap
	//Store the default value for each box
	$('input[type=text][value].swaptextbox').each(function () {
		$(this).data('swap', $(this).attr('value'));
	}).bind('focus', function () {
		if ($(this).val() == $(this).data('swap')) {
			$(this).val('');
		}
	}).bind('blur', function () {
		if ($(this).val() == '') {
			$(this).val($(this).data('swap'));
		}
	});
}

function changePostcode() {
	jQuery("#homeTextLocation a.changeFranchise").click(function () {
		jQuery("#homeTextLocation").removeClass('hasFranchise');
		return false
	});
	//jQuery('form.fChangePostcode').submit(updatePostcode);
	jQuery('.enterPostcode').click(function () {
		clickFire(this, function (f) {
			//f.find('form').submit(updatePostcode);
		});
		return false;
	});
}

function deepFooter() {
	jQuery("#deepFooter .footerTitle").click(function () {
		jQuery("#deepFooter .wrapper").toggleClass('collapse').find('div:not(.footerTitle)').slideToggle(500);
		headscapeDOM.setCookie('expandfooter', jQuery("#deepFooter .wrapper").hasClass('collapse'), 1);
		return false
	});
	if (headscapeDOM.getCookie('expandfooter') == 'true') jQuery("#deepFooter .footerTitle").click();
}

function deepFooterLinks() {
	jQuery('#deepFooter .moreLinks').hide();
	jQuery('.showmore').show().toggle(function () {
		jQuery(this).siblings('li.moreLinks').slideDown('slow');
		jQuery(this).children('span').html('Show Fewer &uarr;');
	}, function () {
		jQuery(this).siblings('li.moreLinks').slideUp('slow');
		jQuery(this).children('span').html('Show More &darr;');
	});
}

function externalLinks() {
	jQuery('a.externalLink').each(function () {
		var titleStr = jQuery(this).attr("title");
		if (titleStr != "" && titleStr != undefined) {
			titleStr += " (new window)";
		} else {
			titleStr = "(new window)";
		}
		jQuery(this).attr("title", titleStr);
		jQuery(this).click(function () {
			window.open(this.href);
			return false;
		});
	});
}
//

function mealsMenuShowHide() {
	var mealsMenuHeight = $('#mealsMenu').height();
	var factor = 1.1;
	$('#hideMealMenu').show().click(function () {
		$('#mealsMenu').animate({ height: mealsMenuHeight * factor }, 200).slideUp(400);
		headscapeDOM.setCookie('expandnav', false, 30);
		return false;
	});
	$('#navigation2011 .mealsButton a').click(function () {
		if ($('#mealsMenu').is(':hidden')) {
			$('#mealsMenu').slideDown(400).animate({ height: mealsMenuHeight }, 100);
			headscapeDOM.setCookie('expandnav', true, 30);
		} else {
			$('#mealsMenu').animate({ height: mealsMenuHeight * factor }, 100).slideUp(400);
			headscapeDOM.setCookie('expandnav', false, 30);
		}
		return false;
	});
	if (headscapeDOM.getCookie('expandnav') == 'false')
		$('#mealsMenu').css({ height: mealsMenuHeight * factor }).hide();
}

function recommendedProducts() {
	$('.col4Products .showMore').click(function () {
		$(this).hide().next('ul.productList').show();
		return false;
	});
}


function hideMessage() {
	var hide_messages = headscapeDOM.getCookie('hide_message');
	$(hide_messages).hide();
	$('.announceBox .closeBox a').click(function () {
		$(this).closest('.announceBox').fadeOut();
		if (hide_messages != null)
			hide_messages += ",";
		else
			hide_messages = "";
		hide_messages += "#" + $(this).closest('.announceBox').attr('id');
		headscapeDOM.setCookie('hide_message', hide_messages, 30);
		return false;
	});
}

//IE needs the basket notification to be at the bottom of the page (after the iframe) for Z-Indexing reasons.
function notify_fix() {
	if (jQuery('#basketLatestIframe').length > 0) {
		/*jQuery('#basketLatest').wrapInner('<div id="basketLatest"></div>')
		.after('#basketLatestIframe');*/
		latestDiv = jQuery('<div id="basketLatest"></div>').append(jQuery('#basketLatest > *'));
		jQuery('dd#basketLatest').remove();
		jQuery('#basketLatestIframe').after(latestDiv);
	}
}

// all-products page
function seo_allProds() {
	jQuery('#allProducts table').each(function () {
		jQuery(this).hide();
		var theTitle = jQuery(this).attr('title');
		jQuery(this).before('<p class="hideshow" title="' + theTitle + '"><a href="#">View more ' + theTitle + ' frozen ready meals</a></p>');
	});
	jQuery('#allProducts .hideshow').click(function () {
		if (jQuery(this).siblings('table:hidden').length > 0) {
			jQuery(this).siblings('table').slideDown();
			this.innerHTML = '<a href="#" class="colapse">Hide all ' + jQuery(this).next().attr('title') + ' frozen ready meals</a>';
		}
		else {
			jQuery(this).siblings('table').slideUp();
			jQuery(this).html('<a href="#">View more ' + jQuery(this).next().attr('title') + ' frozen ready meals</a>');
		}
		return false;
	});
}

/* FAQs */
function faqs() {
	jQuery('.lAnswer').hide();
	jQuery('.lQuestion').toggle(function () {
		jQuery(this).siblings('.lAnswer:hidden').slideDown("fast");
		return false;
	}, function () {
		jQuery(this).siblings('.lAnswer:visible').slideUp("fast");
		return false;
	});
}

/* Landing Pages */

function landing_imgs() {
	jQuery('img.landingImg').each(function () {
		var div = jQuery('<div class="' + jQuery(this).attr('class') + '"></div>');
		div.css('float', jQuery(this).css('float'));
		jQuery(this).wrap(div);
	});
}

/*
Scripts relating to product reviews / ratings
*/
var wffReview = {

	submitReview: function (customerId, productId, review) {
		jQuery.post('/product/submitreview', 'productId=' + productId + '&review=' + escape(review), function (wffAPIResponse) {
			if (!wffAPIResponse.Error) {
				var oResponse = wffAPIResponse.Value;
				if (oResponse.Type == "Redirect") {
					window.location = oResponse.Destination;
				}
				if (oResponse.Type == "Review") {
					jQuery('#reviewFormContainer').hide();
					jQuery('#reviewFormSent').show();
				}
			} else {
				jQuery('#reviewFormSent p[0]').text(wffAPIResponse.Error.Message);
			}
		}, 'json');
	},
	showForm: function () {
		jQuery('#reviewForm').show();
	}
}

function productListing() {
	jQuery('.mainImage img').live('click', function () {
		//jQuery('.mainImage,.prodDetails_info').fadeOut(500);
		jQuery('.bigImage').css({ zIndex: 100, position: 'absolute', left: '0px', top: '0px' }).fadeIn(500).children('img').css({ opacity: 1 });
	});
	jQuery('.bigImage').live('click', function () {
		//jQuery('.mainImage,.prodDetails_info').show();
		jQuery('.bigImage').fadeOut(500);
	});

	//hiding more than 3 reviews
	jQuery('.hreview.more').hide();
	if (jQuery('.hreview.more').length > 0)
		jQuery('#showMoreReviews').click(function () {
			jQuery('.hreview.more').show();
			jQuery(this).hide();
			return false;
		}).show();
}

function convertToNumber(str) {
	return Number(str.replace(/[^0-9\.]+/g, ""));
}

//automatically loads in more results to a page
function initShowMore() {
	if ($('.loadMore .next').length > 0) {
		$('.loadMore').hide().before('<img class="loadMoreImg" border="0" src="/images/loading.gif" alt=""/>');
		var triggerHeight = $('.loadMoreImg').offset().top - 100;
		var loading = false;
		$(window).scroll(function () {
			if (!loading && (jQuery(window).scrollTop() + jQuery(window).height()) > triggerHeight) {
				loading = true;
				$.get($('.loadMore .next').attr('href') + '&request=partial', function (data, textStatus) {
					var newProducts = $('.productList > li', data).addClass('justAdded');
					$('.productList').append(newProducts);
					basketInit('.justAdded form');
					newProducts.removeClass('justAdded');
					var next = $('.loadMore .next', data);
					if (next.length > 0) {
						$('.loadMore .next').attr('href', next.attr('href'));
						triggerHeight = $('.loadMoreImg').offset().top - 100;
						loading = false;
					}
					else {
						$('.loadMoreImg').remove();
					}
				}, 'html');
			}
		});
	}
}

function setupCycler(e) {
	e = jQuery(e);
	if (e.children().length > 1) {
		setInterval(function () {
			var next = e.find('.current').next();
			if (next.length == 0) next = e.children().eq(0);
			next.addClass('next');
			next.fadeIn(1400, function () {
				e.find('.current').removeClass('current');
				jQuery(this).removeClass('next').addClass('current').css({ display: '' });
			});
		}, 5000);
	}
}

function selectAddress() {
	$(".selectAddress dd a").hover(
		function () {
 			$(this).parent().parent().css({ 'background-color': '#E9F4DD', 'border-color': '#e4f1d6' });
		},
		function () {
		$(this).parent().parent().css({ 'background-color': '#fff', 'border-color': '#f1f7e9' });
		}
	);
}

function removeHover() {
	$("input.remove").hover(
		function () {
			$(this).attr("src", "/images/removeHover.gif");
		},
		function () {
			$(this).attr("src", "/images/remove.gif");
		}
	)
}
