



(function(){
	// Add format plugin.
    jQuery.format = function(source, params) {
        jQuery.each(arguments, function(i, n) {
            source = source.replace(new RegExp("\\{" + (i-1) + "\\}", "g"), n);
        });
        return source;
    };
    
    var sky = window.sky || ( window.sky = {} );

    /* --- START: Shared JS -------------------------------------------------- */
    sky.shared = {
        // Open new window with configurable options
        openNewWindow : function(url, height, width, status, toolbar, menubar, resizable, scrollbars) {
            for(var i=0; i<arguments.length; i++){
                // convert boolean values into yes/no equivalent
                if( typeof(arguments[i]) == 'boolean' ){
                    (arguments[i] == true) ? arguments[i] = 'yes' : arguments[i] = 'no';
                }
            }
            
    		var options = "height=" + height + ", width=" + width +", status=" + status + ", toolbar=" + toolbar + ", menubar=" + menubar + ", resizable=" + resizable + ", scrollbars=" + scrollbars + ", location=no";
    		window.open(url, null, options);
    		return false;
        },

        // Disable image flickering in IE6
        disableBackgroundImageFlickeringForIE6 : function(){
            if( jQuery.browser.msie && parseInt( jQuery.browser.version, 10 ) == 6 ) {
                try {
                    document.execCommand( "BackgroundImageCache", false, true ) ;
                } catch ( exception ){ }
            }
        },

        // Button rollover for IE6 (CSS hover on <form/> doesn't work)
        buttonMouseoverForIE6 : function(){
            if( jQuery.browser.msie && parseInt( jQuery.browser.version, 10 ) == 6 ) {
                $('.button form span, .button form button').hover(
                	function(){ $(this).addClass('hover');},
                	function(){ $(this).removeClass('hover');}
                );
            }
        },

        helpPanel : function(){
        	$( "#helpPod #expandhelp a").unbind('click').click( function() {
        		$help = $('#helpPod');
        		if($help.hasClass('on')){
        			$help.removeClass('on').addClass('off');
        		} else{
        			$help.removeClass('off').addClass('on');
        		}
        		return false;
        	});
        },

		myPortfolioPanel : function(){
      		$( "#portfolioPod #expandportfolio a, #portfolioPod #portfolioCallToAction a").unbind('click').click( function(){
      			$portfolio = $('#portfolioPod');
      			if($portfolio.hasClass('on')){
      				$portfolio.removeClass('on').addClass('off');
      			} else{
      				$portfolio.removeClass('off').addClass('on');
      			}
      			return false;
      		});
		},
		
        roiHelpPanel : function(){
			$(".roiInfo .roiExpandhelp a").unbind('click').click( function() {  
				$help = $(this).closest("div.roiInfo");
				if($help.hasClass('on')){
					$help.removeClass('on').addClass('off');
				} else{
					$help.removeClass('off').addClass('on');
				}
				return false;
			});
		},

        Tools : {
            configuredSizes: {
                textSizeSmall:'100%', 
                textSizeMedium:'110%', 
                textSizeLarge:'120%'
            },
            init : function() {

            	$('div#textAndPrint').html('<ol id="textSize"><li class="last"><span class="intro">Text size</span><span id="textSizeSmall">A</span><span id="textSizeMedium">A</span><span id="textSizeLarge">A</span></li></ol>');                
                $('#textSizeSmall, #textSizeMedium, #textSizeLarge').unbind('click').click(function() {
                    sky.shared.Tools.resize(this.id);
                });
                
                $('ol#textSize').after('<ol id="printPage"><li class="last"><span class="printPage"><a href="#">Print page</a></span></li></ol>');
                $('#printPage').click(function() {
                    window.print();
                });
                
                // Resize body font if set previously and underline selected link - default to textSizeSmall
                var fontSize = $.cookie('skyOCPFontSize');
                
                if(fontSize && fontSize.length > 0){
                    sky.shared.Tools.resize(fontSize);
                } else {
                    $('#textSizeSmall').addClass('on'); // Default
                }
            },

            resize : function(fontSize) {
                // Change CSS font-size on body element.
                $('body').css('font-size', this.configuredSizes[fontSize]);

                // Store font-size in cookie so text size persists across pages and sites
                $.cookie( 'skyOCPFontSize', fontSize, { 'path' : '/' + sky.shared.site } );

                // Make the primary nav options equal height.
                var maxAnchorHeight = 0;
                $('#primaryLinksOL > li[id!="secondaryLinksLI"] > a').height('auto').each( function(){
                	maxAnchorHeight = Math.max(maxAnchorHeight, $(this).height());
                }).height(maxAnchorHeight);
                
                $('#textSizeSmall, #textSizeMedium, #textSizeLarge').removeClass('on');
                $('#' + fontSize).addClass('on');
            }
        },
        openJDialog : function(html, url) {
        	var temp = $('<div/>');
        	var props = { progress: false, bg: '#000', opacity: '0.8', showImmediately:true, closeDialogOnEscKey:false };
        	
        	// Pass html content to the dialog
        	if(html){
        		props.content = html;
        	} else {// Pass url to jDialog to make ajax request
        		props.addr = url;
        	}
        	temp.createDialog(props);
        	temp.trigger('click');
        }
    };
    
    /* --- START: Storefront JS ---------------------------------------------- */
    sky.storefront = {
		Utilities : {
			deSerializeString : function(string) {
				var params = string;
				if (string.match(/\?(.+)$/)) {
					// in case it is a full query string with ?, only take everything after the ?
					params = RegExp.$1;
				}
				// split the params
				var pArray = params.split("&");
				// hash to store result
				var pHash = {};
				// parse each param in the array and put it in the hash
				for(var i=0; i<pArray.length; i++) {
					var temp = pArray[i].split("="); 
					pHash[temp[0]] = unescape(temp[1]);
				}
				return pHash;
			},

			convertHtmlForJQuery : function(htmlString) {
				var string = htmlString.replace(/<head(.|\s)*?\/head>/gi, "");
				string = string.replace(/<head(.|\s)*?\/head>/gi, "");
				string = string.replace(/<noscript(.|\s)*?\/noscript>/gi, "");
				string = string.replace(/<script(.|\s)*?\/script>/gi, "");
				string = string.replace(/<iframe(.|\s)*?\/iframe>/gi, "");
				return $('<div />').append(string);
			},

			callJQueryPost : function(url, data, successHandler) {
				$.ajax({ type: 'POST', dataType: 'html', cache: false, url: url, data: data,
					error: sky.storefront.Utilities.ajaxError,
					complete: successHandler
				});
			},

			callJQueryGet : function(url, successHandler) {
				$.ajax({ type: 'GET', dataType: 'html', cache: false, url: url, 
					error: sky.storefront.Utilities.ajaxError, 
					complete: successHandler
				});
			},

			ajaxError : function() {

			},

			stopAjaxInProgress : function() {
				sky.storefront.Basket.ajaxInProgress = false;
			},
			
			/** Adds a CSS spec that will be applied on hover
				spec has 2 attributes
					selector : a jQuery selector for finding the element(s) to add the effect to
					css : an object of css attribute name/value pairs. background-image should just be the url, and this will preloaded and PNG fixed for IE6
					
				The supplied CSS spec will be applied to the matched element(s) on mouseenter
				The static value is stored so that it can be restored on mouseleave.
				
				Usual jQuery getter/setter rules apply in the case of the selector matching more than one element.
			  */
			addHoverEffect : function(spec) {
				var staticSpec = {}
				,	hoverSpec = spec.css
				,	$element = $(spec.selector)
				,	preload
				,	cssAttribute;
			
				// if the spec has a background image
				if(hoverSpec['background-image']) {
					// preload it
					preload = new Image();
					preload.src = hoverSpec['background-image'];
					
					// transform the attributes for the CSS the browser will require
					if(sky.storefront.Utilities.isIe6) {
						hoverSpec['filter'] = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=crop, src='" + hoverSpec['background-image'] + "');";
						hoverSpec['background-image'] = "none";
					}
					else {
						hoverSpec['background-image'] = "url('" + hoverSpec['background-image'] + "')";
					}
				}
				
				// grab existing CSS, to reapply it on mouse leave
				for(cssAttribute in hoverSpec) {
					staticSpec[cssAttribute] = $element.css(cssAttribute);
				}
				
				// add the effect handler
				$element.hover(function() {
						$(this).css(hoverSpec);
					}
					,	function() {
						$(this).css(staticSpec);
					});
			},
			
			// simple decoder for unapplying XML encoding, eg will turn "&lt;p&gt;Hello &amp; welcome!&lt;/p&gt;" into "<p>Hello & welcome!</p>"
			decodeHTML : function (encoded) {
				return $("<div/>").html(encoded).text();				
			},
			
			/* Helper for swfObject
			 * config parameter is an object literal with the following properties.
			 * With the exception of columnWidth, these all match the API docs for swfObject at http://code.google.com/p/swfobject/wiki/api
			 *
			 * Ideally exactly one of width or columnWidth should be suppliled
			 * If both width and columnWidth are supplied, width takes precedence
			 * If neither width nor columnWidth are supplied, the script will attempt to measure the width of an appropriate element
			 * 		first it tries find an element whose id is the config.id and measure its li.col ancestor
			 * 		next it tries to find an li.col ancestor of the last script on the page. (This is assumed to be the script that sourced the call to embedFlash)
			 * 		finally it will measure the mainContent div
			 * 
			 * id (mandatory) - String; id of the element where the SWF will be placed
			 * swfUrl (mandatory) - String; URL of the SWF to load
			 * height (mandatory) - int; pixel height of the SWF
			 * width (optional - see above) - int; pixel width of the SWF
			 * columnWidth (optional - see above) - String; Pod column width class, eg "colx3", from which the SWF pixel width is derived
			 * flashVersion (optional) - String; defaults to "9.0.115.0"; minimum Flash player version
			 * flashVars (optional) - Object; defaults to empty object; flashVars to pass in name:value pairs
			 * params (optional) - Object; defaults to empty object; params to pass to the object element in name:value pairs
			 * attributes (optional) - Object; defaults to empty object; attributes to pass to the object element in name:value pairs
			 * callback (optional) - function; will be called on swfObject completion with an object parameter, the key property of which is a "success" boolean
			 */
			embedFlash : function (config) {
				var colWidths = {
						"colx0-5" : 168, "colx0-75" : 168,
						"colx1"   : 230, "colx1-33" : 312, "colx1-5" : 354,
						"colx2"   : 478, "colx2-25" : 540, "colx2-5" : 540, "colx2-66" : 643,
						"colx3"   : 726, "colx3-5"  : 911,
						"colx4"   : 974
					}
				,	swfObjectParams, flashVars, width, height;
				
				if(window.swfobject && swfobject.embedSWF) {
					width = config.width || colWidths[config.columnWidth] || $('#'+config.id).closest('li.col').width() || $('script').last().closest('li.col').width() || $('div.mainContent').width();
					height = config.height;
					
					flashVars = config.flashvars || {};
					flashVars.width = width;
					flashVars.height = height;
					
					swfObjectParams = [
						config.swfUrl
					,	config.id
					,	width
					,	height
					,	config.flashVersion || "9.0.115.0"
					,	false // expressInstallSwfurl 
					,	flashVars
					,	config.params || {}
					,	config.attributes || {}
					];
					
					if ((typeof config.callback) == 'function') {
						swfObjectParams[9] = config.callback;
					}
					
					swfobject.embedSWF.apply(this, swfObjectParams);
				}
				else if ((typeof config.callback) == 'function') {
					config.callback({success: false});
				}
			},
			
			isIe6 : ( $.browser.msie && parseInt( $.browser.version, 10 ) == 6 )
		},

		Authentication : {
			// We need to check whether a previous signin action was initiated but stopped by user clicking close button
			bindSignInAction : function(){
				//skyidSigninLink2 used so as to stop the SkyID events breaking our flow
				$('.signIn').click(sky.storefront.Authentication.openSkyId);
				$('a[href="?signin=true"]').click(sky.storefront.Authentication.openSkyId);
			},

			openSkyId : function(){
				if(sky.storefront.Authentication.skyIdInProgress){
					sky.storefront.Authentication.resetSkyIdIframe();
				}
				SkyId.Lightbox.Signin.open();
				sky.storefront.Authentication.skyIdInProgress = true;
				return false;
			},

			deepLinkPopUpSignInView : function() {
				if( ($.cookie('skySSO') == null) && (window.location.search.indexOf('showSignIn') != -1) && (window.location.pathname.substr(0,8) != '/ireland')){
					var maxAttempts = 50;
					var numberOfAttempts = 0;
					var waitForSkyIDJS = setInterval(
					function(){
						numberOfAttempts++;
						var iframe = document.getElementById('lightboxContentIframe');
							if (iframe){
								sky.storefront.Authentication.openSkyId();
								clearInterval(waitForSkyIDJS);
							} else if(numberOfAttempts >= maxAttempts){
								clearInterval(waitForSkyIDJS);
							}
					},50);
				}
			},

			// Bind the opening of the SIGNOUT dialog to specified links
			bindSignOutAction : function(){
				$('#skyBasketSignOutLink, #skyidSignoutLink').click(function(){
					jQuery.ajax({
						url: this.href + '&ajaxCall=true',
						complete:function(res, status){
							if( res.getResponseHeader('AJAX-INSTRUCTION') == 'LIGHT-BOX' ){
								sky.storefront.showUserADialog(res);
								redirectUrl = document.location.href.split('?');
								$('#signOutOverlayPod input[name="redir"]').attr('value', redirectUrl[0]);
								$('#signoutNoButton').click(function(){
									$.closeDialog();
									return false;
								});
							} else {
								sky.storefront.refreshPage();
							}
						}
					});
					return false;
				});
			},

			// Bind the clear basket dialog to the signin link if previously identified as Prospective Customer
			bindClearBasketDialog : function() {
				$('.signIn').unbind('click').click(function() {
					jQuery.ajax({
						url: this.href + '&ajaxCall=true',
						complete:function(res, status){
							sky.storefront.showUserADialog(res);
							// OK button
							$('#clearBasketWarningOK').click(function(){
								sky.storefront.Authentication.bindClearBasketAction( $(this) );
								return false;
							});
							// Cancel button
							$('#clearBasketWarningCancel').click(function(){
								$.closeDialog();
								return false;
							});
						}
					});
					return false;
				});
			},
			
			bindBasketInvalidDialog : function() {
				$('#basketInvalidCustomerInfo').unbind('click').click(function() {
					jQuery.ajax({
						url: this.href + '&ajaxCall=true',
						complete:function(res, status){
							sky.storefront.showUserADialog(res);
						}
					});
					return false;
				});
			},
			
			// Bind the clear basket action to the dialog button which does an Ajax post on the form and then opens OBU signin dialog
			bindClearBasketAction : function(button){
				var form = button.parent();
				if( form && form.is('form') ){
					var data = $(form).serialize();
					sky.storefront.Utilities.callJQueryPost( document.location.href + '?ajaxCall=true', data, function(res, status) {
						$.closeDialog();
						SkyId.Lightbox.Signin.open();
					});
				}
			},

			// Bind Omniture signin action passing in 'skyBasketSigninLink' or 'skyidSigninLink2'
			bindOmnitureSigninAction : function(id){
				$('#' + id).click(function(){
					sky.storefront.siteCatalystSignin();
				});
			},

			// Update the vertical/horzontal signin views depending on user SSO cookie being set
			updateSignInView : function(){
				if($('#basketContainer')[0]){
					sky.storefront.Authentication.bindSignOutAction();
					sky.storefront.Authentication.bindOmnitureSigninAction('skyBasketSigninLink');
					// Bind the clear basket dialog to the signin link if previously identified as Prospective Customer 
					// and the basket is not empty 
					var basketIsEmpty = sky.storefront.Basket.checkIfBasketIsEmpty();
					if( ($.cookie('custype') == 'PC') && (!basketIsEmpty) ){
						sky.storefront.Authentication.bindClearBasketDialog();
					} else {
						$('.signIn').click(function(){
							SkyId.Lightbox.Signin.open();
							return false;
						});
					}
				} else {
					sky.storefront.Authentication.bindSignOutAction();
					sky.storefront.Authentication.bindOmnitureSigninAction('skyidSigninLink2');

					// For pages without basket we use #basketPopulated to indicate if items are in the basket
					if($('#basketPopulated')[0]){

						sky.storefront.Authentication.bindClearBasketDialog();
					}
				}
			},

			checkIfSkyIdIframeIsPresent : function(maxAttempts, isPresentHandler, notPresentHandler){
				var numberOfAttempts = 0;
				var iframe = document.getElementById('lightboxContentIframe');
				var waitForSkyIdIframe = setInterval(
					function(){
						numberOfAttempts++;
						if(iframe){
							clearInterval(waitForSkyIdIframe);
							isPresentHandler();
						} else if(numberOfAttempts >= maxAttempts){
							clearInterval(waitForSkyIdIframe);
							if(notPresentHandler){
								notPresentHandler();
							}
						}
					}, 50
				);
			},

			// Call this when user successfully logs in through OBU
			// Either refresh the page with new prices or divert to lightbox
			postSkyIdSuccess : function(){
				var url = '';
				var isAddToBasketRequest = false;
				if(sky.storefront.Basket.refferalUrl){
					url = sky.storefront.Basket.refferalUrl + '&returnToAuthFilter=true&refererIs=skyid';
					// For non-basket pages, change the URl so it returns the full page HTML
					var urlArray = url.split('?');
					url =  document.location.href + '?' + urlArray[1];
					isAddToBasketRequest = true;
				} else {
					// Make sure url doesnt contain any params
					url = document.location.href;
					var safeUrl = url.split("?");
					url = safeUrl[0] + '?ajaxCall=true&returnToAuthFilter=true&refererIs=skyid&site=' + sky.shared.site;
				}

				// Show loading message
				var html = $('#skyIDWaitContent').html();
				$('#skyIDWaitOverlayPod',html).addClass('overlayPod');
				sky.shared.openJDialog(html);
				sky.storefront.Utilities.callJQueryGet(url, function(res, status){
					var jQueryHtml = sky.storefront.Utilities.convertHtmlForJQuery(res.responseText);
					if( res.getResponseHeader('AJAX-INSTRUCTION') == 'LIGHT-BOX' ){
						sky.storefront.showUserADialog(res);
					} else if (res.getResponseHeader('Location') != null && res.getResponseHeader('Location') != '') {
						window.location.href = res.getResponseHeader('Location');
					} else if( jQueryHtml.find('#invalidCustomerNonLightbox')[0] ){
						/*
						Use this instead of case above and remove var jQueryHtml above
						else if( res.getResponseHeader('AJAX-INSTRUCTION') == 'STATIC-ERROR-PAGE' ){}
						*/
						sky.storefront.showInvalidCustomerNonLightbox(jQueryHtml);
					} else {
						// Need to see if there is a deeplink to an external site and then forward to it
						var data = sky.storefront.Utilities.deSerializeString(url);
						var requestURL = null;
						if(data.hasDeeplinkTarget == 'true'){
							requestURL = document.location.href = data.requestURL + '?isInternalLink=' + data.isInternalLink + '&hasDeeplinkTarget=' + data.hasDeeplinkTarget + '&redirectTeaser=' + data.redirectTeaser + '&requestURL=' + data.requestURL;
						}
						sky.storefront.refreshPageBodyWithAjax(res.responseText, requestURL);
					}
				});
				if (sky.ocp) {
					sky.ocp.LivePerson.determineLivePersonCustomerType();
				}
				
				//sky.storefront.Authentication.resetSkyIdIframe();
			},

			// Call this when error is thrown after user attempts to login through OBU
			postSkyIdError : function(url){
				sky.shared.openJDialog(null, url);
				sky.storefront.Authentication.resetSkyIdIframe();
			},

			resetSkyIdIframe : function(){
				//relaod frame content - this is so that it does not end up with a blank lightbox in case of secondary/primary login
				$('#lightboxContentIframe').attr('src', $('#lightboxContentIframe').attr('src'));
			}
		},
		
		TermsAndConditions : (function () {
			var sections = []
			,	$printFrame;
			
			return {
				add : function(config) {
					sections[sections.length] = config.id;
				},
				enable : function (config) {
					$.each(sections, function (i, section) {
						sky.storefront.ExpandCollapsePod.enable({
							prefix : '#termsList_',
							show : config.show,
							hide : config.hide,
							id : section
						});
					});
					
					if(window.opera == undefined) {
						$('#termsPrintLink a').unbind('click').click(function () {
							if($printFrame && $printFrame.remove) {
								$printFrame.remove();
							}
							$printFrame = $('<iframe />').attr('src', $(this).attr('href')).addClass("printIframe").appendTo('#termsPrintLink');
							return false;
						});
					}
				}
			}
		})(),

		CugOffers : (function() {
			return {
				enable : function(config) {
					var config = config || {};
					config.prefix = "#cugOffers_";
					config.hide = config.hide || "close the details";
					config.show = config.show || "open the details";
					config.controlParent = "div.control";

					if (sky.storefront.Basket) {
						sky.storefront.Basket.shouldRefreshWholePage=true;
					}

					sky.storefront.ExpandCollapsePod.enable(config);

					$("#cugOffers_" + config.id + " a.cugButton").click(function () {
						var href = $(this).attr("href")
						,	bits = href.replace(/^.+addToBasket=(.+)&campaignSource=(.+)&level2Offer=(.+)&mailshotDescription=.+$/,"$1|$2|$3").split("|")
						,	products = bits[0].split(":")[0].split(',')
						,	campaignSource = bits[1]
						,	interestSource = bits[2];

						//allow for 'tailored' offers
						if (campaignSource == undefined) {
							campaignSource = config.id;
						}
						if (interestSource == undefined) {
							interestSource = 'ESALES';
						}
						
						sky.storefront.siteCatalystAddRewardsAndOffersToBasket(products,interestSource,campaignSource, config);
						
					});
				}
			}
		})(),
		
		ExpandCollapsePod : (function () {
			// stores the configs for the enabled expand collapse pods
			var _pods = []
			,	_groups = {};
			
			function _expand(control, podNode, text) {
				control.removeClass('expandarrowdown').addClass('expandarrowup').html(text);
				podNode.addClass('open');
			}
			
			function _collapse(control, podNode, text) {
				control.removeClass('expandarrowup').addClass('expandarrowdown').html(text);
				podNode.removeClass('open');
			}
			
			function _toggleExpandCollapse(control, podNode, hideText, showText) {
				if(control.hasClass('expandarrowdown')) {
					_expand(control, podNode, hideText);
				}
				else {
					_collapse(control, podNode, showText);
				}
			}
			
			function _toggleExpandCollapseAll(group) {
				if(group.control.hasClass('expandarrowdown')) {
					$.each(group.expandHandlers, function (i, handler) {
						handler();
					});
				}
				else {
					$.each(group.collapseHandlers, function (i, handler) {
						handler();
					});
				}
				
				_determineExpandAllControlState(group);
			}
			
			function _determineExpandAllControlState(group) {
				if($(group.fullOpenControlSelector).length == 0) {
					group.control.removeClass('expandarrowdown').addClass('expandarrowup').html(group.hideText);
				}
				else {
					group.control.removeClass('expandarrowup').addClass('expandarrowdown').html(group.showText);
				}
			}
			
			function _addControl($controlParent, hideText, showText, startsExpanded) {
				var	$hideControl = $('<span class="expandarrowup"></span>').html(hideText)
				,	$showControl = $('<span class="expandarrowdown"></span>').html(showText)
				,	hideWidth = $hideControl.appendTo($controlParent).width()
				,	showWidth = $showControl.appendTo($controlParent).width()
				,	controlWidth = Math.max(hideWidth, showWidth)
				
				// set the widths
				$hideControl.width(controlWidth);
				$showControl.width(controlWidth);

				// remove the one we don't need
				if(startsExpanded) {
					$showControl.remove();					
				} else {
					$hideControl.remove();
				}
				
				return $controlParent.find('span');
			}
			
			return {
				/*
				 config : js object with the one or more of the following properties
					id (mandatory) : the id of the pod - used to find inbound links and derive the selector for the parent element
					prefix (optional, default '#expandPod_') : the selector prefix to add to id to find the parent element
					hide (optional, default 'Hide') : the text for the "hide" control, may contain HTML which will be single decoded
					show (optional, default 'Show') : the text for the "show" control, may contain HTML which will be single decoded
					controlParent (optional, default '>h3') : the subselector for finding the element into which to add the controls
				*/
				enable : function (config) {
					_pods[_pods.length] = config;
				},
				
				/*
				 config : js object with the one or more of the following properties
					id (mandatory) : the id of the group - used to find inbound links and derive the selector for the parent element
					hide (optional, default 'Hide') : the text for the "hide" control, may contain HTML which will be single decoded
					show (optional, default 'Show') : the text for the "show" control, may contain HTML which will be single decoded
				*/
				enableGroup : function (config) {
					document.write('<div class="expandAllControl" id="expandAllControl_' + config.id + '"></div>');
					config.expandHandlers = [];
					config.collapseHandlers = [];
					config.openControlSelectors = [];
					config.startsAllExpanded = true; // this gets set to false as soon as a closed one is found
					_groups[config.id] = config;
				},
				
				initialise : function () {
					$.each(_pods, function(i, config) {
						var podid = config.id
						,	podSelector = (config.prefix || '#expandPod_') + podid
						,	hideText = sky.storefront.Utilities.decodeHTML(config.hide || "Hide")
						,	showText = sky.storefront.Utilities.decodeHTML(config.show || "Show")
						,	controlParentSelector = config.controlParent || '>h3'
						,	$podNode = $(podSelector)
						,	isDeepLink = (location.hash == '#' + podid)
						,	$controlParent = $podNode.find(controlParentSelector)
						,	startsExpanded = (($podNode.hasClass('open') || isDeepLink)?true:false)
						,	$control = _addControl($controlParent, hideText, showText, startsExpanded)
						,	$inboundLinks = $("a[href='#" + podid + "']").unbind('click') // need to unbind click to get rid of tracking delay
						,	group;
						
						$control.click(function(){
							_toggleExpandCollapse($control, $podNode, hideText, showText);
						});
						
						$inboundLinks.click(function(){ 
							_expand($control, $podNode, hideText);
							$podNode[0].scrollIntoView();
							return false;
						});
						
						/* Handle deep links
						   If the unexpanded content causes the anchor to scroll the page to the bottom,
						   FF will keep it scrolled to the bottom when the pod is expanded. So we need to
						   re-scroll */
						if (isDeepLink) {
							$podNode.addClass('open');
							$podNode[0].scrollIntoView();
						}
						
						if (config.group) {
							group = _groups[config.group];
							
							group.openControlSelectors[group.openControlSelectors.length] = podSelector + " span.expandarrowdown";
							
							group.expandHandlers[group.expandHandlers.length] = function () {
								_expand($control, $podNode, hideText);
							};
							
							group.collapseHandlers[group.collapseHandlers.length] = function () {
								_collapse($control, $podNode, showText);
							};
							
							if(!startsExpanded) {
								group.startsAllExpanded = false;
							}
							
							$control.click(function(){
								_determineExpandAllControlState(group);
							});
							
							$inboundLinks.click(function(){
								_determineExpandAllControlState(group);
							});
						}
					});
					
					$.each(_groups, function(i, group) {
						var	$controlParent = $("#expandAllControl_" + group.id);
						
						group.hideText = sky.storefront.Utilities.decodeHTML(group.hide || "Hide all");
						group.showText = sky.storefront.Utilities.decodeHTML(group.show || "Show all");
						
						group.fullOpenControlSelector = group.openControlSelectors.join(", ");
						
						group.control = _addControl($controlParent, group.hideText, group.showText, group.startsAllExpanded);
						
						group.control.click(function(){
							_toggleExpandCollapseAll(group);
						});
					});
				}
			}
		})(),
		
		DropdownSelectorPod : (function () {
			// flag that gets set to true by the markup in the pod
			var _podsExist = false;
			
			return {
				// called by the markup in the pod to set the flag to true
				enable : function () {
					_podsExist = true;
				},
				
				// called by the ready function to initialise any dropdown pods
				initialise : function () {
					if(_podsExist) { // only if there are any
						$('.dropdownpod').each(function (i, pod) {
							var choices = []	// store the found choices in the closure
							,	options = []
							,	$pod = $(pod)
							,	selectLabel;
							
							// build the HTML for the select box
							$pod.find('div.dropdownoption').each(function(j, entry){
									var $entry = $(entry)
									,	label = $entry.find('h3.title span').text(); // the entry for the dropdown
									
									// if not previously set, derive the label for the dropdown as the bit of the h3 before the entry above
									selectLabel = selectLabel || (function(){
										var h = $entry.find('h3.title').text();
										return h.substring(0, h.indexOf(label));
									})();
									
									// store the content element against the index
									choices[j] = $entry;
									
									// add an option to the drop down mapping the index to the label
									options[j] = ['<option value="', j, '">', label, '</option>'].join('');
								});
							
							// add the HTML controls to the page
							$pod.find('div.intro').prepend([
									'<p class="selection"><label for="dropdownpod', i, '">', selectLabel, '</label>',
									'<select id="dropdownpod', i, '">', options.join(''), '</select></p>'
								].join(''));
							
							// set the newly added select's onchange to swap the content
							$pod.find('div.intro select').change(function(event) {
									// get the index selected
									var choice = $pod.find('div.intro select option:selected').val();
									
									// hide all content
									$pod.find('div.dropdownoption').hide();
									
									// re-show the one that corresponds to the selected index
									$(choices[choice]).show();
								});
						});
					}
				}
			}
		})(),

		infoPopUpPod : (function () {
			// privates
			var _podsExist = false
			,	_popups = {};
			
			function _closePopup() {
				var $minipopup = $('#minipopup');
				
				// fade it all out then remove it from the DOM
				$minipopup.fadeOut(200, function(){
					$('body').removeClass("ie6Overlay");
					$minipopup.remove();
				});
			}
			
			function _makePopup(content, link) {
				var html = '<div id="minipopup"><div id="minipopupmask"></div><div id="minipopupcontent"><div id="minipopupclosebutton">close</div>' + content + '</div></div>'
				,	$body = $('body')
				,	$link = $(link)
				,	popupPosition = $link.offset();
				// so that hitting enter doesn't keep opening clones
				link.blur();
				
				// put it in the DOM first, so we can measure its height
				$body.addClass("ie6Overlay");
				$body.append(html);
				
				// choose the left position
				if (popupPosition.left > 490) {
					// 10px to the left of the link, if there's room
					popupPosition.left = popupPosition.left + $link.outerWidth() - 505;
				}
				else {
					// 10px to the right of the link
					popupPosition.left = popupPosition.left + $link.outerWidth();
				}
				
				// reference the newly created popup
				var $popupcontent = $('#minipopupcontent')
				
				// assess the vertical space around it
				,	popupHeight = $popupcontent.height()
				,	docEl = document.documentElement
				,	viewportBottom = docEl.clientHeight + docEl.scrollTop
				,	popupBottom = popupHeight + popupPosition.top
				,	enoughRoomBelowLink = (viewportBottom > popupBottom)
				,	enoughRoomAboveLink = (popupPosition.top > popupHeight);
				
				// choose the top position
				if (!enoughRoomBelowLink && enoughRoomAboveLink) {
					popupPosition.top -= (popupHeight - $link.outerHeight());
				}
				else {
					// 10px up from the link
					popupPosition.top -= 10;
				}
				
				// position the content fade and it in
				$popupcontent
					.css(popupPosition)
					.hide().fadeIn(150);
				
				// size the mask (needed in IE) and fade it nearly in
				$('#minipopupmask')
					.height($body.height()).width($body.width())
					.hide().fadeTo(150, 0.4);
				
				// close on clicking the close button or mask
				$('#minipopupmask, #minipopupclosebutton').click(_closePopup);
				
				// close on pressing Esc
				$(document).keyup(function(event) {
					if(event.which === 27) {
						_closePopup();
					}
				});
			}
			
			return {
				enable : function () {
					_podsExist = true;
				},
				
				initialise : function () {
					if (_podsExist) { // only if they're there
						$('div.popupPod').each(function(i, pod) {
							var $pod = $(pod)
							,	anchorName = "#" + $pod.find("h2 a.anchor").attr('name')
							,	$inboundLinks = $("a[href='" + anchorName + "']")
							,	$holder;
							
							if($inboundLinks.length > 0) { // there are links for this pod
								$holder = $pod.find("div.contentHolder");
								
								// clean and store the HTML
								$holder.find('h2 a.anchor').remove();
								_popups[anchorName] = $holder.html();
								
								// take the row from the DOM
								$pod.parents('ul.row').remove();
								
								// set the click for the links
								$inboundLinks.unbind('click').click(function (event) { // need to unbind to get rid of tracking delay
									_makePopup(_popups[anchorName], this);
									return false;
								});
							}
						});
					}
				}
			}
		})(),
		
		FlashVideoPreviewPod : (function () {
			var parentPodId;
			
			function _didItFail(swf) {
				if(!swf.success) {
					$("#" + parentPodId + " .genrePanels .genreContent").show();
				}
			}
			
			return {
				embed : function (config) {
					parentPodId = config.podid;
					config.id = config.podid + "_swf"
					
					config.width = 960;
					config.height = config.height || 310;
					
					config.params = config.params || {};
					config.params.wmode = "transparent";
					config.params.allowfullscreen = "true";
					
					config.flashvars = config.flashvars || {};
					config.flashvars.panelChangeCallback = "sky.storefront.FlashVideoPreviewPod.show";
					
					config.callback = _didItFail;
					
					sky.storefront.Utilities.embedFlash(config);
				},
				show : function (htmlId) {
					$("#" + parentPodId + " .genrePanels").fadeOut(200, function () {	// fade out the container
						$("#" + parentPodId + " .genrePanels .genreContent").hide();	// hide all panels
						$("#" + parentPodId + " .genrePanels").show();				// re-show the container
						$("#" + parentPodId + "_Content_" + htmlId).fadeIn(200);		// fade in the chosen panel
					});
				}
			};
		})(),
		
		FlashVideoPreviewPodPanels : (function () {
			var parentPodId = ''
			,	panels = {}
			,	callbackNames = ['Change', 'Show', 'Hide', 'Get'];
			
			function _didItFail(swf) {
				if(!swf.success) {
					$("#" + parentPodId + " .genrePanels .genreContent").show();
				}
			}
			
			function _showPanel(htmlId) {
				var text = panels[htmlId]
				,	$panel = $("<div/>")
								.addClass("panelOverlay")
								.html('<h2 class="overLayHeading">' + text.heading + '</h2><div class="overLaySummary">' + text.summary + '</div><div class="overLayAvailableText">' + text.availableText + '</div>');
								
				$("#" + parentPodId + " .panelOverlay").stop(true, true).remove();	// remove any existing, and stop any runnign animations
				$panel.appendTo("#" + parentPodId).hide();							// add the newly created panel and hide it
				$("#" + parentPodId + " .panelOverlay").fadeIn(350).show();			// fade it in. The extra show catches IE8, where fadeIn in borked, so we show straight after the fadeIn is started; if the fadeIn is working, the show will have no effect
			}

			function _hidePanel(thenShowId) {
				$("#" + parentPodId + " .panelOverlay").stop(true, true).fadeOut(200, function () {	// fade out the container					
					if (thenShowId) {
						_showPanel(thenShowId)
					}
				});
			}
				
			return {
				storePanel : function (panelConfig) {
					var _decode = sky.storefront.Utilities.decodeHTML;
					
					panels[panelConfig.id] = {
						heading: _decode(panelConfig.heading),
						summary: _decode(panelConfig.summary),
						availableText: _decode(panelConfig.availableText)
					};
				},
				embed : function (config) {
					parentPodId = config.podid;
					config.id = config.podid + "_swf"
					
					config.width = 974;
					config.height = config.height || 310;
					
					config.params = config.params || {};
					config.params.wmode = "transparent";
					config.params.allowfullscreen = "true";
					
					config.flashvars = config.flashvars || {};
					
					var i = callbackNames.length;
					while(i--) {
						config.flashvars["panel" + callbackNames[i] + "Callback"] = "sky.storefront.FlashVideoPreviewPodPanels." + callbackNames[i].toLowerCase()
					}
					
					config.callback = _didItFail;
					
					sky.storefront.Utilities.embedFlash(config);
				},
				get : function (htmlId) {
					return panels[htmlId];
				},
				show : _showPanel,
				hide : function (/* no id */) {
					_hidePanel(/* to force no "show" */);
				},
				change : function (htmlId) {
					_hidePanel(htmlId);
				}
			};
		})(),
		
		enableIafIncentiveSelection : function (config){
			$.each(config.tracking, function(name, value) { 
			  $('#'+name).click( function(){
				  sky.storefront.siteCatalystAddIncentiveToBasket(name, value, config.proposition);
			  });
			});
		},
		
		enableIafGiftSelection : function (config) {
			$("#"+config.id).submit(function () {
				if($(this).find("input[name='gift']:checked,input[name='gift']:hidden").length == 0) {
					$("#iafSelectionError").html(sky.storefront.Utilities.decodeHTML(config.error)).show();
					sky.storefront.siteCatalystErrorCode('no rewards selected');
					return false;
				}
				else {
					$("#iafSelectionError").html("").hide();
					// sitecatalyst tracking
					var selectedGift = config.tracking[$(this).find("input[name='gift']:checked,input[name='gift']:hidden").val()]
					,	products = selectedGift.split(':')[0].split(',')
					, interestSource = selectedGift.split('=').length>1 ? selectedGift.split('=')[1] : ''
					, campaignSource = '';
					
					sky.storefront.siteCatalystAddRewardsAndOffersToBasket(products,interestSource,campaignSource,config);
				}
			});
			
			function _highlightSelectedGift() {
				$('#'+config.id+' .iafGift').removeClass("iafGiftSelected");
				$('#'+config.id+' input:checked').parents('#'+config.id+' .iafGift').addClass("iafGiftSelected");				
			}
			
			$('#'+config.id+' .iafGift label').click(_highlightSelectedGift);
			_highlightSelectedGift();
			
			$('#'+config.id+' .iafGiftFooterButton').hover(
				function () {$(this).find('span, button').addClass('hover')},
				function () {$(this).find('span, button').removeClass('hover')}
			)
		},
		
		// Open the OBU lightbox or our internal jDialog depending on the responseHeader instruction
		selectDialogType : function(res){
			if(res.getResponseHeader('LIGHT-BOX-TYPE') == 'SKYID-SIGNIN'){
				$.closeDialog(true);
				SkyId.Lightbox.Signin.open();
				sky.storefront.Utilities.stopAjaxInProgress();

				var jQueryHtml = sky.storefront.Utilities.convertHtmlForJQuery(res.responseText);

				$('#emptyBasketWrapper').replaceWith(jQueryHtml.find('#emptyBasketWrapper'));

				if (res.getResponseHeader('REFFERAL-URL') && res.getResponseHeader('REFFERAL-URL').match(/[&?]iafurn=/)) {
					sky.storefront.Basket.refferalUrl = res.getResponseHeader('REFFERAL-URL');
				}
				
				$('.signIn').click(function(){
					SkyId.Lightbox.Signin.open();
					return false;
				});
			} else {
				sky.storefront.showUserADialog(res);
				$('.dialogClose, #signInLaterButton, #closeButton, #eligibilityDialog a.button').click(function() {
					// We need to reset so User can addToBasket after opting to signin later
					sky.storefront.Utilities.stopAjaxInProgress();
				});
			}
			
			if( (res.getResponseHeader('REFFERAL-URL')) && (res.getResponseHeader('REFFERAL-URL').match('addToBasket')) ){
				sky.storefront.Basket.refferalUrl = res.getResponseHeader('REFFERAL-URL');
			}
		},

		// Open jDialog and insert ajax responseText into chrome
		// Additional custom events depending on LIGHT-BOX-TYPE
		showUserADialog : function(res){
			var jQueryHtml = sky.storefront.Utilities.convertHtmlForJQuery(res.responseText);

			// this is hac-tacular
			jQueryHtml.find('#emptyBasketWrapper').remove();
			jQueryHtml.find('#fakeLoginOverlayPod').remove();
			jQueryHtml.find('#basket').remove();

			if(res.responseText != ""){
				var selfIdDialogHtml = jQueryHtml.find('#selfIdDialog')[0];
				if(selfIdDialogHtml){
					sky.shared.openJDialog(selfIdDialogHtml );
					
					/*
					 
					$('#existingCustomerButton, #prospectCustomerButton').unbind('click');					
			    	
					$("#existingCustomerButton").click(function() {
						$.closeDialog(true);
						sky.ocp.LivePerson.setLivepersonCustomer();
						sky.ocp.LivePerson.toggleSelfIdLightBoxActive();
						var url=this.form.action;
						var serializedForm=$(this.form).serialize() ;
						serializedForm += "&" + this.name + "=EC";
						serializedForm += "&" + "ajaxCall=true";

						sky.storefront.Utilities.callJQueryPost(url, serializedForm, sky.storefront.Basket.updateBasketSuccessHandler);					
						return false;												
					});
					
					$('#prospectCustomerButton').click( function() {
						$.closeDialog(true);
						sky.ocp.LivePerson.setLivepersonProspect();
						sky.ocp.LivePerson.toggleSelfIdLightBoxActive();
						var url=this.form.action;
						var serializedForm=$(this.form).serialize() ;
						serializedForm += "&" + this.name + "=PC";
						serializedForm += "&" + "ajaxCall=true";
						
						sky.storefront.Utilities.callJQueryPost(url, serializedForm, sky.storefront.Basket.updateBasketSuccessHandler);												
						return false;
					});
					
					*/
					
					$('#existingCustomerButton').unbind('click').click( function(){						
						sky.storefront.selfIdInteraction( $(this) ); 
						return false;
					})	;
					
				} else {
					var error_code = jQueryHtml.find('#5049');
					if (error_code.length > 0) {
						sky.storefront.siteCatalystIafLostIncentive();
					}
					sky.shared.openJDialog(jQueryHtml.html());
				}
			} else {
				SkyId.Lightbox.Signin.open();
				sky.storefront.Utilities.stopAjaxInProgress();
			}

			// If session has timed out when adding to lightbox, refresh page when clicking ok
			if( res.getResponseHeader('LIGHTBOX_REFRESH_BASKET') == 'true' ){
				$('#jDialogContainer a.button').click( function() {
					window.location.reload();
				});
			}

			var lightBoxType = res.getResponseHeader('LIGHT-BOX-TYPE');
			if( (lightBoxType == 'PRIMARY-BOX-REMOVE') || (lightBoxType == 'PRIMARY-BOX-NOT-STANDARD') ){
				var url = document.location.href.split('?');
				$('.exceptionDialog form').attr('action', url[0]);
				var errorCode = (lightBoxType == 'PRIMARY-BOX-REMOVE') ? 'removePrimaryBoxWarning' : 'invalidPrimaryBox';
				if (errorCode == 'removePrimaryBoxWarning') {
					$('#removePrimaryBoxOKButton').click(function() {
						var form = $(this).parent();
						var serializedForm = form.serialize();
						var url = form.attr('action') + '?ajaxCall=true';
						sky.storefront.Utilities.callJQueryPost(url, serializedForm, function(res, status){
							if( res.getResponseHeader('AJAX-INSTRUCTION') == 'LIGHT-BOX' ) {
								sky.storefront.selectDialogType(res);
							} else {
								sky.storefront.refreshPageBodyWithAjax(res.responseText);
							}
						});
						return false;
					});
				}
				sky.storefront.siteCatalystErrorCode(errorCode);
			}

			// Make this a response header so we know what LIGHT-BOX-TYPE
			var signInAsPrimaryPod = jQueryHtml.find("#signInAsPrimaryPod");
			if(signInAsPrimaryPod.length > 0){
				sky.storefront.Authentication.resetSkyIdIframe();
				$('#signInAsPrimaryButton').click(function() {
					var form = $(this).parent();
					var serializedForm = form.serialize();
					var url = form.attr('action') + '?ajaxCall=true';
					sky.storefront.Utilities.callJQueryPost(url, serializedForm, 
						function(data,status){
							// Open SkyId lightbox
							sky.storefront.Authentication.resetSkyIdIframe();
							$.closeDialog();
							// Wait until the iframe has refreshed before we open it
							sky.storefront.Authentication.checkIfSkyIdIframeIsPresent(25, SkyId.Lightbox.Signin.open);
							sky.storefront.Utilities.stopAjaxInProgress();
						}
					);
					return false;
				});

				$('#signInLaterButton').click(function(){
					document.location.href = document.location;
					return false;
				});
			}
		},

		// Displays error message which aren't in a Lightbox. 
		showInvalidCustomerNonLightbox : function(jQueryHtml) {
			$('#bodyWrapper').html( jQueryHtml.find('#siteWrapper').html() );
			$('#bodyWrapper').attr({
				'id' : 'siteWrapper',
				'class' : 'errorPage'
			});
			$('#siteWrapper form').attr('action', document.location.href);
			$('.signinContainer').css('display', 'none');
			$.closeDialog(true);
			return true;
		},

		// Called from SELF-ID lightbox form buttons
		selfIdInteraction : function(button){
			var form = button.parent();
			if( form && form.is('form') ){

				var customerType = button.val(); //form.find('input[name="customerType"]').val();
				//adding Omniture tagging about the CustomerType
				sky.storefront.siteCatalystCustomerType(button, customerType);
				// Determining LivePerson CustomerType
				if (sky.ocp) {
					sky.ocp.LivePerson.determineLivePersonCustomerTypeOnSelfId(customerType);
				}
		
				var url=form.action;
				var serializedForm=$(form).serialize();
				serializedForm += "&" + button.attr('name') + "=" + button.val();
				serializedForm += "&" + "ajaxCall=true";
				
				jQuery.ajax({
					url: url,
					type: 'POST',
					dataType: "html",
					data: serializedForm,
					complete: function(res, status, data){
						if(status == 'success'){
							// Sign in after attempting to add to basket as a PC
							if( res.getResponseHeader('AJAX-INSTRUCTION') == 'AJAX-REDIRECT' ){
								jQuery.ajax({
									url: res.getResponseHeader('CONTENT-URL'),
									complete: function(res, status){
										if( res.getResponseHeader('AJAX-INSTRUCTION') == 'LIGHT-BOX' ){
											// 	Existing customer so they must signin or they haven't signed in as primary
											sky.storefront.selectDialogType(res);
											//sky.storefront.Basket.refferalUrl = res.getResponseHeader('REFFERAL-URL');
										} else {
											// Prospect user so just update basket
											sky.storefront.Basket.updateBasketSuccessHandler(res, status, serializedForm);
										}
									}
								});
							} else if(res.getResponseHeader('AJAX-INSTRUCTION') == 'LIGHT-BOX'){
								// Sign in after attempting to add to basket as an EC or after signing from vertical/horizontal pod as EC
								sky.storefront.selectDialogType(res);
							} else {
								// Sign in after attempting to add to basket as a PC
								jQuery.ajax({
									url: res.getResponseHeader('CONTENT-URL'),
									complete: function(res, status){
										if( res.getResponseHeader('AJAX-INSTRUCTION') == 'LIGHT-BOX' ){
											sky.storefront.showUserADialog(res);
										} else {
											sky.storefront.refreshPageBodyWithAjax(res.responseText);
										}
									}
								});
							}
						}
					}
				});
			}
		},

		refreshPage : function(){
			window.location.href = window.location.href;
		},

		refreshPageBodyWithAjax : function(responseText, redirectURL){
			// Close any previous dialogs such as the loading dialog
			$.closeDialog(true);
			var jQueryHtml = sky.storefront.Utilities.convertHtmlForJQuery(responseText);
			// Update signin pod view to show signout before we reload page
			$('#righthandColumnOtherPodsWrapper').html( jQueryHtml.find('#righthandColumnOtherPodsWrapper').html() );
			$('#signinNav').html( jQueryHtml.find('#signinNav').html() );
			
			// At the moment it's too risky to refresh page with Ajax response entirely as there is inline JS.
			// Try and implement when we move to jQuery 1.4 (with added trigger support).
			if(!redirectURL){
				sky.storefront.refreshPage();
			}
		},

		addToBasketTracked : false,

		Tracking : {
			trackingInfos : {
				"tvPacks"			: { code : "TVS8,;TVM1TVM2",	prefix : "Sky World" },
				"mix"				: { code : "TVS8",				prefix : "All Entertainment" },
				"sports"			: { code : "TVM2",	prefix : "Sky Sports Mix" },
				"movies"			: { code : "TVM1",	prefix : "Sky Movies Mix" },
				"TV_ENT_1M128S0M0"  : { code : "TVS7",	prefix : "Entertainment" },
				"TV_XTR_1M256S0M0"  : { code : "TVS8",	prefix : "Entertainment Extra" },
				"TV_SKY_SPORTS_1"	: { code : "TVP3",	prefix : "Sky Sports 1" },
				"TV_SKY_SPORTS_2"	: { code : "TVP4",	prefix : "Sky Sports 2" },
				"TV_SKY_MOVIES_1"	: { code : "TVP1",	prefix : "Sky Movies 1" },
				"TV_SKY_MOVIES_2"	: { code : "TVP2",	prefix : "Sky Movies 2" },
				"ESPN"				: { code : "TVA1",	prefix : "ESPN" },
				"TV_CHELSEA"		: { code : "TVA3",	prefix : "Chelsea TV" },
				"TV_MUTV"			: { code : "TVA4",	prefix : "MUTV" },
				"TV_3DTVSUBS"				: { code : "TVA5",	prefix : "3DTV" },

				"STB_STANDARD"		: { code : "TVE1",	prefix : "Standard Box" },
				"STB_SKY_PLUS"		: { code : "TVE2",	prefix : "Sky+ Box" },
				"STB_HD"			: { code : "TVE3",	prefix : "Sky+HD Box and HD Pack" },
				"STB_HD_NO_SUB"		: { code : "TVE3",	prefix : "Sky+HD Box" },
				"STB_HD_SIN"		: { code : "TVE4",	prefix : "Self Install" },
				"STB_HD_SIN_NO_SUB"	: { code : "TVE4",	prefix : "Self Install" },
				"STB_HD_1_5_TB"		: { code : "TVE5",	prefix : "Sky+HD 1TB Box" },
				"STB_HD_1_5_TB_SIN"	: { code : "TVE6",	prefix : "Self Install HD Terrabyte" },
				"STB_HD_1TB_SIN"	: { code : "TVE6",	prefix : "Self Install HD Terrabyte" },
				"STB_HD_DIGI"		: { code : "TVE9",	prefix : "SkyHD Box and HD Pack" },
				"STB_HD_DIGI_NO_SUB": { code : "TVE9",	prefix : "SkyHD Box" },

				"ST_FREETIME"		: { code : "TP1",	prefix : "Talk Freetime" },
				"ST_UNLIMITED"		: { code : "TP2",	prefix : "Talk Unlimited" },
				"BB_MAX"			: { code : "BB1",	prefix : "Broadband Unimited" },
				"BB_MID"			: { code : "BB2",	prefix : "Broadband Everyday" },
				"BB_BASE"			: { code : "BB3",	prefix : "Broadband Base" },
				"BB_CONNECT"		: { code : "BB4",	prefix : "Broadband Connect" },
				"BB_UNLIMITED"		: { code : "BB5",	prefix : "Broadband Unimited" },

				"LR_LINE_RENTAL"	: { code : "TLR1",	prefix : "Line Rental" },
				"LR_CALL_DIVERSION"	: { code : "TOP1",	prefix : "Call Diversion" },
				"LR_CALLER_DISPLAY"	: { code : "TOP2",	prefix : "Caller Display" },
				"LR_CALL_WAITING"	: { code : "TOP3",	prefix : "Call Waiting" },
				"LR_REMINDER_CALL"	: { code : "TOP4",	prefix : "Reminder Call" },
				"LR_RING_BACK"		: { code : "TOP5",	prefix : "Ring Back" },
				"LR_VOICEMAIL_PLUS"	: { code : "TOP6",	prefix : "Voicemail Plus" },
				"LR_THREE_WAY_CALLING"		: { code : "TOP7",	prefix : "3 way calling" },
				"LR_ANONYMOUS_CALL_REJECT"	: { code : "TOP8",	prefix : "Anonymous Call Reject" },
				"LR_CALLER_BARRING"	: { code : "TOP9",	prefix : "Call Barring" },
				"LR_WITHHOLD_NUMBER": { code : "TOP10",	prefix : "Withhold number" },
				"LR_VOICEMAIL_1571"	: { code : "TOP11",	prefix : "Voicemail 1571" },
				"VCH_25_GBP" : { code : "OF1", prefix : "25 GBP MS" },
				"MARKSANDSPENCERSVOUCHER" : { code : "OF2", prefix : "MS Voucher" }
			}
		},

		espnTagging : function(){
			var hasESPNCookie = ( $.cookie('ESPN') ) ? true : false;
			var isExistingCustomer = ( $.cookie('custype') == 'EC' ) ? true : false;
			if( (isExistingCustomer) && (!hasESPNCookie) ){

				var myscript = document.createElement('script');

				var axel = Math.random()+ "";
				var a = axel * 10000000000000;
				if ((useExternalURL_javascript != undefined) && (useExternalURL_javascript)){
					myscript.src = 'http://view.atdmt.com/jaction/i90elp_SKYESPNChannelPage_1?' + a;
				}else{
					myscript.src = '';
				}
				myscript.type = 'text/javascript';

				if($.browser.msie) {
					$("body").append(myscript);
				} else {
					$("head").append(myscript);
				}
				$.cookie( 'ESPN', 'ESPN', { 'path' : '/' + sky.shared.site } );
			}
		},
		
		siteCatalystIafWarning : function(link, id,myArray) {
			if( typeof(s) === 'object' ){
				s.linkTrackVars="prop15,eVar7,prop52,eVar52,eVar25,prop30";
				s.prop15 = s.eVar7 = "mainContent_" + id.replace("error5151",'') + "_" + s.pageName;
//				campaign source
				s.eVar52=s.prop52='Lost|' +myArray[0];
				//interest source
				s.eVar25=s.prop30='Lost|' +myArray[1];
				s.tl(link,'o',"mainContent");
			}
		},

		siteCatalystGoToCheckout : function(link){
			sky.storefront.addToBasketTracked = false;
			if( typeof(s) === 'object' ){
				var channels = $('#channels').attr("value");
				var boxes = $('#boxes').attr("value");
				var allProducts = $('#allProducts').attr("value");
				var sproducts = $('#basketSproducts').attr("value");
				s.products =  $('#basketSproducts').attr("value");
				s.eVar4 = allProducts; // All Product Codes - mixes/premium/alacarte/boxes/broadband/telephony/line_rental/line_rental_features
				s.eVar20 = 'Storefront';
				s.linkTrackVars = 'products,events,eVar20,eVar4';
				s.tl( link, 'o', link.attr('id') );
			}
		},

		siteCatalystClearBasket : function(link){
			sky.storefront.addToBasketTracked = false;
			if( typeof(s) === 'object' ){
				var sproducts = $('#basketSproducts').attr("value");
				var linkName = "Clear Basket";
				var event = "scRemove";
				s.linkTrackEvents = event;
				s.events = event;
				s.products = sproducts;
				s.prop11="Clear Basket";
				s.prop14="Clear Basket";
				s.linkTrackVars="products,events,prop11,prop14";
				s.tl(link, 'o',linkName);
			}
		},

		siteCatalystDeleteItemFromBasket : function(button, productName){
			sky.storefront.addToBasketTracked = false;
			if( typeof(s) === 'object' ){
				var event = "scRemove";
				var trackingInfo = (sky.storefront.Tracking.trackingInfos[productName]) ? sky.storefront.Tracking.trackingInfos[productName] : 'undefined';
				var propName = trackingInfo.prefix + ' Removed';
				s.linkTrackEvents = event;
				s.events=event;
				s.products=';' + trackingInfo.code;
				s['prop11'] = trackingInfo.prefix;
				s.prop14 = propName;
				s.linkTrackVars="products,events,prop11,prop14";
				s.tl(button, 'o', propName);
			}
		},

		siteCatalystCustomerType : function(button, customerType) {
			if( typeof(s) === 'object' ){
				if(customerType == 'EC'){
					s.linkTrackVars = 'events,eVar23,prop8';
					s.linkTrackEvents = 'event16';
					s.events= 'event16'; 
					s.prop8= 'I am a Customer'; 
					s.eVar23= 'Existing';
					s.tl(this, 'o', s.prop8 );
				} else {
					s.linkTrackVars = 'eVar23,prop8';
					s.prop8= 'I don\'t have Sky'; 
					s.eVar23= 'Prospect';
					s.tl(this, 'o', s.prop8 );
				}
			}
		},
		
		siteCatalystAddIncentiveToBasket : function(buttonName, value, propositionId){
			if( typeof(s) === 'object' ){
				s.products =  value;
				s.eVar4 = value;
				s.eVar20 = 'Storefront';
				s.prop50 = s.eVar50 = propositionId;
				s.linkTrackVars = 'products,eVar20,eVar4,prop50,eVar50';
				s.tl( '#'+buttonName, 'o', value);
			}
		},
		
		siteCatalystAddRewardsAndOffersToBasket : function(products, interestSource, campaignSource, config){
			var productsForTracking = ''
			, trackingInfo
			, customerTypeForTracking = sky.storefront.siteCatalystDetermineCustomerType();
			
			for (var i=0, l=products.length; i < l; i++){
				trackingInfo = sky.storefront.Tracking.trackingInfos[products[i]] || {code:''};
				productsForTracking = productsForTracking + ( (i==0)?';':',;') + trackingInfo.code;
			}
			
			s.linkTrackVars = 'products,events,eVar25,prop7,eVar52,prop52';
			s.linkTrackEvents = 'scAdd';
			
			s.events = 'scAdd';
			s.products = productsForTracking;

			if (interestSource!='') {
				s.eVar25 = s.prop7 = customerTypeForTracking + interestSource;
			}
			
			if(campaignSource!=''){
				s.eVar52 = s.prop52 = customerTypeForTracking + campaignSource;
			}
			s.tl(this, 'o', config.id );
			
		},
		
		siteCatalystDetermineCustomerType : function(){
			var customerType = '';
			if($.cookie("custype") == 'EC'){
				return "e|";
			} else if($.cookie("custype") == 'PC'){
				return "p|";
			}
		},

		siteCatalystAddToBasket : function(pod, attribute){
			var podLocale = "div" + pod;
			/* Events */
			$( podLocale + " .addToBasket button").click(function(event){

				/* Traverse to the parent pod & Extract attribute ID or Class */ 
				var id = $(this).closest(podLocale).attr(attribute);

				/* Get the form clicked and the hidden value for Omniture */
				var formClicked = $(this).closest("form.addToBasket");
				var basketOmnitureId = $(formClicked).find("input.basketOmniture").val()
				var level2Offer = $(formClicked).find("input.level2Offer").val()

				/* Append to update Link  */
				if (id !== "" & sky.storefront.addToBasketTracked !== true) {

					/* Replace first hyphen(-) with +  */
					id = id.replace(/-/,"+");

					/* Replace all underscores with / */
					id = id.replace(/_/g,"/");

					/* Split the string up */
					var idSplit = id; 
					idSplit = idSplit.split("+");

					var podName = idSplit[0];
					var podLoc = idSplit[1];

					/* Check to see that Omniture available */
					if (typeof(s) === 'object'){
						var customerTypeForTracking = sky.storefront.siteCatalystDetermineCustomerType();

						s.linkTrackVars = 'products,events,eVar25,eVar15,prop21,prop4,prop7';
						s.linkTrackEvents = 'scAdd';

						s.events = 'scAdd';
						s.eVar15 = s.prop21 = podName + "|" + podLoc;

						s.products = basketOmnitureId;

						s.eVar25 = s.prop7 = customerTypeForTracking+level2Offer;

						s.tl(this, 'o', id );

						sky.storefront.addToBasketTracked = true;
					}
				}
			});

			/* End siteCatalystAddToBasket */
		},

		siteCatalystHeader : function() { 

			var debug = false;
			var pod = "#headerDiv";
			var attribute = "class";

			var podLocale = "div" + pod;

			/* Events */
			$( podLocale + " ol#primaryLinksOL li:not( li#secondaryLinksLI, ol#secondaryLinksOL li)").click(function(event){

				/* Traverse to the parent pod & Extract attribute ID or Class */ 
				var id = $(this).closest(podLocale).attr(attribute);

				var linkname = $(this).children("a").text();


				/* If id present  */
				if (id !== "") {

					/* Check to see that Omniture available */
					if (typeof(s) === 'object'){

						/* Replace first hyphen(-) with +  */
						id = id.replace(/-/,"+");

						/* Replace all underscores with / */
						id = id.replace(/_/g,"/");

						/* Extract Pod Name ID */
						/* Split the string up */
						var idSplit = id; 
						idSplit = idSplit.split("+");

						var podName = idSplit[0];
						if (debug){console.debug("podName is: '" + podName + "'");}
						var podLoc = idSplit[1];
						if (debug){console.debug("podLoc is: '" + podLoc + "'");}

						s.linkTrackVars="eVar15,prop21,prop1";

						s.eVar15 = s.prop21 = podName + "|" + podLoc;
						s.prop1 = linkname;
					}
				}
			});

		}, /* End siteCatalystHeader */

		siteCatalystTag : function(pod, attribute, getlinkname){ 

			var podLocale = "div" + pod;

			/* Events */
			$( podLocale + " a").click(function(event){
				/* Traverse to the parent pod & Extract attribute ID or Class */ 
				var id = $(this).closest(podLocale).attr(attribute);

				if (getlinkname === true){ 
					var linkname = $(this).text();
				}

				/* Append to update Link  */
				if (id !== "" ) {

					/* Check to see that Omniture available */
					if (typeof(s) === 'object'){
						/* Replace first hyphen(-) with +  */
						id = id.replace(/-/,"+");

						/* Replace all underscores with / */
						id = id.replace(/_/g,"/");

						/* Extract Pod Name ID */

						/* Split the string up */
						var idSplit = id; 
						idSplit = idSplit.split("+");

						var podName = idSplit[0];
						var podLoc = idSplit[1];

						s.linkTrackVars="eVar15,prop21,prop1";

						if (getlinkname === true){
							s.eVar15 = s.prop21 = linkname + "|" + podLoc;
						} else {
							s.eVar15 = s.prop21 = podName + "|" + podLoc;
						}

					}
					//s.tl(this, 'o', id );
				} 
			});

		}, /* End siteCatalystTag */

		siteCatalystSignin : function(){
			if( typeof(s) === 'object' ){
				s.linkTrackVars = 'events,eVar38,prop8';
				s.linkTrackEvents = 'event16';
				s.events = 'event16'; 
				s.prop8 = 'Storefront/Sign-in';
				s.tl(this, 'o', s.prop8 );
			}
		},

		siteCatalystErrorCode : function(errorCode){
			if( typeof(s) === 'object' ){
				s.pageName = errorCode;   
				s.events="event3";
				s.prop2 = errorCode;
				s.eVar2 = errorCode;
				s.tl();
			}
		},
		
		siteCatalystIafLostIncentive : function() {
			if( typeof(s) === 'object' ){
				s.pageName = "error5049";   
				s.events="event3";
				s.prop2 = s.eVar2 = "5049";
				var lostUrn = "lost-" + s.prop30;
				s.prop30 = s.eVar51 = lostUrn;
				s.tl();
			}
		},

		/* --- START: Storefront Flash JS ---------------------------------------- */
		Flash : {
			// basketData props: @requestURL, @addToBasket, @redirectTeaser, @isInternalLink, @hasDeeplinkTarget
			// taggingData props: @flashId, @eventType, @productType
				
			addToBasketClick : function(basketData, taggingData) {
				//Set Site catalyst variables
				//Add level2Offer property to taggingData
				taggingData.level2Offer = basketData.level2Offer;
				sky.storefront.Flash.setTaggingAttributes(taggingData);
				
				// Need to fix variable name in actionScript as not matching HTML version
				basketData.hasDeeplinkTarget = basketData.hasDeepLinkTarget;
				
				//Add to the basket
				sky.storefront.Basket.updateBasket(null, 'add', basketData);
			},
			
			moreInfoClick : function(taggingData) {
				//alert('Flash id: ' + taggingData.flashId + '\nProduct type:' + taggingData.productType + '\nEvent type:' +  taggingData.eventType + '\nURL:' +  taggingData.url );
				sky.storefront.Flash.setTaggingAttributes(taggingData);
				if(taggingData.url){
					document.location.href = taggingData.url;
				}
			},
			
			setTaggingAttributes: function(taggingData) {
				if (typeof(s) === 'object'){
					/* Split the string up */
					var idSplit = taggingData.flashId; 
					idSplit = idSplit.split("-");
					var flashName = idSplit[0];
					var flashLoc = idSplit[1];
	
					s.linkTrackVars = 'products,events,eVar30,eVar15,prop21,prop4';
					s.linkTrackEvents = taggingData.eventType;
					s.eVar15 = s.prop21 = flashName + "|" + flashLoc;
					s.eVar30 = taggingData.level2Offer || '';
					s.products = taggingData.omnitureCode;
					s.events = taggingData.eventType;
					s.prop4 = taggingData.level2Offer || '';
					s.tl(s, 'o', taggingData.flashId);
				}
			},
			
			flashObjects : [],
			// Neeed to store references to Objects to re-insert after Ajax refresh
			storeFlashObjects : function() {
				$('object').each( function(){
					sky.storefront.Flash.flashObjects.push( [this.id, $(this).parent().attr('innerHTML')] );
				});
			},
			
			reInsertFlashObjects : function() {
				$.each( sky.storefront.Flash.flashObjects, function(i, info){
					// Use good old fashioned JS as jQuery doesn't like the '.' in some of our id's.
					var domObject = document.getElementById( info[0] );
					var parent = $(domObject).parent();
					parent.html( info[1] );
				});
			}
		},

		/* --- START: Storefront Basket JS --------------------------------------- */
		/* Basket functionality using Ajax to add/deleteProduct items on the basket */
		Basket : {
		
			initialPath : '/shop',
			url : '/__basket/index.html?ajaxCall=true',
			ajaxInProgress : false,
			refferalUrl : null,
			basketCleared : false,
			shouldRefreshWholePage:false,
		
			add : {
				bindAction : function() {
					$('.addToBasket button').click( function() {
						sky.storefront.Basket.updateBasket( $(this), 'add', {} );
					});
				},
				
				doAction : function(button, data){
					if(button){
						var form = button.parent();
						if( form && form.is('form') ){
							data = $(form).serialize();
							if( form.find('input[name="isBundleDeepLink"]').val() == 'true' ){
								form.submit();
								//don't do ajax version if you're submitting anyway
								return;
							}	
						}
					}
					
					data.showBasketOnly = true;
					data.site = sky.shared.site;
					sky.storefront.Utilities.callJQueryPost( sky.storefront.Basket.getUrl(), data, function(res, status) {
						sky.storefront.Basket.updateBasketSuccessHandler(res, status, data);
					});
				}
			},
			
			// This is where an anchor token is used to add to basket rather than the standard button,
			// so addTobasket can occur within text.
			addToBasketToken : {
				bindAction : function() {
					$('.addToBasketToken').click( function() {
						sky.storefront.Basket.updateBasket( $(this), 'addToBasketToken', {} );
					});
				},
				
				doAction : function(token){
					var data = sky.storefront.Utilities.deSerializeString( token.attr('href') );
					data.showBasketOnly = true;
					sky.storefront.Utilities.callJQueryPost( sky.storefront.Basket.getUrl(), data, function(res, status) {
						sky.storefront.Basket.updateBasketSuccessHandler(res, status, data);
					});
				}
			},
			
			deleteProduct : {
				bindAction : function() {
					$('#basket input.delete').click( function() {
						sky.storefront.Basket.updateBasket( $(this), 'deleteProduct' );
						return false;
					});
				},
				
				doAction : function(button){
					sky.storefront.siteCatalystDeleteItemFromBasket( button, button.val() );
					var data = { 'basketSproducts' : $('#basketSproducts').val(), 'site':'shop' };
					data[ button.attr('name') ] = button.val();
					sky.storefront.Utilities.callJQueryPost( sky.storefront.Basket.getUrl(), data, function(res, status){
						if( res.getResponseHeader('AJAX-INSTRUCTION') == 'LIGHT-BOX' ) {
							sky.storefront.selectDialogType(res);
						} else {
							if (sky.storefront.Basket.shouldRefreshWholePage){
								sky.storefront.refreshPageBodyWithAjax(res.responseText);
							}else{
								sky.storefront.Basket.resetBasketView(res);
							}
						}
					});
				}
			},
				
			clearAll : {
				bindAction : function() {
					$('#basket_clearButton').click( function() {
						sky.storefront.Basket.updateBasket( $(this), 'clearAll' );
						return false;
					});
				},
			
				doAction : function(button){
					sky.storefront.siteCatalystClearBasket(button);
					var data = { 
						'basketSproducts' : $('#basketSproducts').val(),
						'clearBasket' : 'Clear basket'
					}
					sky.storefront.Utilities.callJQueryPost( sky.storefront.Basket.getUrl(), data, function(res, status){
						if( res.getResponseHeader('AJAX-INSTRUCTION') == 'LIGHT-BOX' ) {
							sky.storefront.selectDialogType(res);
						} else {
							if (sky.storefront.Basket.shouldRefreshWholePage){
								sky.storefront.refreshPageBodyWithAjax(res.responseText);
							}else{
								sky.storefront.Basket.resetBasketView(res);
							}
							
						}
					});
					sky.storefront.Basket.basketCleared = true;
				}
			},
			
			goToCheckout : {
				bindAction : function() {
					$('#basket_checkoutBottom, #basket_checkoutTop').click( function() {
						if( $('#isBasketValid').val() != 'false' && $('#isAnyOfferBroken').val() != 'true' ){
							sky.storefront.siteCatalystGoToCheckout( $(this) );
						}
						else {
							
							if( $('#isBasketValid').val() == 'false' ) {
								// Make sure we have a valid error message to display otherwise chrome/safari could throw a dialog with no content
								if( $('#invalidBasketMessageOverlayPodWrapper').html() != null ){
									
									// If user clicks 'Go to checkout' button and the basket is invalid show a dialog
									// The dialog HTML is within basket but ajax method is also available:
									// Ajax post with ajaxCall=true will also return HTML
									sky.shared.openJDialog(
										$('#invalidBasketMessageOverlayPodWrapper').html()
									);
									$('#invalidBasketMessageCloseButton').click( function() {
										$.closeDialog();
										return false;
									});
									return false;
								}	
							}

							if( $('#isAnyOfferBroken').val() == 'true' ) {
								// Make sure we have a valid error message to display otherwise chrome/safari could throw a dialog with no content
								if( $('#invalidNoOffersForIafBasketMessageOverlayPodWrapper').html() != null ){
									
									// If user clicks 'Go to checkout' button and the basket is invalid show a dialog
									// The dialog HTML is within basket but ajax method is also available:
									// Ajax post with ajaxCall=true will also return HTML
									sky.shared.openJDialog(
										$('#invalidNoOffersForIafBasketMessageOverlayPodWrapper').html()
									);
									$('#error5151ChangeIafRewardButton').click( function() {
										var mytestarray = $(this).attr('rel').split(',');
										sky.storefront.siteCatalystIafWarning(this,this.id,mytestarray);
										
									});
									$('#error5151ContinueButton').click( function() {
										var mytestarray = $(this).attr('rel').split(',');
										sky.storefront.siteCatalystIafWarning(this,this.id,mytestarray);
									});
									$('#error5151BackLink').click( function() {
										var mytestarray = $(this).attr('rel').split(',');
										sky.storefront.siteCatalystIafWarning(this,this.id,mytestarray);
										$.closeDialog();
										return false;
									});
									$('#error5151ChangeCugButton').click( function() {
										var mytestarray = $(this).attr('rel').split(',');
										sky.storefront.siteCatalystIafWarning(this,this.id,mytestarray);
										$.closeDialog();
										return false;
									});
									return false;
								}	
							}
						}
					});
				}
			},
			
			getUrl : function() {
				return sky.storefront.Basket.initialPath + sky.storefront.Basket.url;
			},
			
			setInitialPath: function(path) {
				sky.storefront.Basket.initialPath = path;
			},
				
			updateBasket : function(button, sType, flashData) {
				// Only make update if previous request is not in progress
				if(sky.storefront.Basket.ajaxInProgress){
					return false;
				} else {
					sky.storefront.Basket.ajaxInProgress = true;
					$('#ajaxTrackContainer').empty();
					sky.storefront.Basket[sType].doAction(button, flashData);
					$('#ajaxTrackContainer').append('<div id="ajaxLoaded"></div>');
					
				}
			},
			showEmailBasketResponseLightBox: function(res, testStatus) {
			var jQueryHtml = sky.storefront.Utilities.convertHtmlForJQuery(res.responseText);
	            var $emailBasketSendingErrorLightbox = jQueryHtml.find("#emailBasketSendingErrorMessageOverlayPod");
	            var $emailBasketSentSuccessfullyLightbox = jQueryHtml.find("#emailBasketSentSuccessfullyMessageOverlayPod");

	            if ($emailBasketSendingErrorLightbox.length > 0) {
	            	sky.emailBasket.showJDialog($emailBasketSendingErrorLightbox);
	                setTimeout(function() {
	                    $('.closeButton').click(function(){
	                        $.closeDialog(true);
	                        return false;
	                    });
	                }, 1);

	                s.linkTrackVars="events,prop2,eVar2,eVar4";
	                s.linkTrackEvents=s.events="event3";
	                s.prop2 = s.eVar2 = "emb - error sending email";
	                s.eVar4 = $('#allProducts').attr("value");
	                s.tl('emb', 'o', 'error');

	            }
	            if ($emailBasketSentSuccessfullyLightbox.length > 0) {
	            	sky.emailBasket.showJDialog($emailBasketSentSuccessfullyLightbox);
	                setTimeout(function() {
	                    $('.closeButton, .closePopup', '#emailBasketSentSuccessfullyMessageOverlayPod').click(function(){
	                        $.closeDialog(true);
	                        return false;
	                    });
	                }, 1);
	                
	                s.linkTrackVars="events,eVar4";
	                s.linkTrackEvents=s.events="event51";
	                s.eVar4 = $('#allProducts').attr("value");
	                s.tl('emb', 'o', 'success');
	            }
	        },
			updateBasketSuccessHandler : function(res, status, requestParams) {
				var jQueryHtml = sky.storefront.Utilities.convertHtmlForJQuery(res.responseText);
				if( res.getResponseHeader('AJAX-INSTRUCTION') == 'LIGHT-BOX' ) {
					sky.storefront.selectDialogType(res);
				} else if( jQueryHtml.find('#invalidCustomerNonLightbox')[0] ){
					$('#bodyWrapper').html( jQueryHtml.find('#siteWrapper').html() );
					$('#bodyWrapper').attr({
						'id' : 'siteWrapper',
						'class' : 'errorPage'
					});
					$('#siteWrapper form').attr('action', document.location.href);
				} else {
					// Need to turn string into data object
					var data = ( typeof(requestParams) == 'string' ) ? sky.storefront.Utilities.deSerializeString(requestParams) : requestParams;
					var redirectUrl = null;
					if(data.hasDeeplinkTarget == 'true'){
						// Redirect Url
						redirectUrl = data.requestURL + '?isInternalLink=' + data.isInternalLink + '&hasDeeplinkTarget=' + data.hasDeeplinkTarget + '&redirectTeaser=' + data.redirectTeaser + '&requestURL=' + data.requestURL;
					}
					
					// Check if page contains a basket
					if( $('#basket')[0] ){
						sky.storefront.Basket.resetBasketView(res);
						sky.storefront.Authentication.bindClearBasketDialog();
					} else if( ($('#basket')[0]) && (this.url != sky.storefront.Basket.getUrl()) ){
						// For non-basket, refresh whole page - but only if full page html is in response (not just basket)
						sky.storefront.refreshPageBodyWithAjax(res.responseText, redirectUrl);
					}
					
					if(redirectUrl){
						document.location.href = redirectUrl;
					}
					
					$.closeDialog();
				}
				
			},
		
			resetBasketView : function(res) {
				sky.storefront.Basket.ajaxInProgress = false;
				sky.storefront.Basket.refferalUrl = null;
				sky.storefront.Basket.refreshBasketContent(res);
				sky.storefront.Basket.bindBasketActions();
				sky.storefront.siteCatalystAddToBasket(".pod", "id");
				sky.storefront.Authentication.updateSignInView();
			},
	
			refreshBasketContent : function(res) {
				res.responseText.replace(/<script(.|\s)*?\/script>/g, "");
				$('#storefrontBasket').html(res.responseText);
				sky.shared.myPortfolioPanel();
				sky.shared.helpPanel();
				sky.shared.roiHelpPanel();
				sky.storefront.Authentication.updateSignInView();
			},
			
			bindBasketActions : function() {
				sky.storefront.Basket.add.bindAction();
				sky.storefront.Basket.addToBasketToken.bindAction();
				sky.storefront.Basket.clearAll.bindAction();
				sky.storefront.Basket.deleteProduct.bindAction();
				sky.storefront.Basket.goToCheckout.bindAction();
				sky.storefront.Authentication.bindBasketInvalidDialog();
			},
			
			checkIfBasketIsEmpty : function() {
				var $basketSproducts = $('#basketSproducts');
				var $val = "";
				
				if($basketSproducts.length > 0){
					$val = $basketSproducts.val();
				}
				if( sky.storefront.Basket.basketCleared || $val.length < 1 ){
					return true;
				} else {
					return false;
				}
			}
		},

		/* --- START: Storefront TV Details -------------------------------------- */
		tvDetails : {
	
			thumbnailNavigation : function() {
			
				/* Events */
				$( "div.tvDetailsTeaser .thumbnailItem a").click(function(event){	
					event.preventDefault();
					var tvcarousel = $(this).closest("ul.tvcarousel"); /* Get the carousel we are in*/					
					var item = $(this).closest("li.item"); /* Get the item object clicked on */					
					var tvteaser = $(this).closest("div.tvDetailsTeaser"); /* Get the tvDetailsTeaser clicked on */
					
					$(tvcarousel).find("li.thumbimage").removeClass("on"); /* Turn image background onstates off */					
					$(item).find("li.thumbimage").addClass("on"); /* Turn the image background into the onstate */ 
	
					/* Get the data we need to update the tvIntro/introItem  */
					var mainImageSrc = $(item).find("li.mainimage img").attr("src");
					var mainImageAlt = $(item).find("li.mainimage img").attr("alt");
					var title = $(item).find("li.title").html();
					var copy = $(item).find("li.copy").html();
					var links = $(item).find("li.links").html();
					
					/* For thumbnailMulti we need to position the pagination nicely */
					var tvTeaserClass = $(tvteaser).attr("class");
					
					if (tvTeaserClass == "tvDetailsTeaser thumbnailMulti"){
						$(tvteaser).find("div.tvIntro li.pagination").hide();
					}
					
					$(tvteaser).find("ul.introItem").fadeOut("fast", function () {
	
						/* Update the tvIntro/introItem */
						$(tvteaser).find("div.tvIntro ul.introItem li.mainimage img").attr({
							src: mainImageSrc,
							alt: mainImageAlt
						});
						$(tvteaser).find("div.tvIntro ul.introItem li.title").html(title);
						$(tvteaser).find("div.tvIntro ul.introItem li.copy").html(copy);
						$(tvteaser).find("div.tvIntro ul.introItem li.links").html(links);
	
						if (tvTeaserClass == "tvDetailsTeaser thumbnailMulti"){
							
							$(this).fadeIn("fast", function () {								
								/* Position pagination */
								var titleHeight = $(tvteaser).find("div.tvIntro li.title").height();
								var copyHeight = $(tvteaser).find("div.tvIntro li.copy").height();
								var linksHeight = $(tvteaser).find("div.tvIntro li.links").height();
	
								var totalHeight = titleHeight + copyHeight + linksHeight;
								
								if (totalHeight < 158) {
									var offsetHeight = 158 - totalHeight;
									offsetHeight = offsetHeight + linksHeight;
									$(tvteaser).find("div.tvIntro li.links").height(offsetHeight);
								}
							
								$(tvteaser).find("div.tvIntro li.pagination").show();
							});						
						} else {							
							$(this).fadeIn("fast");
						}						
					});					
				});
			},
			
			tvDetailsPaging : function(tvtype) {
	
				/* Some set up specifically for this Teaser */
				/* Check to see if there are instances of the teaser on the page */
				var noPageTvTeasers = $("div.tvDetailsTeaser."+ tvtype +"").length -1;
	
				/* If the teasers are present */
				if (noPageTvTeasers >= 0) {
				
					/* Create Arrays with the page numbers and length of the thumbnail lists */
					var pageNos = new Array(noPageTvTeasers);
					var initTvCarouselLength = new Array(noPageTvTeasers);
	
					for (i=0; i <= noPageTvTeasers; i++){
						
						pageNos[i] = 1; // Set the page to first for page load
	
						/* Get initial thumbnails list length */
						initTvCarouselLength[i] = $("div.tvDetailsTeaser."+ tvtype +":eq("+ i +") ul.tvcarousel ul.thumbnailItem").length;
	
						/* Update the counter */
						var initpagecounter = "1/" + initTvCarouselLength[i];
						$("div.tvDetailsTeaser."+ tvtype +" div.tvIntro li.pagination div.pagecount:eq("+ i +")").html(initpagecounter);
	
						/* If there is only one item in the list don't display the next button */
						if (initTvCarouselLength[i] == 1){
							$("div.tvDetailsTeaser."+ tvtype +" div.tvIntro li.pagination div.pageright:eq("+ i +")").hide();
						}
						
						/* Give each instance a unique id */
						$("div.tvDetailsTeaser."+ tvtype +":eq("+ i +")").attr("id", "tvDetailsTeaser"+ tvtype +"" + i);
						
						/* Turn border 'on' on first item */
						if ( tvtype  == "thumbnailMulti"){
							$("div.tvDetailsTeaser.thumbnailMulti:eq("+ i +") li.thumbimage:eq(0)").addClass("on");
						}
						
						/* Position pagination */
						
						var titleHeight = $("div.tvDetailsTeaser."+ tvtype +" div.tvIntro li.title:eq("+ i +")").height();
						var copyHeight = $("div.tvDetailsTeaser."+ tvtype +" div.tvIntro li.copy:eq("+ i +")").height();
						var linksHeight = $("div.tvDetailsTeaser."+ tvtype +" div.tvIntro li.links:eq("+ i +")").height();
	
						var totalHeight = titleHeight + copyHeight + linksHeight;
						if (totalHeight < 158) {
							var offsetHeight = 158 - totalHeight;
							offsetHeight = offsetHeight + linksHeight;
							
							$("div.tvDetailsTeaser."+ tvtype +" div.tvIntro li.links:eq("+ i +")").height(offsetHeight);
							
						}
					}
					
					$( "div.tvDetailsTeaser."+ tvtype +" li.pagination a").click(function(event){
	
						event.preventDefault();
	
						/* Get the tvDetailsTeaser clicked on */
						var tvteaser = $(this).closest("div.tvDetailsTeaser."+ tvtype +"");
						
						/* Clear previously set height on links */
						$(tvteaser).find("div.tvIntro li.links").css("height", "auto");
						
						/* Find out which 'noPageTvTeasers' i am via my set id*/
						var myIndex = $(tvteaser).attr("id");
												
						switch(tvtype) {
							case "nothumbs":
								myIndex = myIndex.replace(/tvDetailsTeasernothumbs/,"");
								break;
							case "thumbnailMulti":
								myIndex = myIndex.replace(/tvDetailsTeaserthumbnailMulti/,"");
								break;
							default:
						}
	
						/* Count how many items in the ul tvcarousel list */
						var tvcarouselLength = $(tvteaser).find("ul.tvcarousel ul.thumbnailItem").length;
	
						/* Clicked Prev or Next*/
						var pagenav = $(this).closest("div").attr("class");
	
						switch(pagenav) {
							case "pageleft":
								pageNos[myIndex] = pageNos[myIndex] -1;
								break;
							case "pageright":
								pageNos[myIndex] = pageNos[myIndex] +1;
								break;
							default:
						}
	
						/* Set up the display of buttons */
						if ( pageNos[myIndex] == 1 ) {
							$(tvteaser).find("div.tvIntro li.pagination div.pageleft").hide();
							$(tvteaser).find("div.tvIntro li.pagination div.pagecount").css('margin-left', '17px');
						} else {
							$(tvteaser).find("div.tvIntro li.pagination div.pageleft").show();
							$(tvteaser).find("div.tvIntro li.pagination div.pagecount").css('margin-left', '0px');
						}
	
						if ( pageNos[myIndex] == tvcarouselLength ) {
							$(tvteaser).find("div.tvIntro li.pagination div.pageright").hide();
						} else {
							$(tvteaser).find("div.tvIntro li.pagination div.pageright").show();
						}
	
						var pagecounter = pageNos[myIndex] + "/" + tvcarouselLength;
						
						/* Update the counter */
						$(tvteaser).find("div.tvIntro li.pagination div.pagecount").html(pagecounter);
	
						/* Create an index var to navigate through the content */
						var itemIndex = pageNos[myIndex] -1;
						
						/* Get the data we need to update the tvIntro/introItem  */
						var mainImageSrc = $(tvteaser).find("div.tvThumbmenu ul.tvcarousel li.mainimage img:eq("+ itemIndex +")").attr("src");
						var mainImageAlt = $(tvteaser).find("div.tvThumbmenu ul.tvcarousel li.mainimage img:eq("+ itemIndex +")").attr("alt");
						var title = $(tvteaser).find("div.tvThumbmenu ul.tvcarousel li.title:eq("+ itemIndex +")").html();
						var copy = $(tvteaser).find("div.tvThumbmenu ul.tvcarousel li.copy:eq("+ itemIndex +")").html();
						var links = $(tvteaser).find("div.tvThumbmenu ul.tvcarousel li.links:eq("+ itemIndex +")").html();
						
						$(tvteaser).find("div.tvIntro li.pagination").hide();
						
						$(tvteaser).find("div.tvIntro ul.introItem").fadeOut("fast", function () {
							/* Update the tvIntro/introItem */
							$(tvteaser).find("div.tvIntro ul.introItem li.mainimage img").attr({
								src: mainImageSrc,
								alt: mainImageAlt
							});
							$(tvteaser).find("div.tvIntro ul.introItem li.title").html(title);
							$(tvteaser).find("div.tvIntro ul.introItem li.copy").html(copy);
							$(tvteaser).find("div.tvIntro ul.introItem li.links").html(links);
							
							$(this).fadeIn("fast", function () {

								/* Position pagination */
								var titleHeight = $(tvteaser).find("div.tvIntro li.title").height();
								var copyHeight = $(tvteaser).find("div.tvIntro li.copy").height();
								var linksHeight = $(tvteaser).find("div.tvIntro li.links").height();
								var totalHeight = titleHeight + copyHeight + linksHeight;
								
								if (totalHeight < 158) {
									var offsetHeight = 158 - totalHeight;
									offsetHeight = offsetHeight + linksHeight;
									$(tvteaser).find("div.tvIntro li.links").height(offsetHeight);
								} 	
							
								$(tvteaser).find("div.tvIntro li.pagination").show();
							});
						});
						
						
						if ( tvtype  == "thumbnailMulti"){
							$(tvteaser).find("div.tvThumbmenu ul.tvcarousel li.thumbimage").removeClass("on");
							$(tvteaser).find("div.tvThumbmenu ul.tvcarousel li.thumbimage:eq("+ itemIndex +")").addClass("on");
						}
					});
					
					/* If thumbnailMulti we need to update the pagination when thumbnails are clicked on */
					if ( tvtype  == "thumbnailMulti"){
						$( "div.tvDetailsTeaser.thumbnailMulti ul.thumbnailItem a").click(function(event){
					
							/* Get the tvDetailsTeaser clicked on */
							var tvteaser = $(this).closest("div.tvDetailsTeaser.thumbnailMulti");
							
							/* Clear previously set height on links */
							$(tvteaser).find("div.tvIntro li.links").css("height", "auto");
					
							/* Find out which 'noPageTvTeasers' i am via my set id*/
							var myIndex = $(tvteaser).attr("id");
							myIndex = myIndex.replace(/tvDetailsTeaserthumbnailMulti/,"");
	
							/* Get item No clicked on */
							var itemNoClicked = $(this).closest(".item").attr("class");
							itemNoClicked = itemNoClicked.replace(/item item/,"");
							
							itemNoClicked = itemNoClicked *1;/* Make sure we have a number */
	
							/* Update the page no with the clicked on page */
							pageNos[myIndex] = itemNoClicked;
	
							/* Count how many items in the ul tvcarousel list */
							var tvcarouselLength = $(tvteaser).find("ul.tvcarousel ul.thumbnailItem").length;
							
							/* Create Pagecounter String  */
							var pagecounter = pageNos[myIndex] + "/" + tvcarouselLength;
							
							/* Set up the display of buttons */
							if ( pageNos[myIndex] == 1 ) {
								$(tvteaser).find("div.tvIntro li.pagination div.pageleft").hide();
								$(tvteaser).find("div.tvIntro li.pagination div.pagecount").css('margin-left', '17px');
							} else {
								$(tvteaser).find("div.tvIntro li.pagination div.pageleft").show();
								$(tvteaser).find("div.tvIntro li.pagination div.pagecount").css('margin-left', '0px');
							}
	
							if ( pageNos[myIndex] == tvcarouselLength ) {
								$(tvteaser).find("div.tvIntro li.pagination div.pageright").hide();
							} else {
								$(tvteaser).find("div.tvIntro li.pagination div.pageright").show();
							}	
							
							/* Update the counter */
							$(tvteaser).find("div.tvIntro li.pagination div.pagecount").html(pagecounter);
						});
					}
				}
			}
		},
		/* --- START: Storefront IAF Callout -------------------------------------- */
		IAFCallout : {
			_initialiseCallouts : function() {
				$('.callout').each(function() {
					var target_el = $(this).attr('id').replace('callout_', '');
					$('.iafGiftImage, .iafGiftHeading', '#' + target_el).bind('mouseover', function() {
						sky.storefront.IAFCallout._triggerCallout('#callout_' + target_el, target_el);
						return false;
					}).bind('mouseout', function() {
						sky.storefront.IAFCallout._doClose();
					});
				}).hide();
			},
			_triggerCallout : function(content, target_el) {
				$('#calloutIaf').html($(content).html());
				this._positionAndShowCallout($('#' + target_el + ' .iafGiftHeading'));
			},
			_positionAndShowCallout : function($el) {
				$('#calloutWrapper').css({
					'top' : ($el.offset().top + $el.height()) + 8,
					'left' : $el.offset().left - 22
				}).show();
			},
			_generateAndInitialiseCalloutMarkup : function() {
				$('<div id="calloutWrapper"><div id="calloutIaf"></div></div>').appendTo('#bodyDiv');
				this._initialiseCloseActions();
			},
			_initialiseCloseActions : function() {
				if (!$.browser.msie) {
					$(window).bind('resize', function() {
						sky.storefront.IAFCallout._doClose();
					});
				}
			},
			_doClose : function() {
				$('#calloutWrapper').hide().css({'top' : 'auto', 'left' : 'auto'}).find('#calloutIaf').empty();
			},
			/* 'Public' methods */
			initialise : function() {
	        	this._generateAndInitialiseCalloutMarkup();
	        	this._initialiseCallouts();
	        },
	        closeCallouts : function() {
	        	this._doClose();
	        }
		}
	};
	
	jQuery("html").addClass("jsEnabled");

	jQuery( function() {
		jQuery('#jsEnabled').val('true');
		
		// class should be on the html tag, but several pod rely on it being on the body
		jQuery("body").addClass("jsEnabled"); 

		sky.shared.helpPanel();
		sky.shared.myPortfolioPanel();
		sky.shared.roiHelpPanel();
		sky.shared.buttonMouseoverForIE6();
		sky.shared.Tools.init();

		// reset width
		if($.browser.msie && $.browser.version >= 6) {
			$('#searchTextPrint').css('width', '36em');
		} else {
			$('#searchTextPrint').css('width', '35em');
		}

		$('#searchTextPrint').css('margin-right', '4px');
		$('#searchTextPrint').css('margin-top', '0');
		$('#searchTextPrint .tl, #searchTextPrint .tr, #searchTextPrint .bl, #searchTextPrint .br').css('display', 'block');

		if($.browser.safari) {
			$('#utilityDiv #searchSiteOL').css('height', '27px');
			$('#utilityDiv #searchSiteOL').css('margin-bottom', '5px');
			$('#utilityDiv #searchTextPrint').css('-webkit-border-radius', '5px');
			$('#searchTextPrint .tl, #searchTextPrint .tr, #searchTextPrint .bl, #searchTextPrint .br').css('background', 'none');
		}

		// Add expando to faq headings
		$('.faq h3').click(function() {
			$(this).parent('li').toggleClass('expanded');
		});

		if($('#basketContainer')[0]){
			$('#jsIsEnabled').val('true');
		}

		sky.storefront.siteCatalystHeader();
		sky.storefront.siteCatalystAddToBasket(".pod", "id");
		sky.storefront.siteCatalystAddToBasket(".topImagePod", "id");
		sky.storefront.siteCatalystAddToBasket(".headlineHalfWidthPod", "id");
		sky.storefront.siteCatalystAddToBasket(".headlineFullWidthPod", "id");
		sky.storefront.siteCatalystTag("#globalNavDiv", "class", true);
		sky.storefront.siteCatalystTag("#headerDiv", "class", true);
		sky.storefront.siteCatalystTag("#siteMapDiv", "class", true);
		sky.storefront.siteCatalystTag("#footerDiv", "class", true);
		sky.storefront.siteCatalystTag(".tabNavigation", "id", true);
		sky.storefront.siteCatalystTag(".pod", "id", false);
		sky.storefront.siteCatalystTag(".topImagePod", "id", false);
		sky.storefront.siteCatalystTag(".headlineHalfWidthPod", "id", false);
		sky.storefront.siteCatalystTag(".headlineFullWidthPod", "id", false);

		// Create a placeholder link for initialising skyId sign-in lightbox
		// Do not remove ID attribute as this is referenced by SkyId.Lightbox.OnlineShop.init
		if( !$('#skyidSigninLink')[0] ){
			$('<a id="skyidSigninLink" class="hide" href="#" title="Ignore this link" />').appendTo('body');
		}

		sky.storefront.Authentication.bindSignInAction();
		sky.storefront.Authentication.updateSignInView();
		sky.storefront.Authentication.deepLinkPopUpSignInView();
	
		sky.storefront.Basket.bindBasketActions();
		
		/* Enable jCarousel for any Tv Details Teasers Using it  */
		jQuery('div.tvDetailsTeaser.thumbnails div.tvThumbmenu. ul.tvcarousel').jcarousel({scroll: 5, wrap: 'last'});
		jQuery('div.tvDetailsTeaser.thumbnailsHD div.tvThumbmenu ul.tvcarousel').jcarousel({scroll: 5, wrap: 'last'});
		jQuery('div.tvDetailsTeaser.thumbnailTitles div.tvThumbmenu ul.tvcarousel').jcarousel({scroll: 5, wrap: 'last'});
		jQuery('div.tvDetailsTeaser.thumbnailTitlesHD div.tvThumbmenu ul.tvcarousel').jcarousel({scroll: 5, wrap: 'last'});
		
		sky.storefront.tvDetails.thumbnailNavigation();
		sky.storefront.tvDetails.tvDetailsPaging("thumbnailMulti");
		sky.storefront.tvDetails.tvDetailsPaging("nothumbs");
		
		sky.storefront.DropdownSelectorPod.initialise();
		sky.storefront.ExpandCollapsePod.initialise();
		sky.storefront.infoPopUpPod.initialise();
		sky.storefront.IAFCallout.initialise();

		var selfIDHiddenInput = $('#showSelfID')[0];
		if(selfIDHiddenInput){
			var url=selfIDHiddenInput.form.action;
			var serializedForm=$(selfIDHiddenInput.form).serialize() ;
			sky.storefront.Utilities.callJQueryPost(url, serializedForm, sky.storefront.showUserADialog);
		}
		if( $('#skyLightBoxOverlayPod').html() != null ) {
			sky.shared.openJDialog(
				'<div id="skyLightBoxOverlayPod" class="dialogContainer exceptionDialog">' +	$('#skyLightBoxOverlayPod').html() + '</div>');
		}
	});
	
})();
