var tunnel=new LanguageTunnel();	

JQ(function(){
	JQ('a').each(function(){
		if (JQ(this).attr('href')=='#'){
			JQ(this).attr('href', 'javascript:void(0);');
		}
	});
});
		
function LanguageTunnel()
{
	var self=this;
	this.preInit=function()
	{
		self.path='/';
		
		self.date=new Date();
		self.date.setTime(self.date.getTime()+3600000*24*365);
		
		self.getParams();
		self.mergeConfigs();
		self.handleCookies();
	}
	this.init=function()
	{
		self.preloadImages();
		self.container=JQ('#tunnel_container');
		self.render();
		if(typeof afterGlobalGatewayRenders=='function')
			afterGlobalGatewayRenders();
	}
	this.preloadImages=function()
	{
		for(var p in self.config.images)
			JQ('body').append("<img src=\""+self.config.images[p]+"\" style=\"display:none;\"/>");
	}
	this.render=function()
	{
		//--resize container to match background image
		self.container.css(
		{
			height:self.config.style.height+"px",
			width:self.config.style.width+"px",
			background:"url("+self.config.images.tunnel_bg+") no-repeat right bottom"
		});
		
		//--add floater div
		JQ('body').append("<div id=\"tunnel_floater\"></div>");
		self.floater=JQ('div#tunnel_floater');
		
		//--add logo
		self.container.append("<div id=\"tunnel_logo\"><img src=\""+self.config.images.logo+"\" /></div>");
		
		//--add languages
		self.container.append("<div id=\"language_wrapper\"></div>");
		self.language_wrapper=self.container.find('#language_wrapper');
		JQ.each(self.config.region,function()
		{
			var id="lang_bg_"+Math.floor(Math.random()*10000000);
			var _class="";
			if(typeof this._class=='string')
				_class=" "+this._class+"_region";
			var str="";
				str+="<div class=\"language_button_wrapper"+_class+"\">";
				str+="	<img src=\""+((this.countries.length==1)?self.config.images.lang_button_bg_arrowless:self.config.images.lang_button_bg)+"\" class=\"language_button_bg\" id=\""+id+"\" />"
				str+="	<div class=\"language_button\">"+this.display+"</div>";
				str+="</div>";
			self.language_wrapper.append(str);
			self.language_wrapper.find('#'+id).parent().data("countries",this.countries);
		});
		
		//--activate language buttons
		self.container.find('div.language_button_wrapper').each(function()
		{
			var background=JQ(this).find('img.language_button_bg');
			background.css('opacity','0');
			var others=JQ(this).find('img.language_button_bg').not('#'+JQ(this).attr('id')).parent();
			var animLength=150;
			JQ(this).css('cursor', 'pointer');
			if (JQ(this).data('countries').length==1) {
				JQ(this).click(function(){
					self.loadCookies(JQ(this).data('countries')[0]);
				});
				JQ(this).hover(function()
				{
					JQ(this).addClass('hover');
					//--deactivate others
					self.container.find('div.language_button_wrapper.active').removeClass('active');
					//--activate this
					JQ(this).addClass('active');
					background.css({opacity:1});
					
					self.container.find('div.language_button_wrapper').not('.active').find('img.language_button_bg').css({opacity:0});
					
					self.floater.html('');
				},function()
				{
					JQ(this).removeClass('hover');
				});	
			} else {
				JQ(this).hover(function()
				{
					JQ(this).addClass('hover');
					//--deactivate others
					self.container.find('div.language_button_wrapper.active').removeClass('active');
					//--activate this
					JQ(this).addClass('active');
					background.css({opacity:1});
					
					self.container.find('div.language_button_wrapper').not('.active').find('img.language_button_bg').css({opacity:0});
					
					//--build flyout
					self.renderFlyOut(	JQ(this)	);
				},function()
				{
					JQ(this).removeClass('hover');
				});	
			}
		});
	}
	this.renderFlyOut=function(node)
	{
		//--grab countries
		var countries=node.data("countries");
		//--position flyout
		self.floater.css(
		{
			position:'absolute',
			top:node.offset().top,
			left:node.offset().left+220
		});
		if (JQ(countries).length > 10) {
			var str= "";
			str+="<div class=\"floater_wrapper active wide\" style=\"width:400px;background:url("+self.config.images.floater_bg_wide+") repeat-y;\" >";
			str+="	<div class=\"floater_bottom_wrapper\" style=\"width:400px;background:url("+self.config.images.floater_bottom_wide+") no-repeat left bottom;\">";
			str+="		<div class=\"floater_top\" style=\"width:400px;background:url("+self.config.images.floater_top_wide+") no-repeat left top;\">";
			str+="			<div class=\"floater_content\" style=\"float:left;\" ></div>";
			str+="			<div class=\"floater_content2\" ></div>";
			str+="			<div class=\"floater_content_clear\" >&nbsp;</div>";
			str+="		</div>";
			str+="	</div>";
			str+="</div>";
			self.floater.html(str);
			
			var half = Math.ceil(JQ(countries).length / 2);
			var container = "div.floater_content";
			JQ.each(countries,function(){
				if (--half == -1) container = "div.floater_content2";
				var str="<div class=\"country\">";
				str+="	<a href=\"#\" >"+this.display+"</a>";
				str+="</div>";
				self.floater.find(container).append(str);
				self.floater.find(container + ' div.country:last a').data('country',this);
			});
		} else {
			var str= "";
			str+="<div class=\"floater_wrapper narrow active\" style=\"width:200px;background:url("+self.config.images.floater_bg+") repeat-y;\" >";
			str+="	<div class=\"floater_bottom_wrapper\" style=\"width:200px; background:url("+self.config.images.floater_bottom+") no-repeat left bottom;\">";
			str+="		<div class=\"floater_top\" style=\"width:200px;background:url("+self.config.images.floater_top+") no-repeat left top;\">";
			str+="			<div class=\"floater_content\" ></div>";
			str+="		</div>";
			str+="	</div>";
			str+="</div>";
			self.floater.html(str);
			JQ.each(countries,function()
			{
				var str="<div class=\"country\">";
				str+="	<a href=\"#\" >"+this.display+"</a>";
				str+="</div>";
				self.floater.find('div.floater_content').append(str);
				self.floater.find('div.floater_content div.country:last a').data('country',this);
			});
		}

		
		//--activate flyout:
		var animLength=50;
		self.floater.find('div.country a').css('color',self.config.style.countryColor);
		//self.floater.find('div.country:last').css('overflow','hidden');
		self.floater.find('div.country img').css('opacity',0);
		self.floater.find('div.country').each(function()
		{
			JQ(this).find('a').click(function()
			{
				var data=JQ(this).data('country');
				self.loadCookies(data);
				return false;
			});
		});
	}
	this.mergeConfigs=function()
	{
		var defaultConfig=
		{
			cookies:['NIKE_LANG_LOCALE','NIKE_COUNTRY','NIKE_COMMERCE_COUNTRY','NIKE_COMMERCE_LANG_LOCALE'],
			style:
			{
				width:999,
				height:666,
				floater_top:22,
				countryColor:"e9e6e2",
				countryHoverColor:"605e5b",
				langColor:"ffffff"
			},
			images:
			{
				logo:"/nikeos/global/image/global_gateway/tunnel_logo.jpg",
				lang_button_bg:"/nikeos/global/image/global_gateway/button_background.jpg",
				tunnel_bg:"/nikeos/global/image/global_gateway/tunnel_bg.jpg",
				floater_bg:"/nikeos/global/image/global_gateway/tunnel_floater_bg.jpg",
				floater_top:"/nikeos/global/image/global_gateway/tunnel_floater_top.jpg",
				floater_bottom:"/nikeos/global/image/global_gateway/tunnel_floater_bottom.jpg",
				country_hover_bg:"/nikeos/global/image/global_gateway/country_hover_bg.jpg"
			},
			region:[]
		};
		if(typeof NIKE_TUNNEL_CONFIG != 'undefined')
			self.config=JQ.extend(true,{},defaultConfig,NIKE_TUNNEL_CONFIG);
		else
			self.config=defaultConfig;
			
				
		var j,temp;
		for(var i=0;i<self.config.region.length;i++)
		{
			if(self.config.region[i].countries.constructor!=Array)
			{
				temp=self.config.region[i].countries;
				self.config.region[i].countries=[];
				self.config.region[i].countries[0]=temp;
			}
		}	
	}
	this.handleCookies=function()
	{
		self.hasAllCookies=true;
		self.cookies=[];
		var temp;
		JQ.each(self.config.cookies,function()
		{
			temp=JQ.cookie(this);
			if(!temp)
				self.hasAllCookies=false;
			else
				self.cookies[this]=temp;
		});
		if(self.hasAllCookies && location.search.indexOf("?change")==-1)
			return self.leave();
		JQ(function()
		{
			setTimeout(self.init, 0);
		});
	}
	this.loadCookies=function(data)
	{
		if(typeof data.LINK != "undefined")
		{
			self.cookies=data;
			if(typeof self.cookies != "undefined")
			{
				for(var p in data)
				{
					if(p!="display"&&p!="tracking_value" && p!="COOKIES")
						JQ.cookie(p, data[p],{ expires: self.date, path: self.path, domain: self.getDomain()});
				}
			}
			self.leave();
			return;
		}
		
		for(var p in data)
		{
			if(p!="display"&&p!="tracking_value" && p!="COOKIES")
				JQ.cookie(p, data[p],{ expires: self.date, path: self.path, domain: self.getDomain()});
		}
		self.cookies=data;
		self.trackClick(data.tracking_value);
		self.leave();
	}
	this.leave=function()
	{
		
		var regions=self.config.region;
		var j,countries,link=false;
		for(var i=0;i<regions.length;i++)
		{
			countries=regions[i].countries;
			for(j=0;j<countries.length;j++)
			{
				if(countries[j].NIKE_COUNTRY==self.cookies.NIKE_COUNTRY && countries[j].NIKE_LANG_LOCALE==self.cookies.NIKE_LANG_LOCALE)
				{
					if(typeof countries[j].LINK !='undefined')
					{
						link=countries[j].LINK;
						if(typeof leaveGatewayOverwrite=='function')
							return leaveGatewayOverwrite(link);
						location.href=link;
						return;
					}
				}
			}
		}
		if(typeof leaveGatewayOverwrite=='function')
			return leaveGatewayOverwrite(self.getURL());
		document.location.href=self.getURL();
	}
	this.trackClick=function(val)
	{
		tracking.click({pageName:track_site+'>language_tunnel>'+val});
	}
	this.getParams=function()
	{
		self.continueURL=getParam('continueURL','query_string');
	}
	this.getURL=function(url)
	{
		var	baseURL="/nikefootball"
		var	selectedURL=baseURL+"/home/";
		var	localeParameter="locale="+self.cookies.NIKE_LANG_LOCALE;
		
		if( (self.cookies.NIKE_LANG_LOCALE=="es_LATM")) {
            localeParameter="locale=es__LATM";
		}
		
		var returnURL=selectedURL;
		
		if (self.continueURL != "undefined" && self.continueURL != "") {
            if(self.continueURL.indexOf(baseURL) != 0) {
                returnURL = baseURL+"/"+self.continueURL;
            } else {
                returnURL = self.continueURL;                 
            }

			if (returnURL.indexOf(selectedURL) < 0) {
				returnURL = selectedURL;
			}
		}
		
		if(localeParameter != "") {
			returnURL=returnURL+"?"+localeParameter;
		}			
		
	if((self.cookies.NIKE_LANG_LOCALE=="vi_VN") ||
    (self.cookies.NIKE_LANG_LOCALE=="ja_JP")) {
		
		baseURL="/nikeos/p/"+self.config.site;
		selectedURL=baseURL+"/"+self.cookies.NIKE_LANG_LOCALE+"/";
		localeParameter="";    
		returnURL = selectedURL;
    }
		
		return returnURL;
	}
	this.getDomain=function()
	{
		var d='';
		if (location.href.toString().indexOf('nike.com')>=0) d='nike.com';
		else if (location.href.toString().indexOf('rga.com')>=0) d='rga.com';
		return d;
	}
	self.preInit();
}

function getParam(x,location)
{
	var url=window.location.href;
	if (url.indexOf('#') >= 0) {
		if(location=='query_string')
			url=url.substring(0,url.indexOf('#'));
		else if(location=='hash')
			url=url.substring(url.indexOf('#'),url.length);
	}
	x=x.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS="[\\?&]"+x+"=([^&#]*)";
	var regex=new RegExp(regexS);
	var results=regex.exec(url);
	if(results==null)
		return "";
	else
		return results[1];
}