// ----------------------------------------
// -- NAMESPACES --------------------------
// ----------------------------------------

// Define the console object if not already there
if (console === undefined) {
	var console = {};
	console.log 
		= console.warn
		= console.error
		= console.debug
		= console.info
		= console.trace
		= function () {};
}

// Define framework namespaces
var nf = nf || {};			// Nike Football/Women
	nf.fw = nf.fw || {};	// Framework
	nf.gv = nf.gv || {};	// Global Variables
	nf.tr = nf.tr || {};	// Tracking interceptor


// ----------------------------------------
// -- GLOBAL VARIABLES --------------------
// ----------------------------------------

// Could be used to set host information, currently blank so URLs should be /nikewomen/?
nf.gv.host = '';

// Has flash installed?
nf.gv.hasflash = swfobject.getFlashPlayerVersion();
if(nf.gv.hasflash.major === 0){
	nf.gv.hasflash = false;
} else {
	nf.gv.hasflash = true;
}

// ----------------------------------------
// -- SERVICES ----------------------------
// ----------------------------------------

$.getScript("/nikewomen/assets/framework/v1/js/services.js");


// ----------------------------------------
// -- TRACKING WRAPPER --------------------
// ----------------------------------------

nf.tr.init = function(){
	nf.tr.options = nf.tr.options || {};
	
	// Set up anchor tracking for footer links
	// track_site taken from global variable set for dalewarth tracking script
	$("div.sitemapinner li.link a").click(function(){
		s.eVar13 = "footer>nav";
		s.prop3 = "footer>nav";
		nf.tr.click(track_site + $(this).attr("data-tracking"));
	
	});
	
	// Set up anchor tracking for central nav links
	// track_site taken from global variable set for dalewarth tracking script
	$("div#centralNav a").click(function(){
		s.prop18 = "collections";
		nf.tr.click(track_site + $(this).attr("data-tracking"));
	
	});
	
	// Set up anchor tracking for non-commerce pdps
	// track_site taken from global variable set for dalewarth tracking script
	$("div.tooltip p.storeLocation a").live("click", function(){
	
		s.prop18 = "lookbook"; //featuredProductName
		nf.tr.click(track_site + $(this).attr("data-tracking"));
	
	});
	
}

// Fired on page loaded
nf.tr.page = function(string){
	tracking.click(string);
}

// Fired on CTA clicks
nf.tr.click = function(string){
	tracking.click(string);
}

// Fired when content is changed without reload of page i.e. ajax, tabs
nf.tr.view = function(string){
	tracking.click(string);
}

// Fired when overlays are displayed
nf.tr.overlay = function(string){
	tracking.click(string);
}

// ----------------------------------------
// -- CUFON -------------------------------
// ----------------------------------------

// Set font family count to support single font locales (ja_JP, zh_HK, zh_CN etc)
// Font count is increased within each font file
Cufon.fontCount = 0;

// Cufon replacement method
nf.fw.cufonise = function (cufonData, fontFamilyBase) {
	if (cufonData === undefined || !cufonData) {
		return;
	}
	
	// If single font family detected change all calls to use header font
	if(Cufon.fontCount == 1){
		fontFamilyBase = "header";
	}

	if (nf.gv.textReplacement) {
		Cufon.set('fontFamily', fontFamilyBase);
		$.each(cufonData, function (idx, ele) {
			var selector = ele.selector;
			if (selector === undefined || !selector) {
				return;
			}
			if (ele.options === undefined || !ele.options) {
				Cufon.replace(selector);
			} else {
				Cufon.replace(selector, ele.options);
			}
		});
	}
}

// Framework Cufon
nf.fw.goCufon = function () {
	var cufonDataHeader = [
		{selector: '#p_navigation div.third-level li h2'},
		{selector: '#p_navigation li a', options: {hover: true}},
		{selector: '#p_navigation dd a', options: {hover: true}},
		{selector: '#p_navigation dt a', options: {hover: true}},
		{selector: '#swooshlozenge a', options: {hover: true}},
		{selector: '#p_commerce .commerceinner a', options: {hover: true}},
		{selector: '#p_commerce .nikeplusinner .hdr a', options: {hover: true}}
		
	];
	
	nf.fw.cufonise(cufonDataHeader, 'header');
	
	var cufonDataBody = [
		//{selector: 'div.footercontainer a', options: {hover: true}},
		//{selector: 'div.footercontainer p.copyright'},
		//{selector: 'div.footercontainer li strong'}
	];
	
	nf.fw.cufonise(cufonDataBody, 'body');
	
}

// ----------------------------------------
// -- CONTENT STUB ------------------------
// ----------------------------------------
nf.fw.setUpContentStub = function(){
	
	$("#p_innerwrapperfooter").prepend($("#p_contentstub"));
	
	$.each($("div#p_contentstub>div"), function(index){

		var precontent = $(this).find(">*");
		if(precontent[0].tagName.toUpperCase() == "P"){
			var postcontent = precontent.slice(0,precontent.length);
			
			var left = postcontent.slice(0,((postcontent.length/2)));
			var right = postcontent.slice(left.length, postcontent.length);
			
			var leftcount = 0;
			var rightcount = 0;
			
			$.each(left, function(){
				leftcount = parseInt(leftcount) + parseInt($(this).html().length);
			});
			$.each(right, function(){
				rightcount = parseInt(rightcount) + parseInt($(this).html().length);
			});
			
			if(leftcount < rightcount){
				left = postcontent.slice(0,((postcontent.length/2)+1));
				right = postcontent.slice(left.length, postcontent.length);
			}
		
			$(this).empty();
			$(this).append('<div class="leftcol"></div><div class="rightcol"></div>');
			
			for(i=0;i<left.length;i++){
				$(this).find("div.leftcol").append(left[i]);
			}
			for(i=0;i<right.length;i++){
				$(this).find("div.rightcol").append(right[i]);
			}
		} else {
			var h = $(precontent[0]).height();
			if($(precontent[1]).height() > h){ h = $(precontent[1]).height() }
			$(this).css("height",h);
		}
	});
	
}

/* ----------------------------------------
 * -- HTML5 VIDEO WITH FLASH FALLBACK -----
 * ---------------------------------------- */
nf.fw.videos = {

	init: function(){
		
		this.supportsHTMLVideo();
		
		/*if((!nf.gv.supportsHTMLVideo)){
		// IE can not handle a request to get a non-supported tag, therefore we use the div wrapper instead
		$.each($(".videotagcontainer"), function(index, item){
			nf.fw.videos.setUpVideoPlaceHolder(item);
		});
		}*/
		
	},
	
	supportsHTMLVideo: function(){

		nf.gv.supportsHTMLVideo = false;
		
		/*
			var v = document.createElement("video");
			if((!v.play)){
				nf.gv.supportsHTMLVideo = false;
			} else {
				nf.gv.supportsHTMLVideo = true;
			}
		*/
		
		
	},

	showVideoInOverlay: function(guid, options){
	
		// Add container for simple video overlays
		$("body").append('<div id="p_overlaycontainer"></div><div id="p_overlayvideo"><span id="p_video"></span><span id="p_closeoverlay"></span></div>');
		$("#p_closeoverlay").click(function(evt){
			nf.fw.videos.hideVideoOverlay();
		});
		if($.browser.version.indexOf("6.") != -1){
			$("#p_overlaycontainer").addClass('close').click(function(evt){
				nf.fw.videos.hideVideoOverlay();
			});
		}
		$("#p_overlayvideo").hide();
		
		if (nf.gv.supportsHTMLVideo) {
			// embed HTML video
			this.injectHtmlVideo("p_video", guid);
		} else {
			// use flash video player
			if (options) {
				// Option to use the old Odaptor video player
				if (options.useOld) {
					this.injectFlashVideo("p_video", guid);
				}
				else {
					if (options.width && options.height) { 
						$("#p_video").videoplayer({guid: guid, locale: nf.gv.locale, width: options.width, height: options.height} );						
						// test guid 74d32089-43d0-fa57-b00a-35ca690fa341
					}
					if (options.playerType) { 
						$("#p_video").videoplayer({guid: guid, locale: nf.gv.locale, playerType: options.playerType } );						
					}
				}
			}
			else { // Default to using Brightcove video player at full 908px width
				$("#p_video").videoplayer({guid: guid, locale: nf.gv.locale});
			}
		}
		
		this.placement();
		
		$("#p_overlaycontainer").fadeTo("slow", 0.6);
		$("#p_overlayvideo").fadeTo("slow", 1);
		
	},

	placement: function(){

		if($.browser.msie){
			if($.browser.version.indexOf("6.") != -1){
				$('html,body').animate({scrollTop: 0});
			}
		}
		$("#p_overlaycontainer").css({
			"height" : $("body").height()
		});
		if($.browser.msie){
			$("#p_overlayvideo").css({
				"left" : ((($("body").width()-910)/2)+36)
			});
		}else{
			$("#p_overlayvideo").css({
				"left" : ((($("body").width()-910)/2)+35)
			});
		}
	},

	hideVideoOverlay: function(){
		$("#p_overlayvideo").fadeTo("fast", 0);
		$("#p_overlaycontainer").fadeTo("slow", 0, function(){
			$("#p_video").remove();
			$("#p_overlayvideo").remove();
			$("#p_overlaycontainer").remove();
		});
		
	},
	
	injectHtmlVideo: function(moduleElement, guid){
		$(moduleElement).load('/nikewomen/assets/framework/v1/html/snippet-video.html .videoplayer');
		if(debugMode){
			console.log("-- MSG -- HTML video player initialised");
		}
	},

	injectFlashVideo: function(moduleElement, guid){
		
		//console.log(moduleElement);
		//console.log(guid);
		
		var flashVars = {};
		var flashParams = {};
		var flashAttributes = {};

		flashVars.locale = nf.gv.locale;
		
		flashParams.wmode = ($.browser.msie)? "window": "opaque";
		flashParams.scale = "noscale";
		flashParams.allowScriptAccess = "always";
		flashParams.allowFullScreen = "true";
		flashParams.bgColor = "#000000";

		// Video module specific
		var moduleWidth = "908";
		var moduleHeight = "510";
		
		var moduleSWF = "http://www.nike.com/nikeos/global/modules/video/v1/swf/video_player_v2_0.swf";
		
		/**
			IE8-specific workaround: IE8 will not play the video more than
			once. The issue has been narrowed to a problem retrieving
			the video data from the browser cache. Adding random number
			parameter to the swf to prevent caching.
		*/
		if($.browser.msie){
			if($.browser.version.indexOf("8.") != -1){
				moduleSWF = moduleSWF + "?rand=" + Math.floor(Math.random()*100000);
			}
		}

		flashVars.guid = guid;
		
		// replace __ with _
		flashVars.locale = nf.gv.locale.replace(/__/,"_");
		
		flashVars.regionConfig = "http://www.nike.com/nikeos/global/modules/video/v1/xml/reg/reg_config_" + nf.gv.locale.replace(/__/,"_") + ".xml";
		flashVars.siteConfig = "http://www.nike.com/nikewomen/global/xml/videoSiteConfig.xml";
		
		flashVars.currentUrl = escape(location.href);

		flashAttributes.id = moduleElement;
		flashAttributes.name = moduleElement;

		swfobject.embedSWF(moduleSWF, moduleElement, moduleWidth, moduleHeight, "9", flashParams.bgColor, flashVars, flashParams, flashAttributes);
	
	}
	
}


/* ----------------------------------------
 * -- MINI PDP ----------------------------
 * ---------------------------------------- */
nf.fw.minipdp = {

    init: function () {

        // Add NikeOS EventBridge listener interceptors for 
        // viewDetails, goToCheckout, loginRequired, goToLocker and close miniPDP events (overrides nikecommerce.js)
        var nonOSminiPDPObject = {};
        nonOSminiPDPObject.listenerFunction = function (event) {
            
            switch (event.data.id) {
                case "viewDetails":
                    var curCommerce = nike_commerce.mandatoryFlashParams;
                    var curCategory = document.location.href.substring((document.location.href.lastIndexOf("/") + 1), document.location.href.indexOf("?"));
                    var catToReturn = "shoes";
                    if (curCategory != "shoes") {
                        catToReturn = "clothing";
                    }
                    if (curCategory == "bags") {
                        catToReturn = "gear";
                    }

                    var targetUrl = document.location.protocol + "//" + document.location.host + "/nikeos/p/nikewomen/" + nf.gv.locale + "/" + catToReturn + "?ll=" + curCommerce.lang_locale + "&ct=" + curCommerce.country + "&pid=" + event.data.productId + "&cid=" + event.data.catalogId + "&pgid=" + event.data.productGroupId + "&p=PDP#/";
                    location.href = targetUrl;
                    // e.g. http://dev.nike.com/nikeos/p/nikewomen/en_GB/clothing?ll=en_GB&ct=GB&pid=&cid=102001&pgid=&p=PDP
                    break;
                case "goToCheckout":
                    var curCommerce = nike_commerce.mandatoryFlashParams;
                    if (document.location.href.indexOf("ecn10") != -1) {
                        var curEnviron = "ecn10-secure-store";
                    } else {
                        var curEnviron = "secure-store";
                    }
                    var targetUrl = "https://" + curEnviron + ".nike.com/nikestore/checkout/index.jsp?l=cart&site=nikewomen&country=" + curCommerce.country + "&lang_locale=" + curCommerce.lang_locale + "&returnURL=" + escape(document.location);
                    location.href = targetUrl;
                    // e.g. https://secure-store.nike.com/nikestore/checkout/index.jsp?l=cart&site=nikewomen&country=GB&lang_locale=en_GB&returnURL=
                    break;
                case "loginRequired":
                    var curCommerce = nike_commerce.mandatoryFlashParams;
                    var targetUrl = "/nikeos/p/nikewomen/" + nf.gv.locale + "/profile?page=signin&fields=screenname&continueURL=" + escape(document.location);
                    location.href = targetUrl;
                    // e.g. http://dev.nike.com/nikeos/p/nikewomen/en_GB/profile?page=signin&fields=screenname&continueURL=
                    break;
                case "goToLocker":
                    var curCommerce = nike_commerce.mandatoryFlashParams;
                    var targetUrl = "/nikeos/p/nikewomen/" + nf.gv.locale + "/commerce?ll=" + curCommerce.lang_locale + "&ct=" + curCommerce.country + "&p=ML";
                    location.href = targetUrl;
                    // e.g. http://www.nike.com/nikeos/p/nikewomen/en_GB/commerce?ll=en_GB&ct=GB&p=ML
                    break;
                case "close":
                    $(".FlashPDP").hide();
                    //alert(event);
                    break;
                default:
                    //alert(event.data.id);
            }

        }

            EventBridge.addListener("minipdpEventType", nonOSminiPDPObject, "listenerFunction");

            // Add NikeOS EventBridge listener interceptors for 
            // gotomylocker, gotoorderstatus events (overrides nikecommerce.js)
            var nonOSmyLockerObject = {};
            nonOSmyLockerObject.listenerFunction = function (event) {

                switch (event.data.id) {
                    case "gotomylocker":
                        var curCommerce = nike_commerce.mandatoryFlashParams;
                        var targetUrl = "/nikeos/p/nikewomen/" + curCommerce.lang_locale + "/commerce?ll=" + curCommerce.lang_locale + "&ct=" + curCommerce.country + "&p=ML";
                        location.href = targetUrl;
                        // e.g. http://www.nike.com/nikeos/p/nikewomen/en_GB/commerce?ll=en_GB&ct=GB&p=ML
                        break;
                    case "gotoorderstatus":
                        var curCommerce = nike_commerce.mandatoryFlashParams;
                        var targetUrl = "/nikeos/p/nikewomen/" + curCommerce.lang_locale + "/commerce?ll=" + curCommerce.lang_locale + "&ct=" + curCommerce.country + "&p=OS";
                        location.href = targetUrl;
                        // e.g. http://www.nike.com/nikeos/p/nikewomen/en_GB/commerce?ll=en_GB&ct=GB&p=OS
                        break;
                    default:
                        //alert(event.data.id);
                }
            }

            EventBridge.addListener("minicartEventType", nonOSmyLockerObject, "listenerFunction");
        
    },

    addPDPContainer: function (parent, id, x, y) {

        //$(this).parent().prepend('<span id="' + shopidsArray[0] + '" style="position:absolute; z-index:150; top:' + nf.fw.minipdp.containPDPinGrid("top", $(this).position().top) + 'px; left:' + nf.fw.minipdp.containPDPinGrid("left", $(this).position().left) + 'px; width:320px; height:260px; overflow:hidden;" class="miniPDP"><span id="' + shopidsArray[0] + 'inner"></span></span>');
        //nf.fw.minipdp.injectFlashMiniPDP(shopidsArray[0] + "inner", shopidsArray[1], shopidsArray[2], shopidsArray[3]);

        $("#" + parent).append('<div class="FlashPDP" id="' + id + '" style="position:absolute;left:' + nf.fw.minipdp.containPDPinGrid("left", x) + 'px;top:' + nf.fw.minipdp.containPDPinGrid("top", y) + 'px;z-index:400;"><div style="overflow: hidden; width: 320px; height: 260px;"><div id="' + id + '_flash"></div></div></div>');

    },

    containPDPinGrid: function (boundry, position) {

        position = parseInt(position);

        // Dimensions for home page with 10px gutter - will need to pull these out to app level for other implementations
        minLeft = 10;
        minTop = 10;
        maxLeft = 898;
        maxTop = 1100;

        // PDP width 320, height 260
        // Flash object overspill 228 - need to adjust right boundry to cater for this otherwise horizontal scroll bar appears

        // Check position is good...
        var result = position;
        switch (boundry) {
            case "top":

                var h1 = (position - 130);
                if (h1 < minTop) {
                    result = minTop;
                }
                var h2 = (position + 130);
                if (h2 > maxTop) {
                    result = (maxTop - 260);
                }

                if (result == position) {
                    result = (position - 130);
                }

                break;
            case "left":

                var w1 = (position - 160);
                if (w1 < minLeft) {
                    result = minLeft;
                }
                var w2 = (position + 160);
                if (w2 > maxLeft) {
                    result = (maxLeft - 320);
                }

                if (result == position) {
                    result = (position - 160);
                }

                break;
        }

        return result;
    },

    injectFlashMiniPDP: function (moduleElement, catalogId, productGroupId, productId) {
	
        moduleElement = moduleElement + '_flash';

        var flashVars = {};
        var flashParams = {};
        var flashAttributes = {};

        flashVars.locale = nf.gv.locale;

        flashParams.wmode = "transparent";
        flashParams.salign = "tl";
        flashParams.quality = "high";
        flashParams.scale = "noscale ";
        flashParams.allowScriptAccess = "always";
        flashParams.allowFullScreen = "false";
        flashParams.bgColor = "";

        var moduleWidth = "548";
        var moduleHeight = "401";

        var environment = ""
        if (location.href.indexOf("dev.nike.com") != -1) {
            environment = "dev";
        } else if (location.href.indexOf("ecn") != -1) {
            environment = "qa";
        }
        switch (environment) {
            case "dev":
                var modules = "http://dev-modules.nike.com";
                break;
            case "qa":
                var modules = site_data.base_modules_url;
                break;
            default:
                var modules = "http://modules.nike.com";
        }
        var moduleSWF = modules + "/nikestore/modules/web/miniPDP.swf";

        // replace __ with _
        flashVars.locale = nf.gv.locale.replace(/__/, "_");

        flashVars.siteId = "28";
        flashVars.catalogId = catalogId;
        flashVars.country = nike_commerce.mandatoryParams.ct.toUpperCase();
        flashVars.lang_locale = nike_commerce.mandatoryParams.ll;
        flashVars.productGroupId = productGroupId;
        flashVars.productId = productId;
        flashVars.FQDN = modules;
        flashVars.configPath = "/nikewomen/content/framework/v1/modules/minipdp_config.xml";

        flashAttributes.id = moduleElement;
        flashAttributes.name = moduleElement;

        swfobject.embedSWF(moduleSWF, moduleElement, moduleWidth, moduleHeight, "9", flashParams.bgColor, flashVars, flashParams, flashAttributes);

    }
};



/* ----------------------------------------
 * -- A COUPLE OF METHODS THAT NEED TO GO SOMEWHERE. SO PLONKED ON JQUERY FOR THE TIME BEING ---------------
 * ---------------------------------------- */
$.reduce = function(ret, data, func, scope){
	$.each(data, function(key, value){
		ret = func.call(scope, ret, key, value);
	});
	return ret;
};

$.object = function() {
	
	var Func = function(){};
	
	return function(proto, instance){
		var object, callSuper, method;
		Func.prototype = proto;
		Func.prototype.callSuper = function() {
			var origArgs = Array.prototype.shift.call(arguments);
			return origArgs.callee.callSuper.apply(this, arguments);
		};
		object = new Func();
		if (instance) {
			for(method in instance) {
				callSuper = object[method];
				object[method] = instance[method];
				if(typeof callSuper === "function") {
					object[method].callSuper = callSuper;
				}
			}
			
		}
		if(typeof object.__init__ === "function") {
			object.__init__.call(object);
		}
		return object;
	};		

}();

/* ----------------------------------------
 * -- JSON BASED TEMPLATING ---------------
 * ---------------------------------------- */
nf.fw.template = {
	
	__init__: function() {
		this.templates = {};
	},
	
	process: function(template, data, fragment) {
		
		var self = this;
		data = data instanceof Array ? data : [data || {}];
		return $.reduce(fragment || false, data, function(element, i, dataObj){
			var el = self.parseTemplate(self.templates[template].call(self, dataObj));
			if(/document-fragment/.test(element.nodeName)) {
				element.appendChild(el);
			}
			else {
				element = el;
			}
			return element;
		});
	},
	
	include: function(template, data) {
		var self = this;
		return function() {
			return self.process(template, data, document.createDocumentFragment());
		};
	},
		
	parseTemplate: function(block) {
		
		var self = this;

		return $.reduce(false, block, function(element, i, item) {
			if(i === 0) {
				element = document.createElement(item);
			}
			else {
				if(item instanceof Array) {
					element.appendChild(self.parseTemplate(item));
				}
				else if(typeof item === "string") {
					element.appendChild(document.createTextNode(item));
				}
				else if(typeof item === "number") {
					element.appendChild(document.createTextNode("'" + item + "'"));
				}
				else if(typeof item === "function") {
					element.appendChild(item());
				}
				else if(item instanceof Object) {
					$.each(item, function(key, value) {
						if(typeof value === "function") throw "Cannot not attach functions directly.";
						if (key === "class") {
							element.className = value;
						}
						if(key === "style" && element.style.setAttribute) {
							element.style.setAttribute("cssText", value); 						
						}
						else {
							element.setAttribute(key, value);
						}
					});
				}
				else {
					console.log(block + i + ": Non valid data type '" + item + "' specified");
				}
			}
			return element;
		});
		
	},
	
	load: function(templates) {
		$.extend(this.templates, templates);
	}	
};

/* ----------------------------------------
 * -- BASE VIEW OBJECT --------------------
 * ---------------------------------------- */
nf.fw.view = {
	
	fadeTime: 500,
	
	loadTemplates: function(templates) {
		if(!this.hasOwnProperty("templates")) {
			this.templates = $.object(nf.fw.template);
		}
		this.templates.load(templates);
	},

	draw: function(id, html) {
	 	$(html).hide().appendTo($("#" + id)).fadeIn(this.fadeTime);
	}

};

/* ----------------------------------------
 * -- COMMERCE CONTENT SWITCHER ---------------
 * ---------------------------------------- */
nf.fw.commerceContentSwitcher = $.object(nf.fw.view, {

    //    prototype initialisation function
    __init__: function() {
        
		this.html = {};
		
        this.loadTemplates({
            hotspots: function (data) {
				return ["div", {"id" : "hotspotsDiv", "class" : "hotspotPanel"}, this.include("hotspot", data.pdps)];
			},
            hotspot: function(data) {
					if(data.isActive != "false"){
						return ["a", {
									"href" : "#",
									"class" : "trigger hotSpots",
									"style" : "display: block; position: absolute; top:" + data.y + "px; left: " + data.x + "px;",
									"id" : "hotspot_" + data.productId, 
									"data-tracking" : "shop>lookbook>[collection]>[product_name]>pdp>click",
									"data-shopids" : ["minipdp_" + data.productId, nf.gv.catalogId, data.productGroupId, data.productId, data.x, data.y, data.isActive].join("|")
								}
						];
					} else {
						return ["a", {
									"href" : "#",
									"style" : "display: none;",
									"id" : "hotspot_" + data.productId,
									"data-tracking" : "shop>lookbook>[collection]>[product_name]>pdp>click",
									"data-shopids" : ["minipdp_" + data.productId, nf.gv.catalogId, data.productGroupId, data.productId, data.x, data.y, data.isActive].join("|")
								}
						];
					}
			}
        });

    },
  
    //    public init function: call on dom load
    init: function(data) {
        
		this.data = data;
		
		this.images = $.reduce({"lowResImage": {}, "highResImage": {}}, this.data, function(ret, key, product) {
			ret.lowResImage[key] = new Image();
			ret.lowResImage[key].src = product.lowResImage;
			ret.highResImage[key] = new Image();
			ret.highResImage[key].src = product.highResImage;
			return ret;
		});
		
		this.initListeners();
    },
	
	//	
	initListeners: function() {
		
		var self = this;
		$("#" + this.containerId).delegate(".trigger", "click", function(){

			var hotspotData = this.getAttribute("data-shopids").split("|"),
				element = hotspotData[0],
				catalog = hotspotData[1],
				productGroup = hotspotData[2],
				pcatProduct = hotspotData[3],
				x = hotspotData[4],
				y = hotspotData[5],
				isActive = hotspotData[6];
			
			nf.fw.minipdp.addPDPContainer(self.containerId, element, x, y);
			nf.fw.minipdp.injectFlashMiniPDP(element, catalog, productGroup, pcatProduct);

			// Set up pdp tracking
			// track_site taken from global variable set for dalewarth tracking script
			s.prop17 = "shop";
			s.prop18 = "lookbook";
			s.prop19 = document.location.href.substring((document.location.href.lastIndexOf("/")+1),document.location.href.indexOf("?"));
			var trackingString = "shop>lookbook>" + s.prop19 + ">[product_name]>pdp>click";
			trackingString = trackingString.replace("[product_name]", featuredProduct);
			nf.tr.click(track_site + trackingString);
			
			return false;
			
		});
	},

    load: function(id) {
		
		this.switchBgImage(id);
		if($("body").hasClass("hasflash")){
			this.switchHotspots(id);
		}
	},

	switchBgImage: function(id) {

		// Product imagery
		$('div#' + this.containerId).removeClass().addClass(this.data[id].pageTheme);
		$('div#' + this.containerId).css({ "backgroundImage": 'url("' + this.data[id].lowResImage + '")'});//.hide().fadeIn(500);
		$('img#highResImage').attr("src", this.data[id].highResImage);
		
		if($("img#highResImage").attr("complete") != "true"){
 			$("img#highResImage").fadeIn(500);
		}
		else {
			$("img#highResImage").bind("load",function() {
				$("img#highResImage").fadeIn(500);
			});
		}
		
		var theme = $('div#m_athlete_content').attr('class');
		if( theme == 'white' ){
			Cufon.replace('h2.strapline span', { fontFamily: nf.fw.fonts.header, color: '#ffffff' });
			Cufon.replace('#athleteLooks h3, #athleteNav h3, #m_feature h3', { fontFamily: nf.fw.fonts.header, color: '#ffffff' });
			//Cufon.replace('#athlete p.subStrapline',	{ fontFamily: nf.fw.fonts.body, color: '#ffffff' });
			Cufon.replace('#athlete p.subStrapline', { fontFamily: nf.fw.fonts.header_specific, color: '#ffffff' });
			Cufon.replace('.featureHeading', { fontFamily: nf.fw.fonts.header_specific, color: '#ffffff' });	
			Cufon.replace('p.desc, .fbFanCopyName, .fbFanCopyComment, .fbFanCopyLink a, .featureStrapline', { fontFamily: nf.fw.fonts.body, color: '#ffffff' });			
		}
		if( theme == 'black' ){
			Cufon.replace('h2.strapline span', { fontFamily: nf.fw.fonts.header, color: '#000000' });
			Cufon.replace('#athleteLooks h3, #athleteNav h3, #m_feature h3', { fontFamily: nf.fw.fonts.header, color: '#000000' });
			//Cufon.replace('#athlete p.subStrapline',	{ fontFamily: nf.fw.fonts.body, color: '#000000' });
			Cufon.replace('#athlete p.subStrapline', { fontFamily: nf.fw.fonts.header_specific, color: '#000000' });
			Cufon.replace('.featureHeading', { fontFamily: nf.fw.fonts.header_specific, color: '#000000' });			
			Cufon.replace('p.desc, .fbFanCopyName, .fbFanCopyComment, .fbFanCopyLink a, .featureStrapline', { fontFamily: nf.fw.fonts.body, color: '#000000' });
		}
		//Cufon.replace('.athleteName', { fontFamily: nf.fw.fonts.body });
		nf.product.CountTouts();

    },
    
    switchHotspots: function(id) {
		
		$("#hotspotsDiv").remove();
		
		if(typeof this.data[id].pdps !== "undefined") {
			if (typeof this.html["hotspots_" + id] === "undefined") {
				this.html["hotspots_" + id] = this.templates.process("hotspots", this.data[id]);
			}
			this.draw(this.containerId, this.html["hotspots_" + id]);
		}
		
    }
});


/* ----------------------------------------
 * -- NON COMMERCE CONTENT SWITCHER -----------
 * ---------------------------------------- */
nf.fw.nonCommerceContentSwitcher = $.object(nf.fw.commerceContentSwitcher , {

    __init__: function() {
        
        this.callSuper(arguments);

        this.loadTemplates({
            
			hotspots: function (data) {
				return ["div", {"id" : "hotspotsDiv", "class" : "hotspotPanel"}, this.include("hotspot", data.pdps), this.include("tooltip", data.pdps)];
			},
            tooltip: function(data) {
				return ["div", {
							"class": "tooltip", 
							"id" : "hotspotDetails_" + data.productId, 
							"style" : "position:absolute;"
						}, 
						["p", {"class": "title"}, data.productName],
						["p", {"class": "storeLocation"}, 
							["a", {"href" : data.storeLink.url}, data.storeLink.title] 
						]
					];
			}
        });

    },
	
	initListeners: function() {
		
		$("#" + this.containerId).delegate(".trigger", "click", function(index){

			var product_id = this.id.split('_')[1];

			var anchor = $("#hotspot_" + product_id);;
			var divToToggle = $("#hotspotDetails_" + product_id);

			var triggerLeft = parseInt(anchor.css('left').replace("px",""));
			var triggerTop = parseInt(anchor.css('top').replace("px",""));
			
			Cufon.replace('.tooltip p.title, .tooltip p.storeLocation a', { fontFamily: nf.fw.fonts.body });
			
			divToToggle.css({
				"top": ((((triggerLeft+12) - divToToggle.outerWidth()) > 5) ? (triggerTop - 40) : (triggerTop - 80) ) + 'px',
				"left": ((((triggerLeft+12) - divToToggle.outerWidth()) > 5) ? ((triggerLeft+12) - divToToggle.outerWidth()) : 5 ) + 'px'
			});
			
			var divState = $(divToToggle).css('display');
			if (divState == 'block'){
				$(divToToggle).slideUp('fast');
			} else {
				$(divToToggle).slideDown('fast');
			}
			divToToggle.fadeTo("fast", 0.9);

			// Set up pdp tracking
			// track_site taken from global variable set for dalewarth tracking script
			s.prop17 = "shop";
			s.prop18 = "lookbook";
			s.prop19 = document.location.href.substring((document.location.href.lastIndexOf("/")+1),document.location.href.indexOf("?"));
			var trackingString = "shop>lookbook>" + s.prop19 + ">[product_name]>pdp>click";
			trackingString = trackingString.replace("[product_name]", featuredProduct);
			nf.tr.click(track_site + trackingString);
			
			return false;
			
		});
	}


});



// ----------------------------------------
// -- DOM READY ---------------------------
// ----------------------------------------
$(function() {

	/* ----------------------------------------
	 * -- ADD CSS FLAG FOR SCRIPT SUPPORT -----
	 * ---------------------------------------- */
	$("body").addClass("jsison");
	
	/* ----------------------------------------
	 * -- ADD CSS FLAG FOR FLASH SUPPORT ------
	 * ---------------------------------------- */
	if(nf.gv.hasflash){
		$("body").addClass("hasflash");
	}
	
	// Move content stub to footer
	nf.fw.setUpContentStub();
	
	// Configure video support
	nf.fw.videos.init();
	
	// Cufon
	//nf.fw.goCufon();
	
	
	/* ----------------------------------------
	 * -- FIX FOR IPAD BACKGROUND SCALING -----
	 * ---------------------------------------- */
	var IsiPhone = navigator.userAgent.indexOf("iPhone") != -1 ;
	var IsiPod = navigator.userAgent.indexOf("iPod") != -1 ;
	var IsiPad = navigator.userAgent.indexOf("iPad") != -1 ;

	var IsiPhoneOS = IsiPhone || IsiPad || IsiPod ;

	if(IsiPhoneOS){
		$("body").css("-webkit-background-size","2850px 1248px")
	}
	
		
	//a solution for problems with the background repeat
	if ($('#p_outermostwrapper').height() < $(window).height()){
		$('#p_outermostwrapper, body, html').height($(window).height());	
	}else{
		if($.browser.msie){
			$("#p_outermostwrapper, body, html").height($('#p_outermostwrapper').height() + 10); //Fixing an issue in IE where extra pixels were being cut off without background
		}
	}
	$(window).resize(function() {
		if ($('#p_outermostwrapper').height() < $(window).height()){
			$('#p_outermostwrapper, body, html').height($(window).height());
			
		}
	});

	

});


// ----------------------------------------
// -- PAGE LOADED -------------------------
// ----------------------------------------
$(window).load(function() {
	
	$("noscript").remove();
	
	nf.tr.init(); // Set up tracking wrapper (including nav and footer links)
	
	if($("body").hasClass("hasflash")){
		nf.fw.minipdp.init(); // Set up event listeners for mini PDP
	}
	
	if(!($("body").hasClass("hasflash"))){
		$('div.ShowIfNoFlash').css({'margin-left':'-112px'});
	}

//nf.fw.videos.showVideoInOverlay("2b982a5d-b912-1e10-57b7-8f628915946f_id1368153");


// Used for testing NikeOS flash components
/*
var customObject = {};
customObject.listenerFunction = function(event){

        //alert("id="+event.data.id);
}

EventBridge.addListener("url", customObject, "listenerFunction");
*/
/*
var clickEvents = $(".featureUnit .toutLink").data("events").click;
jQuery.each(clickEvents, function(key, handlerObj) {
	alert(handlerObj.handler) // alerts "function() { alert('clicked!') }"
});
*/

});

/* ----------------------------------------
 * -- BROWSER RE-SIZED --------------------
 * ---------------------------------------- */
//
/*
 *  Resize event was being fired multiple times in IE6, even if the window was not being resized.
 *  Nick added a logic that checks if the window dimensions really changed.
*/
var windowSize = [$(window).width(),$(window).height()];
$(window).resize(function() {

	/* ----------------------------------------
	 * -- ADJUST VIDEO OVERLAY POSITION -------
	 * ---------------------------------------- */
	
	var newWindowSize = [$(window).width(),$(window).height()];
	if (windowSize[0] != newWindowSize[0] || windowSize[1] != newWindowSize[1]) {
		nf.fw.videos.placement();
		windowSize = newWindowSize;
	}
	
});

// ----------------------------------------
// -- PAGE UN-LOADED ----------------------
// ----------------------------------------
$(window).unload(function() {
	$("*").unbind();
	nf = null;						// Nike Football/Women Namespace
	$ = null;						// JQuery
	JQ = null;						// JQuery
	jQuery = null;					// JQuery
	swfobject = null;				// SWFOject 2
	deconcept = null;				// SWFObject 1.5 override
	tracking = null;				// Framework Tracking Object
	NIKEOS = null;					// NIKEOS Object
	BrowserDetect = null;			// PPK browser detection
	EventBridge = null;				// Flash Event Bridge
	Cufon = null;					// Cufon
	CallbackManager = null;			// Proxy callback manager
	DaleWarth = null;				// Nike Tracking Object
	nike_commerce = null;			// Nike Commerce Object
	NIKE_COMMERCE_CONFIG = null;	// Nike Commerce Config Object
	s = null						// Omniture Tracking Object
	site_data = null;				// Nike site_data
	XMLHttpRequest = null;			// Destroy any outstanding AJAX calls
});



