/*
* J Sainsbury Plc 2011
* @25/07/11
*/

$(document).ready(function () {

	var $SAS = {}

	/* hide mobile_only links */
	if ((screen.width >= 600)) {
		$('.mobile_only').css("display", "none");
	}

	var AppSettings = {
		DEBUGMODE: true, //change to turn on/off console.log statements
		jsClass: "js",
		ieClass: "ie",
		isIE6: ($.browser.msie && $.browser.version.substr(0, 1) < 7) ? true : false
	};

	$SAS.Main = Main = {

		_selectedClass: "selected",
		_activeClass: "active",
		_hoverClass: "hover",

		//Run class, add page load methods here
		run: function () {
			$('html').addClass(AppSettings.jsClass);
			if ($.browser.msie && $.browser.version.substr(0, 1) < 9) $('html').addClass(AppSettings.ieClass);
			Plugins.launch();
			Utils.smoothScroll();
			Utils.externalLink();
			Utils.addExternalIcon();
			Utils.zebraStripes();
			Utils.tableFormat();
			Utils.smartSpacing();
			Utils.equalHeights();
			Utils.expandableContent();
			Utils.verticalCentre();
			DropdownNav.launch();
			WordFilter.init();
			Modal.launch();
			SocialNetworks.launch();
			Forms.launch();
			Interactions.valuesWheel();
			Aux.launch();
		}

	};

	$SAS.Plugins = Plugins = {

		_carouselSelector: ".carousel",

		launch: function () {
			this.rounded();

			var $carousel = $(this._carouselSelector);
			if ($carousel.length) this.initCarousel();
		},

		rounded: function () {
			if (!Modernizr.borderradius && !AppSettings.isIE6) {
				// Rounded images, anchor tags and divs
				$('img.rounded, a.rounded').each(function () {
					$(this).wrap('<span class="rounded_corners" />');
				});
				$('span.rounded_corners').append('<span class="corner tl" />').append('<span class="corner tr" />').append('<span class="corner br" />').append('<span class="corner bl" />');

				// Rounded tabs
				$('div.tabbed_content').each(function () {
					$(this).wrap('<span class="rounded_bottom" />');
				});
				$('span.rounded_bottom').append('<span class="corner br" />').append('<span class="corner bl" />');

				// Corner plugin
				//if (Utils.exists('div.tabbed_content')) $('div.tabbed_content').corner("bottom 6px");
				if (Utils.exists('div.rounded')) $('div.rounded').corner("6px");
			}

			// Rounded images, anchor tags and divs
			$('div.rounded_carousel, .carousel .pager a').each(function () {
				$(this).wrap('<span class="rounded_corners" />');
			});
			$('span.rounded_corners').append('<span class="corner tl" />').append('<span class="corner tr" />').append('<span class="corner br" />').append('<span class="corner bl" />');

		},

		initCarousel: function () {

			$('.uneven_thirds #hero_container .carousel, .home #hero_container .carousel, .paralympics #hero_container .carousel').recycle({
				auto: true,
				pager: "#hero_container .pager",
				onInit: function () { },
				onInitComplete: function () {
					$(this).find("li").each(function (i) {
						var $this = $(this, i),
						itemHeight = $this.find('.content_holder').height() / 2;
						$this.find('.content_holder').css({ "position": "absolute", "top": "50%", "margin-top": -itemHeight });
					})
				},
				onBeforeTransition: function (x, y) {
					var $roundal = $('.roundal.orange').eq(x).add($('.roundal.white').eq(x)).fadeOut(200);
					$('.roundal').not($roundal).hide();
				},
				onAfterTransition: function (x) {
					$('.roundal.orange').eq(x).add($('.roundal.white').eq(x)).fadeIn(400);
				}
			});

			$('#hero_container #key_facts_carousel .carousel').recycle({
				cyclic: false,
				shift: 3,
				speed: 400,
				btnNext: "#hero_container .shaded .carousel_nav .next",
				btnPrev: "#hero_container .shaded .carousel_nav .prev"
			});

			// count our values slides
			var numberOfSlides = $('#our_views .carousel').find('li').length;
			// random number function
			function randomRange(min, max) {
				return Math.random() * (max - min) + min;
			}
			// set and round random number var
			var randomSlideNumber = randomRange(1, numberOfSlides);
			var randomNumberRounded = Math.round(randomSlideNumber);
			// use random slide var as start point for carousel
			$('#our_views .carousel').recycle({
				cyclic: true,
				speed: 500,
				start: randomNumberRounded,
				btnNext: "#our_views .next",
				btnPrev: "#our_views .prev",
				onInitComplete: function () {
					var caption = $(this).find(".active .faux_header").html();
					$("#our_views .caption").html(caption);
				},
				onAfterTransition: function (curr) {
					var caption = $(this).children().eq(curr).find(".faux_header").html();
					$("#our_views .caption").html(caption);
				}
			});

			$('#carousel_news').recycle({
				shift: 4,
				visible: 4,
				btnNext: "#carousel_news_nav .next",
				btnPrev: "#carousel_news_nav .prev"
			});

			// count our values slides
			var numberOfFooterSlides = $('#footer_carousel .carousel').find('li').length / 2;
			// set and round random number var
			var randomFooterSlideNumber = randomRange(1, numberOfFooterSlides);
			var randomFooterNumberRounded = Math.round(randomFooterSlideNumber);
			// use random slide var as start point for carousel
			$('#footer_carousel .carousel').recycle({
				cyclic: true,
				speed: 400,
				start: randomFooterNumberRounded,
				btnNext: "#footer_carousel .carousel_nav .next",
				btnPrev: "#footer_carousel .carousel_nav .prev",
				onInitComplete: function () {
					var caption = $(this).find(".active .text_container").html();
					$(".carousel_caption").html(caption);
				},
				onAfterTransition: function (curr) {
					var caption = $(this).children().eq(curr).find(".text_container").html();
					$(".carousel_caption").html(caption);
				}
			});

			// Replicate vertical centering for single image roudels
			var $single_roundel = $('.roundel_image');
			if ($single_roundel.length) {
				var itemHeight = $('.roundel_image').find('.content_holder').height() / 2;
				$('.roundel_image').find('.content_holder').css({ "position": "absolute", "top": "50%", "margin-top": -itemHeight });
			};
		}

	};

	$SAS.Utils = Utils = {

		exists: function (element) {
			return $(element).length > 0 ? true : false;
		},

		getSelectedIndexValue: function (element) {
			return element.options[element.selectedIndex].value;
		},

		emptyDiv: function (elementId) {
			$(elementId).html('');
		},

		smoothScroll: function () {
			$('.smoothscroll a, a.smoothscroll, ul.nav_tabs li a').bind('click', function (event) {
				var $anchor = $(this);
				$('html, body').stop().animate({
					scrollTop: $($anchor.attr('href')).offset().top// - 20
				}, 800, 'easeInOutQuad');
				Debug.log($anchor.attr('href'));
				event.preventDefault();
			});

			/*$(window).load(function () {
			var $anchor = $(window.location.hash).attr('id');
			if ($anchor) {
			var offsetAmount = $('#' + $anchor).offset().top - 20;
			$('html, body').scrollTop(offsetAmount)
			};
			});*/
		},

		externalLink: function () {
			$('.external, .social_external').click(function () {
				var link = $(this).attr('href');
				window.open(link);
				return false
			});

		},

		addExternalIcon: function () {
			var $anchorLinks = $('.richTextFormat a[target=_blank]');
			if ($anchorLinks.length > 0) $anchorLinks.each(function () {
				if ($(this).children('span').size() == 0 && $(this).children('img').size() == 0) {
					$(this).addClass('external');
					var linkText = $(this).html();
					$(this).html('<span>' + linkText + '</span>');
				}
			});
		},

		zebraStripes: function () {
			$('table.calendar tbody tr:odd').addClass('row_odd');
		},

		tableFormat: function () {
			$('table.financial tr, .richTextFormat table tr').each(function () {
				$('td:last', this).addClass('np_right');
				$('th:last', this).addClass('np_right');
			});
		},

		smartSpacing: function () {
			$('.richTextFormat ul.list_links').prev('p').css("margin-bottom", "10px");
		},

		equalHeights: function () {
			/* Equal height text columns */
			function equalHeightText(group) {
				var isIE6 = ($.browser.msie && $.browser.version.substr(0, 1) < 7) ? true : false;
				group.each(function (i) {
					var tallest = 0;
					var $this = $(this, i);
					var $el = $this.find('.text_container').each(function (i) {
						var thisHeight = $(this, i).height();
						if (thisHeight > tallest) {
							tallest = thisHeight;
						}
					});
					$el.css(isIE6 ? "height" : "min-height", tallest);
				});
			}
			equalHeightText($("#carousel_news ul.list_promo_inline"));

			/* Equal height hero modules */
			function equalHeightHero(group) {
				var isIE6 = ($.browser.msie && $.browser.version.substr(0, 1) < 7) ? true : false;
				group.each(function (i) {
					var tallest = 0;
					var $this = $(this, i);
					var $el = $this.find('.shaded').each(function (i) {
						var thisHeight = $(this, i).height();
						if (thisHeight > tallest) {
							tallest = thisHeight;
						}
					});
					$el.find('.content_holder').css(isIE6 ? "height" : "min-height", tallest);
				});
			}
			equalHeightHero($("#hero_container"));
		},

		expandableContent: function () {
			$('.expandable_content_holder').css("display", "none");
			$('ul.list_faqs li > a').click(function () {
				$('.expandable_content_holder', $(this).parent()).slideToggle(300);
				$(this).toggleClass('current');
				return false;
			});
		},

		verticalCentre: function () {
			var $keyfacts = $('.key_fact_container');
			if ($keyfacts.length) {
				$($keyfacts).find(".investor_key_fact").each(function (i) {
					var $this = $(this, i),
						itemHeight = $this.find('.content_holder').height() / 2;
					$this.find('.content_holder').css({ "position": "absolute", "top": "50%", "margin-top": -itemHeight });
				})
			}
		},

		getQueryString: function (key) {
			/// <param name="key" type="String">Parameter in the querystring that you want the value of</param>
			/// <returns type="String">The value of the requested parameter</returns>
			key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
			var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
			var qs = regex.exec(window.location.href);
			if (!qs) return "";
			else return qs[1];
		}


	};

	$SAS.Dropdown = DropdownNav = {

		selector: "#nav_main",
		dropdown: ".dropdown_container",
		rolloverDelay: 250,

		launch: function () {
			var $dropdown = $(this.selector);
			if ($dropdown.length) $dropdown.each(DropdownNav.init);
			//if ($dropdown.length) $dropdown.each(DropdownNav.initQuick);
		},

		init: function (i) {
			var $this = $(this, i),
			isIE = $('html').hasClass(AppSettings.ieClass),
			rollOverTimer,
			rollOutTimer;

			var $target = $($this.children()).children().not(":only-child").parent();

			$target.addClass("dropdown");

			$target.hover(function (event) {
				var $this = $(this);

				if ($(DropdownNav.dropdown).is(':visible')) {
					DropdownNav.rolloverDelay = 0;
				} else {
					DropdownNav.rolloverDelay = 250;
				};

				clearTimeout(rollOverTimer);
				clearTimeout(rollOutTimer);

				rollOverTimer = setTimeout(function () {
					(isIE) ? $this.siblings().removeClass(Main._hoverClass).find(DropdownNav.dropdown).hide() : $this.siblings().removeClass(Main._hoverClass).find(DropdownNav.dropdown).css("opacity", 0).hide();
					if (isIE) {
						$this.parent().addClass("focus").end().addClass(Main._hoverClass).find(DropdownNav.dropdown).show();
					} else {
						($this.parent().hasClass("focus")) ? $this.addClass(Main._hoverClass).find(DropdownNav.dropdown).css("opacity", 1).show() : $this.parent().addClass("focus").end().addClass(Main._hoverClass).find(DropdownNav.dropdown).stop().fadeTo(200, 1);
					}
				}, DropdownNav.rolloverDelay);

			}, function (event) {
				var $this = $(this);

				rollOutTimer = setTimeout(function () {
					(isIE) ? $this.removeClass(Main._hoverClass).find(DropdownNav.dropdown).hide() : $this.removeClass(Main._hoverClass).find(DropdownNav.dropdown).stop().fadeTo(150, 0).hide();
					$this.parent().removeClass("focus");
				}, DropdownNav.rolloverDelay);

				clearTimeout(rollOverTimer);

			});
		},

		initQuick: function (i) {
			var $this = $(this, i),
				isIE = $('html').hasClass(AppSettings.ieClass),
				rollOverTimer,
				rollOutTimer;

			var $target = $($this.children()).children().not(":only-child").parent();

			$target.hover(function (event) {
				var $this = $(this);

				if ($(DropdownNav.dropdown).is(':visible')) {
					DropdownNav.rolloverDelay = 0;
				} else {
					DropdownNav.rolloverDelay = 250;
				};

				clearTimeout(rollOverTimer);
				clearTimeout(rollOutTimer);

				rollOverTimer = setTimeout(function () {
					$this.siblings().removeClass(Main._hoverClass).find(DropdownNav.dropdown).hide();
					$this.parent().addClass("focus").end().addClass(Main._hoverClass).find(DropdownNav.dropdown).show();
					Debug.log(DropdownNav.rolloverDelay);
				}, DropdownNav.rolloverDelay);

			}, function (event) {
				var $this = $(this);

				rollOutTimer = setTimeout(function () {
					$this.parent().removeClass("focus").end().removeClass(Main._hoverClass).find(DropdownNav.dropdown).hide();
				}, DropdownNav.rolloverDelay);

				clearTimeout(rollOverTimer);

			});
		}

	};

	/*author@j.lau 14.09.2011 - start
	**/
	$SAS.WordFilter = WordFilter = {

		init: function () {
			this.parseText(document.getElementById("site_container"), function (_txtnode) {
				var _txt = _txtnode.data;

				if (/\S/.test(_txt)) _txtnode.data = _txt.replace(/J Sainsbury/g, "J\u00A0Sainsbury");
				if (/\S/.test(_txt)) _txtnode.data = _txt.replace(/J Sainsbury plc/g, "J\u00A0Sainsbury\u00A0plc");
			});
		},

		parseText: function (node, func) {
			var arr = [], txt;

			if (node) {
				if (node.nodeName.toLowerCase() != "script" && node.nodeName.toLowerCase() != "style") {
					node = node.firstChild;

					while (node != null) {
						if (node.nodeType == 3) {
							if (typeof func == "function") {
								txt = func(node);
								if (txt != undefined) arr[arr.length] = txt;

							} else arr[arr.length] = node;

						} else arr = arr.concat(this.parseText(node, func));

						node = node.nextSibling;
					}
				};
			};

			return arr;
		}
	}
	/* end **/

	$SAS.Modal = Modal = {

		_governanceSelector: ".list_governance",

		launch: function () {
			var $governance = $(this._governanceSelector);
			if ($governance.length) $.each($governance, Modal.initModal);
		},

		initModal: function () {
			var isIE = $('html').hasClass(AppSettings.ieClass);
			var $item = $(this).find("li > a");
			var $modal = $(this).find(".governance_modal");
			var $close = $(this).find("a.modal_close");

			$item.click(function () {
				if (isIE) {
					$(this).parent("li").find($modal).show();
				} else {
					$(this).parent("li").find($modal).fadeIn(300);
				};
				$('html, body').stop().animate({
					scrollTop: $('#tabbed_section').offset().top
				}, 800, 'easeInOutQuad');
				return false;
			});
			$close.click(function () {
				if (isIE) {
					$modal.hide();
				} else {
					$modal.fadeOut(300);
				}
				return false;
			});
		}

	};

	$SAS.Forms = Forms = {

		_validateSelector: "form #contour.feedback, form #contour.sitecomments",
		_wordcountSelector: ".wordcount",
		_stylishSelectSelector: "select",
		_labelOverlaySelector: "#contour textarea, #contour input:text, .label_overlay textarea, .label_overlay input:text",
		_pageContainerFormSelector: "#page_container form",

		launch: function () {
			var $validate = $(this._validateSelector);
			// Don't need jquery validate on any forms now using Contour validation
			//if ($validate.length) $validate.each(Forms.initValidation);

			var $wordcount = $(this._wordcountSelector);
			if ($wordcount.length) $wordcount.each(Forms.initWordcount);

			var $stylish = $(this._stylishSelectSelector);
			$('#contour .feedback select option[value=""]').html('Select a topic');
			$('#contour .emailnewsservicesubscription select option[value=""]').html('Select a profession');
			if ($stylish.length && !AppSettings.isIE6) $stylish.each(Forms.initStylishSelect);

			var $field = $(this._labelOverlaySelector);
			if ($field.length) $field.each(Forms.labelOverlayInit);

			var $form = $(this._pageContainerFormSelector);
			if ($form.length) $form.each(Forms.initQuerystringCheck);

		},

		initStylishSelect: function (i) {
			var $this = $(this, i);
			$this.sSelect();
			if ($this.hasClass("nm_right")) $this.next("div").addClass("nm_right");
		},


		initWordcount: function () {
			var $this = $(this),
				$field = $this.prev("textarea, input:text")
				.data({ "_limit": parseInt($this.html().match(/\d+/), 10), "_label": $this.html(), "_target": $this });

			$field.bind('keypress keyup blur', Forms.updateCountHandler);
		},

		updateCountHandler: function (event) {
			var $this = $(this);
			var $target = $this.data("_target"),
				limit = $this.data("_limit"),
				txt = this.value,
				counter = limit - txt.length,
				str = (txt.length == limit - 1) ? " character remaining" : " characters remaining";

			if (!txt.length && event.type == "blur") $target.html($this.data("_label"));
			else if (txt.length > limit)/*$this.val($this.val().slice(0, limit));*/ this.value = this.value.substring(0, limit);
			else $target.html(counter + str);

			$target[txt.length >= limit ? "addClass" : "removeClass"]("limit");
		},

		labelOverlayInit: function (i) {
			var $label = $(this, i).closest("form").find('label[for="' + this.id + '"]')[this.value.length ? "hide" : "show"]();
			var isIE = $('html').hasClass(AppSettings.ieClass);

			if (isIE) {
				this.onfocus = function () { $label.hide(); };
				this.onblur = function () { if (this.value == "") $label.show(); };
			} else {
				this.onfocus = function () { $label.fadeOut(50); };
				this.onblur = function () { if (this.value == "") $label.fadeIn(50); };
			}
		},

		initValidation: function (i) {
			var $form = $(this, i);
			//var $field = $form.find(".required");
			//console.log($field)

			if ($("#field_feedback").length) var limit = parseInt($("#field_feedback").siblings(".wordcount").html().match(/\d+/), 10);

			$form.validate({
				//debug: true,  //DEVNOTE : dev purposes only *remove for LIVE
				rules: {
					field_feedback: {
						required: true,
						maxlength: limit
					}
				}
			})
		},

		initQuerystringCheck: function () {
			if (window.location.search != '') {
				window.location.hash = $('#page_container form').attr("id");
			}
		}
	};

	$SAS.SocialNetworks = SocialNetworks = {

		_twitterSelector: ".twit",
		_fbSelector: ".fb",

		launch: function () {
			var $twit = $(this._twitterSelector);
			var $fb = $(this._fbSelector);
			if ($twit.length) $.each($twit, SocialNetworks.initTwitter);
			if ($fb.length) $.each($fb, SocialNetworks.initFacebook);
		},

		initTwitter: function (i, el) {
			var $target = $(el).find('.content_holder'),
				account = $target.find('h3 a').text();

			if ($('#page_container').hasClass('home')) {
				$target.tweet({
					username: account.slice(1),
					count: 2,
					tweet_class: "list_tweet"
				});
			} else if ($(el).hasClass('plum')) {
				$target.tweet({
					username: account.slice(1),
					count: 3,
					tweet_class: "list_tweet"
				});
			} else {
				$target.tweet({
					username: account.slice(1),
					count: 2,
					tweet_class: "list_tweet"
				});
			};
		},

		initFacebook: function () {

		}
	};

	$SAS.Interactions = Interactions = {

		valuesWheel: function () {
			var focusAreasChart = $("#five_areas_chart");
			if (focusAreasChart.length > 0) {
				$(focusAreasChart).find("img").css({ opacity: 0 });
				$('#five_areas_chart map area').hover(function () {
					// Area rollover
					var focus_id = $(this).attr('alt');
					var focus_rollover = $("#" + focus_id);
					$(focus_rollover).stop().animate({ opacity: 1 }, 150);
				}, function () {
					// Remove area rollover
					var focus_id = $(this).attr('alt');
					var focus_rollover = $("#" + focus_id);
					$(focus_rollover).stop().animate({ opacity: 0 }, 250);
				});
			}
		}

	};

	$SAS.Aux = Aux = {

		_printSelector: ".print_article",
		_newWinSelector: ".new_window",

		launch: function () {
			var $print = $(this._printSelector);
			if ($print.length) $print.each(this.initPrint);

			var $win = $(this._newWinSelector);
			if ($win.length) $win.each(this.openNewWindow);
		},

		initPrint: function (i) {
			$(this, i).click(function () { window.print(); return false; });
		},

		openNewWindow: function (i) {
			var $this = $(this, i);

			if (window.open) {
				$this.click(function () {
					window.open(this.href, '', "width=760, height=650, status=1, toolbar=1, location=1, menubar=1, directories=1");
					return false;
				});
			};
		}
	};

	//Wrapper so IE doesn't break
	var Debug = {

		log: function (str) {
			if (AppSettings.DEBUGMODE) {
				try { console.log(str); }
				catch (e) { }
			}
		}

	};

	Main.run(); //invoke app
});
