/*
	Nike 6.0 Common JavaScript Library
	Author: Scott Kyle
*/

(function($){
	
	// GLOBAL NIKE 6.0 OBJECT

	var embedded = {};	// embedded flash modules
	var delayed = {};	// delayed flash modules
	var $overlay;		// loading ajax page overlay
	
	this.Nike6 = $.extend(this.Nike6 || {}, {
		
		delay: function(id){
			delayed[id] = true;
		},
		
		embed: function(options, more){
			if (options.src && (/(jpe?g|gif|png)$/i).test(options.src))
				return Nike6.embedImage(options, more);
			else
				return Nike6.embedSWF(options, more);
		},
		
		embedSWF: function(options, more){
			if (typeof options == 'string'){
				var id = options;
				delete delayed[id];
				options = embedded[id];
				if (!options) return null;
			}
			
			options = $.extend(true, {
				src: '',
				element_id: 'feature',
				queries: 'param_'
			}, options, more);
			
			if (options.src.charAt(0) == '/' && Nike6.onBlog())
				options.src = site_data.base_url + options.src;
			
			var id = options.element_id;
			embedded[id] = options;

			return delayed[id] ? null : NIKEOS.insertSWF(options) ? Nike6.getSWF(id) : Nike6.noFlash(id);
		},
		
		embedImage: function(options, more){
			if (typeof options == 'string') options = {src: options};
			options = $.extend({}, options, more);
			
			var $el = $('#' + (options.element_id || 'feature')).empty();
			delete options.element_id;
			
			var $img = $('<img />');
			for (var attr in options) $img.attr(attr, options[attr]);
			
			return $img.appendTo($el);
		},
		
		getSWF: function(id){
			id = $('#' + id).find('embed, object').attr('id');
			return $.browser.msie ? window[id] : document[id];
		},
		
		noFlash: function(id){
			if (id == 'feature') $('#feature .no-flash').show();
			return null;
		},
		
		changeNav: function(label){
			if (label) site_data.nav_current = label;
			return Nike6.embed('nav-module-left', {vars: {
				currentNav: site_data.nav_current
			}});
		},
		
		onBlog: function(){
			return location.href.indexOf(site_data.blog_base_url) != 1;	
		},
		
		params: function(url, param){
			url = (url || window.location.search).replace(/.*?\?/, '');
			if (!url) return null;
			
			var result = {};
			var args = url.split("&");
			for (var i = 0; i < args.length; i++){
				var keys = args[i].split("=");
				result[keys[0]] = decodeURIComponent(keys[1]) || '';
			}
			return param ? result[param] : result;
		},
		
		hashChange: function(callback){
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE, callback);
		},
		
		scroll: function(to){
			$('html, body').animate({scrollTop: to || 0});
		},
		
		overlay: function(on, speed){
			if (!$overlay)
				$overlay = $('<div class="loading-overlay" />').hide().css('opacity', 0.5).appendTo('#content-container');
			$overlay.fadeTo(speed || 200, on ? 'show' : 'hide');
		},
		
		NewsFeed: function(){
			var $newsfeed = $('#newsFeed');
			if (!$newsfeed.length || !$.NewsFeed) return null;
			
			return new $.NewsFeed({
				container: $newsfeed,
				newsItems: $newsfeed.find('li.newsItem'),
				list: $newsfeed.find('ul'),
				limit: $newsfeed.hasClass('tall') ? 5 : 3
			});
		},
		
		// accepts a pageName tag that with different behavior if it starts with '>' or '<'
		track: function(tag, click){
			if (!tag) {
				return;
			} else if (typeof tag == 'object'){
				var obj = tag;
				tag = obj.pageName;
			} else {
				var obj = {};
			}
			
			// action tags
			if (tag.indexOf('NAS') == 0){
				JQ("<img src='http://view.atdmt.com/action/" + tag + "'/>").insertAfter("body");
				//new Image().src = 'http://view.atdmt.com/action/' + tag;
				return;
			}
			
			var first = tag.charAt(0);
			if (first == '>') tag = page_tracker_obj.pageName + tag;
			else if (first == '<') tag = page_tracker_obj.pageName.replace(/[^>]+>[^>]+$/, tag.slice(1));
			else tag = page_tracker_obj.pageName.replace(/[^>]+$/, tag);
			
			obj.pageName = tag;
			if (click) tracking.click_track(tag);
			else tracking.click($.extend({}, page_tracker_obj, obj));
		},
		
		setTitle: function(title){
			title = site_data.site_title + (title ? ' - ' + title : '');
			if (window.SWFAddress) SWFAddress.setTitle(title);
			else document.title = title;
		},
		
		popup: function(url, name, options){
			options = $.extend({
				toolbar: 0, status: 0, scrollbars: 1, location: 0, resizable: 0, menubar: 0, toolbar: 0
			}, options);
			return window.open(url, name, $.param(options).replace(/&/g, ','));
		}
		
	});

	var fetches = {};		// cached nodes
	var retrieved = {};		// retrieval timestamps
	var fetch_timer;		// like it sounds
	
	// jQuery extensions
	$.fn.extend({
		
		// Fetch and cache HTML
		fetch: function(url, data, callback, once){
			if (typeof data == 'function'){
				once = callback;
				callback = data;
				data = null;
			}
			if (data) url += '?' + $.param(data);
			
			// delete 5 minute old cached nodes every minute
			if (!fetch_timer) fetch_timer = setInterval(function(){
				var now = +new Date;
				for (var url in retrieved){
					if (now - retrieved[url] < 300000) continue;
					delete retrieved[url];
					delete fetches[url];
				}
			}, 60000);
			
			if (fetches[url]){
				this.empty().append(fetches[url]);
				return (callback) ? this.each(callback) : this;
			}
			
			return this.load(url, function(){
				fetches[url] = $(this).contents();
				retrieved[url] = +new Date;
				if (callback) callback.call(this);
				if (once)	  once.call(this);
			});
		},
		
		// fast event delegation
		delegate: function(type, rules){
			return this.bind(type, function(e){
				for (var selector in rules){
					for (var t = e.target; t && t != this; t = t.parentNode){
						if ($.multiFilter(selector, [t]).length){
							rules[selector].apply(t, arguments);
							break;
						}
					}
				}
			});
		},
		
		// click tracking, can take delagation object, callback function(s), or strings
		track: function(tag, click){
			var fire = function(tag){
				if (typeof tag == 'function') tag = tag.call(this);
				if (tag) Nike6.track(tag, click);
			};
			
			if (typeof tag == 'object'){
				var rules = {};
				$.each(tag, function(sel, tag){
					rules[sel] = function(){ fire.call(this, tag); };
				});
				return this.delegate('click', rules);
			} else {
				return this.click(function(){
					fire.call(this, tag);
				});
			}
		},
		
		// Crossfade on rollover
		hoverFade: function(speed){
			var $hidden = $('<div />').hide().appendTo('body');
			
			this.filter('img').each(function(){
				var $over = $('<img />').attr('src', this.src.replace(/\.(\w+)$/, '_on.$1')).css({
					position : 'absolute',
					zIndex : -1
				}).appendTo($hidden);
				
				var $this = $(this).hover(
					function(){
						var pos = $this.position();
						$over.css({
							top : pos.top,
							left : pos.left
						}).insertBefore($this);
						$this.fade('out', speed);
					},
					function(){
						$this.fade('in', speed, function(){
							$over.remove();
						});
					}
				);
			});
			return this;
		},
		
		// IE and Chrome 1 can't fade PNGs :-(
		cannotFade: function(){
			if (($.browser.chrome && $.browser.version < 2) || ($.browser.msie)){
				var data = this.data('cannotFade');
				if (data != null) return data;
				
				var png = false;	// chrome and IE can't fade transparent pngs
				this.find('*').andSelf().each(function(){
					if (/\.png/i.test(this.tagName == 'IMG' ? this.src : $(this).css('background-image'))){
						png = true;
						return false;
					}
				});
				this.data('cannotFade', png);
				return png;
			}
			return false;
		},
		
		// better fade
		fade: function(o, speed, callback, queue){
			o = (o == 'in') ? 1 :
				(o == 'out') ? 0 : o;
			
			if (typeof speed == 'function'){
				if (callback) queue = callback;
				callback = speed;
				speed = null;
			}
			
			var complete = function(){
				if (callback) callback.call(this);
			};
			
			// neither IE nor Chrome can handle setting opacities on transparent PNGs...
			if (this.cannotFade()){
				if (/show|hide|toggle/.test(o)) this[o]();
				else this.css('visibility', o ? 'visible' : 'hidden');
				complete();
			} else {
				if (!queue) this.stop();
				if (o && this.css('visibility') == 'hidden') this.css({
					visibility: 'visible',
					opacity: 0
				});
				this.animate({ opacity: o }, speed || 400, 'swing', complete);
			}
			return this;
		},
		
		// CSS hack machine
		browserDetect: function(){
			if (window.BrowserDetect){
				var browser = BrowserDetect.browser == 'Explorer' ? 'IE' : BrowserDetect.browser;	// new version uses IE, protection from the future
				var version = BrowserDetect.version.toFixed(0);		// I don't like decimals in classes
				this.addClass((browser + ' ' + browser + version + ' ' + BrowserDetect.OS).toLowerCase());
			}
			return this;
		}
		
	});
	
	// add chrome to jQuery browser test
	var chrome = $.browser.chrome = /chrome/i.test(navigator.userAgent);
	if (chrome) $.browser.version = navigator.userAgent.match(/chrome\/(\d+)/i)[1];
	
	// Tracking hack to track all countries using their cookies (not needed until other langs come out)
	//var countryToTrack = $.cookie('NIKE_COUNTRY') || "us";
	//tracker_obj.prop14 = countryToTrack.toLowerCase();
	
	$(function(){
		
		// add Chrome to BrowserDetect
		if (chrome && window.BrowserDetect){
			BrowserDetect.browser = 'Chrome';
			BrowserDetect.version = +$.browser.version;
		}
		
		// just in case it's needed somewhere...
		$(document.body).browserDetect();

		// Fire an action tag, if there is one
		// This has been relocated to templates/fragments/jsincludes.html
		//Nike6.track(site_data.action_tag);
		
		// init NewsFeed module
		new Nike6.NewsFeed;
		
		// make Privacy link into popup
		$('#footer_link_privacy').click(function(){
			var win = Nike6.popup(this.href, 'privacy', {height: 654, width: 574});
			if (win) win.focus();
			else window.location = this.href;
			return false;
		});
		
		// Crossfade on hover-fade touts
		$('img.hover-fade, .hover-fade img').hoverFade(600);
		
		
		// NAV MODULE
		
		// adjust SEO links before Nav is embedded
		$('#nav a[type=ajax]').each(function(){
			this.href = this.href.replace('?', '#').replace(/&?\w+=/g, '/');
		});
		
		// allows for hash changing (works around bugs in the Nav)
		navListener.openURL = function(event){
			if (window.location.href == event.data.href)
				window.location.reload();
			else
				window.location = event.data.href;
		};
		navListener.openAJAX = function(event){
			if (window.location.href.indexOf(event.data.href) == 0)
				Nike6.changeNav(event.data.tracking[1]);
			window.location = event.data.href;
		};
		EventBridge.addListener('url', navListener, 'openURL');
		EventBridge.addListener('ajax', navListener, 'openAJAX');
		
		Nike6.embed({
			element_id: 'nav-module-top',
			type: 'lockup',
			version: 'v1.2',
			width: 257,
			height: 61,
			vars: {
				id: 'nav_module_top_swf',
				locale: site_data.platypus_region,
				stylePath: site_data.base_url + site_data.nav_style_path,
				siteXML: innerXHTML('site', true)
			}
		});

		Nike6.embed({
			element_id: 'nav-module-left',
			type: 'nav',
			version: 'v1.2',
			width: 102,
			height: 500,
			vars: {
				id: 'nav_module_left_swf',
				locale: site_data.platypus_region,
				stylePath: site_data.base_url + site_data.nav_style_path,
				currentNav: site_data.nav_current,
				navXML: innerXHTML('nav', true)
			}
		}) || $('#nav, #site').show();
		
		ready = true;
		
	});
	
	var ready = false;
	this.isReady = function(){ return ready; };
	this.setMenuArea = function(id, width, height){
		$('#' + id).width(width + 'px').height(height + 'px');
	};
	
	// crazy idea, that works
	var Sizzle = $.find;
	$.find = function(selector, context, results, seed){
		if (typeof selector == 'string')
			selector = selector.replace(/\[@/g, '[');
		return Sizzle.call(this, selector, context, results, seed);
	};
	
	// crazy fix to once and for all plug a horrible firefox 3 error
	// where at one point a DOM element returns a huge number as its
	// length, when it should be undefined
	$.makeArray = function( array ) {
		var ret = [];
	
		if( array != null ){
			var i = array.length;
			// The window, strings (and functions) also have 'length'
			if( i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval || array.nodeType )
				ret[0] = array;
			else
				while( i )
					ret[--i] = array[i];
		}
	
		return ret;
	};
	
})(jQuery);
