/*  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() {
	guide();
	newsHome();
	deepFooter();
	deepFooterLinks();
	mealsMenuShowHide();
	changePostcode();
	faqs();
	validation();
	formSubmit();
	externalLinks();
	seo_allProds()
	landing_imgs();
	notify_fix();
	basketInit();
	productListing();
	initShowMore();
	jQuery.ajaxSetup({ timeout: 7000, cache: false });
	hideShowPassowrd();
	setupCycler('.imagesRotator');
});

/* Generic page functionality */

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 updatePostcode() {
	//start with a cookie test. If cookies are disabled, don't even bother with anything else!
	headscapeDOM.setCookie('jsCookiesEnabled', 'Yes', 1);
	if (headscapeDOM.getCookie('jsCookiesEnabled') != 'Yes') {
		location.href = '/cookies.asp';
	}
	//flash the postcode box if nothing entered
	if (jQuery(this).find('input[name=postcode]').val() == '') {
		jQuery(this).find('input[name=postcode]').parent()
                                              .animate({ opacity: '.4' }, 200)
                                              .animate({ opacity: '1' }, 100)
                                              .animate({ opacity: '.4' }, 200)
                                              .animate({ opacity: '1' }, 100, function() { jQuery(this).css({ opacity: '' }); });
		return false;
	}
	clickFire(); //shows a loading graphic in the popup
	//stop products being added to the basket while we're updating the postcode
	wffBasket.updatingPostcode = true;
	jQuery.post('/api/franchise.api.asp', jQuery(this).serialize(), function(jo) {
		//show any errors (such as bad postcode)
		if (jo.errorText && jo.errorText.length > 0) {
			jQuery('#warningMessage .title').text('something has gone wrong');
			jQuery('#warningMessage p').html('<ul>' + jo.errorText + '</ul>');
			jQuery('#warningMessage').fadeIn();
		}
		//show any warnings (such as change of basket items / price)
		else if (jo.warningText && jo.warningText.length > 0) {
			jQuery('#warningMessage .title').text('Please note..');
			jQuery('#warningMessage p').html('<ul>' + jo.warningText + '</ul>');
			jQuery('#warningMessage').fadeIn();
			//regardless of any errors / warnings, update the product listing (if we havea  franchise)
			//If there's a warning, that just means we have actually switched franchises. No warning implies no switch.
		}
		else {
			jQuery('#warningMessage').hide();
		}
		if (+jo.franchiseId > 0) {
			//update users postcode
			jQuery('.basketPostcode').text(jo.basketPostcode);
			//update franchise details everywhere
			jQuery('.franchiseName').text(jo.franchiseName);
			jQuery('.franchisePostcode').text(jo.franchisePostcode);
			jQuery('.franchiseTel').text(jo.franchiseTel);
			jQuery('a.franchiseEmail').attr('href', 'jo.franchiseEmail').text(jo.franchiseEmail);
			jQuery('.franchiseOpenTimes').text(jo.franchiseOpeningTimes);
			jQuery('.franchiseAddr1').text(jo.franchiseAddress1);
			jQuery('img.outletPic').attr('src', jo.franchiseImage == '' ? '/images/outletpic.jpg' : '/images/franchise/' + jo.franchiseImage);
			//hide forms to enter postcode
			jQuery("#toolsOutlet").removeClass('showPostcodeEntry');
			//flash the box on the homepage
			jQuery('#homeTextLocation').animate({ opacity: "0" }, 250)
                                       .queue(function() { jQuery(this).addClass('hasFranchise'); jQuery(this).dequeue(); })
                                       .animate({ opacity: "1" }, 250)
                                       .animate({ opacity: "0.8" }, 250)
                                       .animate({ opacity: "1" }, 250);
			jQuery.getJSON('/api/basket.api.asp', function(jo) {
				if (jo.intProdCount == '') jo.intProdCount = 0;
				jQuery('#basketCount').text(jo.intProdCount + ' item' + (jo.intProdCount != 1 ? 's' : ''));
				jQuery('#basketPrice').text(jo.mnyTotal);
			});
			//get the current address, in partial-request form.
			var addr = location.href;
			if (addr.indexOf('#') > 0) addr = addr.slice(0, addr.indexOf('#'));
			addr += (addr.indexOf('?') > 0 ? '&' : '?') + 'request=partial';

			jQuery('#mealsMenu >ul').load(addr + '&onlyshow=mealsmenu #mealsMenu>ul>*', function(responseText, textStatus, XMLHttpRequest) {
				if (textStatus == 'success') mealsMenuShowHide();
			});
			if (jQuery('#prodList,#productList,#prodTypeList,#prodGroupList,#dietDetailsImg,#mainContent').length > 0) {
				var id = jQuery('#prodList,#productList,#prodTypeList,#prodGroupList,#dietDetailsImg,#mainContent').attr('id');
				//fade it out, and update with correct products
				jQuery('#' + id + ' form').fadeTo('slow', .2);
				jQuery('#productLoader').fadeIn();
				jQuery('#' + id).load(addr + ' #' + id + ' >*', function() {
					jQuery('#productLoader').fadeOut();
					wffBasket.updatingPostcode = false;
					//wffBasket.watch();
					basketInit();
					closePop(); //close any popups
					//check if we now have an empty product list
					if (jQuery('#prodList li,#productList li,#prodTypeList li').length == 0)
						jQuery('#prodList,#productList li,#prodTypeList').html('<li><h2>Sorry, this franchise doesn\'t stock any products for this category.</h2></li>');
				});
			}
			else {
				wffBasket.updatingPostcode = false;
				basketInit();
				closePop(); //close any popups
			}
		}
		else {
			wffBasket.updatingPostcode = false;
			closePop(); //close any popups
		}

	}, 'json');
	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;
		});
	});
}
//

var navexpanded = false;
function mealsMenuShowHide() {
	jQuery(".mealsMenu ul li:gt(6)").addClass('toggleItems');
	jQuery(".mealsMenu .mealsMenu_new").removeClass('toggleItems');
	jQuery(".mealsMenu ul").append('<li class="showMore"><a href="#"><em class="more">Vegetarian and more</em><em style="display:none;" class="fewer">Show Fewer</em></a></li>');
	jQuery(".mealsMenu .showMore").click(toggleMenu);
	if (headscapeDOM.getCookie('expandnav') == 'true') toggleMenu();
}

function toggleMenu() {
	jQuery(".mealsMenu .toggleItems").toggle(500);
	jQuery(".mealsMenu .showMore em:eq(0)").toggle(300);
	jQuery(".mealsMenu .showMore em:eq(1)").toggle(300);
	jQuery(".tHome .brochure").toggle();
	navexpanded = !navexpanded;
	headscapeDOM.setCookie('expandnav', navexpanded, 1);
	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);
	}
}

/* SEO (all_products page) */
function seo_allProds() {
	jQuery('body.tseo 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('body.tseo .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;
	});
}

/* Validation */

function validation() {
	jQuery("#cIssue").bind('keyup', function() {
		if (jQuery(this).val().length > 2) {
			alert('Please note that the Issue number on maestro cards will be shown on the front of your Maestro card.\r\nYou do not need to enter the digit CV2 security number for your card to place an order with Wiltshire Farm Foods');
		}
	});
}

/* Form Submission */

function formSubmit() {
	//prevent double submissions of special forms (ie. final checkout)
	jQuery('#specialF,#existCustForm,#feedback,#sendFriend').submit(function() {
		if (jQuery(this).data('submitted') == true) {
			return false;
		}
		else {
			jQuery(this).data('submitted', true)
			return true;
		}
	});
}

/* Home page functionality */

function guide() {
	jQuery("#homeGuide .col").click(function() {
		jQuery("#homeGuide .wrapper").toggleClass('collapse').find('ol').slideToggle(500);
		headscapeDOM.setCookie('homeguide', jQuery("#homeGuide .wrapper").hasClass('collapse'), 1);
		return false
	});
	//collapse by default.
	//if (headscapeDOM.getCookie('homeguide') == null) headscapeDOM.setCookie('homeguide', true, 1);
	if (headscapeDOM.getCookie('homeguide') == 'true') jQuery("#homeGuide .col").click();
}

function newsHome() {
	jQuery("#newsHome .col").click(function() {
		jQuery("#newsHome .wrapper").toggleClass('collapse').find('ol').slideToggle(500);
		headscapeDOM.setCookie('homenews', jQuery("#newsHome .wrapper").hasClass('collapse'), 1);
		return false
	});
	jQuery('#newsHome li').click(function() {
		location.href = jQuery(this).find('a:eq(0)').attr('href');
	});
	if (headscapeDOM.getCookie('homenews') != 'false') jQuery("#newsHome .col").click();
}

/* 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 = {

	addRating: function(customerId, productId, rating, e) {
		jQuery.post('/api/reviews.api.asp', 'a=addrating&c=' + customerId + '&pr=' + productId + '&p=' + rating, wffReview.redrawRatings, 'json');
		// Stop the form submitting
		if (window.event) {
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
		if (e && e.stopPropagation && e.preventDefault) {
			e.stopPropagation();
			e.preventDefault();
		}
		return false;
	},

	redrawRatings: function(wffAPIResponse) {
		if (!wffAPIResponse.Error) {
			var oResponse = wffAPIResponse.Value;
			if (oResponse.Type == 'Redirect') {
				window.location = oResponse.Destination;
			}
			if (oResponse.Type == 'Rating') {
				var totalScore = oResponse.TotalScore;
				var totalVotes = oResponse.TotalVotes;
				var newScore = oResponse.NewScore;
				var newStarWidth = oResponse.NewStarWidth;
				var message = oResponse.Message;
				var rating = oResponse.Rating;

				jQuery('#current-text-rating2').html('&nbsp;&nbsp;(' + newScore + ')');
				jQuery('#current-rating2').css({ width: newStarWidth + 'px' });

				message = newScore + ' star';
				if (newScore != 1) message = message + 's';
				message = message + ' based on an average over ' + totalVotes + ' rating';
				if (totalVotes != 1) message = message + 's';
				message = message + '.';
				jQuery('#current-text-rating2-description').html(message);
				jQuery('#starrating-1,#starrating-2,#starrating-3,#starrating-4,#starrating-5').css({ visibility: 'hidden' });

				message = 'You have rated this product.  Your rating was : <strong>' + rating + ' Star';
				if (rating != 1) message = message + 's';
				message = message + '.</strong><br /><strong>4 Stars</strong> - Excellent, <strong>4 Stars</strong> - Good, <strong>3 Stars</strong> - Average, <strong>2 Stars</strong> - Below Average, <strong>1 Star</strong> - Poor';
				jQuery('#customers-rating').html(message);
			}
		} else {
			alert(wffAPIResponse.Error.Message);
		}
	},

	submitReview: function(customerId, productId, review) {
		jQuery.post('/api/reviews.api.asp', 'a=addcomment&c=' + customerId + '&pr=' + productId + '&p=' + escape(review), wffReview.redrawReview, 'json');
	},

	redrawReview: 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);
		}
	},

	publishReviews: function(strParams) {
		jQuery.post('/api/reviews.api.asp', strParams, wffReview.publishComplete, 'json');
	},

	publishComplete: function(wffAPIResponse) {
		if (!wffAPIResponse.Error) {
			var oResponse = wffAPIResponse.Value;
			if (oResponse.Type == "Redirect") {
				window.location = oResponse.Destination;
			}
		} else {
			alert(wffAPIResponse.Error.Message);
		}
	},

	showForm: function() {
		jQuery('#reviewForm').show();
	}
}

function productListing() {
	//MJC remove edspopup for productpages test
	/*jQuery('.productListing a, .basketProductLink a').live('click', function() {
		clickFire(this, function(box) {
			var prodCode = box.find('input[name=pid],input[name=mid]').attr('name') + '-' + box.find('input[name=pid],input[name=mid]').val();
			basketInit('#edspopupbox .productForm');
		});
		return false;
	});*/
	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);
	});
	//adding / removing favs
	jQuery('a.favourite').live('click', function() {
		var l = this;
		var href = jQuery(this).attr('href');
		jQuery.get('/api/favourites.api.asp' + href + '&request=partial', function(msg) {
			if (msg.toString().length == 0) {
				//jQuery('#warningMessage').show().find('p').text('Unfortunately this item couldn\'t be added to your favourites. Please make sure you are signed in and then try again.');
				window.location = href;
			} else {
				jQuery('.successBox').show().find('p').text(msg);
			}
			//find all identical links. like, say on favourites page.
			$('a[href=' + $(l).attr('href') + ']').each(function() {
				var link = this;
				//if we just added it, we give em a link to remove again.
				if (msg.indexOf('added to') > 0) {
					$(link).text('Remove from favourites').closest('prodDetails_fav').addClass('isFavourite');
					if ($(link).closest('table').hasClass('myAccountTable')) {
						$('.favouritesList tr:last').after(
							$(link).closest('td').removeClass('myAccountTableAdd').addClass('myAccountTableRemove').closest('tr').clone()
						);
					}
				}
				//and vice versa.
				else if (msg.indexOf('removed from') > 0) {
					if ($(link).closest('table').hasClass('favouritesList')) {
						$(link).closest('tr').fadeOut(700);
					}
					else {
						if ($(link).closest('table').hasClass('myAccountTable'))
							$(link).closest('td').removeClass('myAccountTableRemove').addClass('myAccountTableAdd');
						$(link).text('Add to favourites').closest('prodDetails_fav').removeClass('isFavourite');
					}
				}
			});
		});
		return false;
	});
	//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');
			}
		});
	}
}

/* Account section */

function hideShowPassowrd() {
	//hiding and showing form fields and things
	jQuery('.textPasswordShow').show();
	jQuery('.textPasswordShow').toggle(function() {
		jQuery('.pwdObfuscated').hide();
		jQuery('.pwdText').show();
		jQuery(this).text('Hide this password');
	},function() {
		jQuery('.pwdText').hide();
		jQuery('.pwdObfuscated').show();
		jQuery(this).text('Show this password');
	});
	jQuery('.formPair .fpInput').hide();
	jQuery('.formPair .fpText').show();
	jQuery('.formPair .editValue').click(function() {
		jQuery(this).closest('.fpText').hide().siblings('.fpInput').show().find('input:first').focus();
		return false;
	});
	jQuery('.resetForm').click(function() {
		jQuery('.formPair').removeClass('valid').removeClass('invalid');
		jQuery('.formPair .fpInput').hide();
		jQuery('.formPair .fpText').show();
	});
	
	//make print buttons work
	jQuery('.printOrder').show().click(function() {
		window.print();
		return false;
	});
}

function setupCycler(e) {
	e = jQuery(e);
	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);
}