
var WWWServerPath = "http://www.lululemon.com"; //*** put in absolute path to CDN
var ShopServerPath = "http://shop.lululemon.com";
var imgServer = "http://images.lululemon.com/is/image/lululemon";//http://lululemon-o.scene7.com
var searchServer = "http://search.lululemon.com";
var JSONPath = ShopServerPath + "/elements/navigation_json.jsp";


$(document).ready(function() {


//*** load nav and setup cookie values.
if(!Modernizr.localstorage  || (typeof amplify.store.sessionStorage("megaNav")=="undefined") || (typeof amplify.store.sessionStorage("footer")=="undefined") || (amplify.store.sessionStorage("region") != getUsrLocale()))
	{
		//*** get the content, save it to the cache and publish it.
		showNavDefault();
		showFooterDefault();
		getExternalContent(JSONPath,errorCallBack); 
			
	}else{
		//*** public out of local storage
			//alert("cache");
			setupUtilBar();
			publishMegaMenu(amplify.store.sessionStorage("megaNav"));
			setupMegaNav();
			publishFooter(amplify.store.sessionStorage("footer"));
			setupFooter();
	}


//*** Util Bar
	function openSubMenu() {
		jQuery(this).find('div').prev().addClass('on');
		jQuery(this).find('div').show();
	};
	function closeSubMenu() {
		jQuery(this).find('div').prev().removeClass('on');
		jQuery(this).find('div').hide();
	};
	
	jQuery('.utilityMenu > li').live('mouseover', openSubMenu);
	jQuery('.utilityMenu > li').live('mouseout', closeSubMenu);
	

	jQuery('#regionSelector').live('mouseover', showRegionChangeBox);
	jQuery('.utilitySubMenu').live('mouseout', hideRegionChangeBox);
	jQuery('#regionSelector').live('click', swapRegionChangeBox);

// *** MEGA-NAV
	function openSubNav() {
		jQuery(this).addClass('on');
		jQuery(this).find('.mnSubMenu').show();
	};
	function closeSubNav() {
		jQuery(this).removeClass('on');
		jQuery(this).find('.mnSubMenu').hide();
	};
	jQuery('#NAV li.mnMain').live('mouseover', openSubNav);
	jQuery('#NAV li.mnMain').live('mouseout', closeSubNav);


// *** SEARCH

jQuery('#search').live('click', function() {
		if(jQuery('#searchField').is( ":focus" )==false){
			submitSearch();
		}
	});

	jQuery('#searchField').live('focus', function() {
		if(jQuery(this).val() == 'search') {
			jQuery(this).val('');
		}
	});
	jQuery('#searchField').live('blur', function() {
		if(jQuery(this).val() == '') {
			jQuery(this).val('search');
		}
	});
	
	$('#searchField').bind('keypress', function(e) {
		var code = (e.keyCode ? e.keyCode : e.which);
		 if(code == 13) { 
		 	submitSearch()
		 }
	});

function submitSearch()
{
	var searchVal = "us";
	
	if(jQuery('#searchField').val()!="search")
	{
	var safeSearch = encodeURIComponent(jQuery('#searchField').val());
	
	if(getUsrLocale()=="en_CA"){searchVal="ca";}
	
    parent.location = searchServer + "/search?region="+searchVal+"&asug=&w=" + safeSearch;
	}
}

	//EMAIL SIGN-UP
	jQuery('.emailSignUpField').live('focus', function() {
		if(jQuery(this).val() == 'enter your email address' || jQuery(this).val() == 'please enter a valid email' || jQuery(this).val() == 'error signing up, please try again') {
			jQuery(this).val('');
			jQuery(this).css('color', '#777C84');
		}
	});
	jQuery('.emailSignUpField').live('blur', function() {
		if(jQuery(this).val() == '') {
			jQuery(this).val('enter your email address');
		}
	});


jQuery("#signin, #fbLoginLink").click(function(event) {
		event.preventDefault();
		jQuery.fancybox({
			'padding' : 0,
			'transitionIn' : 'none',
			'transitionOut' : 'none',
			'scrolling' : 'no',
			'autoDimensions' : false,
			'autoScale' : false,
			'width' : 502,
			'height' : 283,
			'type' : 'iframe',
			'href' : jQuery(this).attr("href"),
			'onCleanup' : function() {
				setupUtilBar();
			}
		});
	});

	//REGISTER
	jQuery("#register").click(function(event) {
		event.preventDefault();
		jQuery.fancybox({
			'padding' : 0,
			'transitionIn' : 'none',
			'transitionOut' : 'none',
			'scrolling' : 'no',
			'autoDimensions' : true,
			'autoScale' : false,
			'width' : 502,
			'height' : 302,
			'type' : 'iframe',
			'href' : jQuery(this).attr("href"),
			'onCleanup' : function() {
				setupUtilBar();
			}
		});
	});


jQuery('#shoppingBag a#shoppingBagLink').live('click',function(event){
		event.preventDefault();
		jQuery.fancybox({
			'autoDimensions'		: true,
			'autoScale'				: false,
			'hideOnContentClick'	: false,
			'height'				: 870,
			'width'					: 980,
			'transitionIn'			: 'elastic',
			'transitionOut'			: 'elastic',
			'speedIn'				: 600,
			'speedOut'				: 200,
			'overlayShow'			: true,
			'scrolling'				: 'no',
			'modal'					: false,
			'type'					: 'iframe',
			'href'					: jQuery(this).attr('href'),
			'onCleanup' : function() {
				setupUtilBar(); //*** check cookies to see if they've changed the cart count
			}
});
	});



$(".extLink").fancybox({
	         'autoScale' : true,
	         'type' : 'iframe',
			 'opacity' : 'true'
	     });

});

//CONTINUE SHOPPING
jQuery('#continueShopping').live('click',function(event) {
event.preventDefault();
setupUtilBar();
});


function changeLinksForStage()
{
if(window.location.hostname.indexOf(".lululemon.com")==-1)
						{
		 jQuery("a").each(function() { 
			 var href = jQuery(this).attr('href');
			 if (href != undefined && href != "") {
					
					if(href.indexOf("/secure/")>-1 || href.indexOf("/shop/")>-1)
					{
						href = href.replace("http://www.lululemon.com","http://stage.lululemon.com");
						href = href.replace("https://www.lululemon.com","https://stage.lululemon.com"); 
						jQuery(this).attr('href', href);
					}else{
					
						
						href = href.replace("http://www.lululemon.com",""); 
						href = href.replace("https://www.lululemon.com",""); 
						jQuery(this).attr('href', href);

					
					}

			 }
		 });	
	}
}


function setupUtilBar()
{

	$("#regionSelector").css("visibility","visible");
	
	showRegionAsCa(getUsrLocale()=="en_CA");

	$("#bagItemCount").html(getShoppingCartCount());
	
	if(getShoppingCartCount()==0)
	{
		$("#checkOutButton").css("display","none");
	}else{
		$("#checkOutButton").css("display","block");
	}

	$("#shoppingBag").css("visibility","visible");
	
	if(getLoggedIn()==false)
	{
		$(".loggedIn").css("display","none");
		$(".notLoggedIn").css("display","block");
	}else{
		$(".loggedIn").css("display","block");
		$(".notLoggedIn").css("display","none");
	}
	$("#myAccount").css("visibility","visible");

}

function setupMegaNav()
{

	var SUBMENU_WIDTH = 174;
	var SUBMENU_HEIGHT_ADJUST = 70;
	//women
	var multiColumnWidthWomen = jQuery('#NAV #women.mnSubMenu .multiColumn ul').length * SUBMENU_WIDTH;
		multiColumnWidthWomen = multiColumnWidthWomen +'px';
		jQuery('#NAV #women.mnSubMenu .multiColumn').css('width',multiColumnWidthWomen);
	var multiColumnWomenHeight = jQuery('#NAV #women.mnSubMenu').height()-SUBMENU_HEIGHT_ADJUST;
		jQuery('#NAV #women.mnSubMenu .multiColumn ul').css('height',multiColumnWomenHeight);
	//men
	var multiColumnWidthMen = jQuery('#NAV #men.mnSubMenu .multiColumn ul').length * SUBMENU_WIDTH;
		multiColumnWidthMen = multiColumnWidthMen +'px';
		jQuery('#NAV #men.mnSubMenu .multiColumn').css('width',multiColumnWidthMen);
	var multiColumnMenHeight = jQuery('#NAV #men.mnSubMenu').height()-SUBMENU_HEIGHT_ADJUST;
		jQuery('#NAV #men.mnSubMenu .multiColumn ul').css('height',multiColumnMenHeight);
	//shop by
	var multiColumnWidthShopBy = jQuery('#NAV #shopBy.mnSubMenu .multiColumn ul').length * SUBMENU_WIDTH;
		multiColumnWidthShopBy = multiColumnWidthShopBy +'px';
		jQuery('#NAV #shopBy.mnSubMenu .multiColumn').css('width',multiColumnWidthShopBy);
	var multiColumnShopByHeight = jQuery('#NAV #shopBy.mnSubMenu').height()-SUBMENU_HEIGHT_ADJUST;
		jQuery('#NAV #shopBy.mnSubMenu .multiColumn ul').css('height',multiColumnShopByHeight);
}

function setupFooter()
{
	
	///*** find a store button
	$('#findAStoreButton').click(function() {
	  document.location.href= WWWServerPath + "/stores";
	});


//EMAIL SIGN UP IN FOOTER
               jQuery('#emailSignUpField').val('enter your email address');
               jQuery('#signMeUpButton').click(function(e) {
                              e.preventDefault();
                              var emailAddr = jQuery('#emailSignUpField').val();

                              //processing
                              jQuery('#emailProcessing').show();
                              jQuery('#emailSignUpField, #emailSignUpForm span.btn').hide();

                              //handler
                              jQuery.ajax({
                                             url: ShopServerPath + "/elements/emailSignUp.jsp",
                                             type: "post",
                                             data: {email : emailAddr},
                                             dataType: "jsonp",
                                             jsonpCallback : "emailSignUp",
                                             success: function(data){
                                                            jQuery('#emailProcessing').hide();
                                                            var messaging  = jQuery.trim(data.formMessage);
                                                            jQuery('#emailMessaging').text(messaging);
                                                            if(data.result == 'success') {
                                                                           jQuery('#emailMessaging').fadeIn();
                                                            } else if(data.result == 'exists') {
                                                                           jQuery('#emailMessaging').fadeIn();
                                                            } else {
                                                                           jQuery("#emailMessaging").hide();
                                                                           jQuery("#emailSignUpField").val(messaging);
                                                                           jQuery("#emailSignUpField").css('color', '#FF1543');
                                                                           jQuery("#emailSignUpField").show();
                                                                           jQuery("#signMeUpButton").show();
                                                                           jQuery("#signMeUpButton").parent().show();
                                                            }

                                                            _gaq.push(['ga._trackEvent', 'User Event', 'Email Signup', 'lululcom']);
                                                            
                                             }
                              });
               });




// ***TOOLTIP

jQuery('.emailSignUpField').qtip({
		content: 'by signing up, you are agreeing to <br/>our <a href="' + WWWServerPath + '/terms" target="_blank">> terms and conditions</a>',
		show: {
			when: 'focus'
		},
		hide: {
			when: 'blur',
			fixed: true
		},
		style: {
			background: '#fff2cc',
			border: {
				color: '#f4de9f',
				width: 2,
				radius: 2
			},
			color: '#000',
			name: 'cream',
			padding: 10,
			tip: true
		},
		position: {
			corner: {
				target: 'bottomMiddle',
				tooltip: 'topMiddle'
			},
			adjust: {
				y: -10
			}
		}
	});
	
}


function publishMegaMenu(mega_menu_html){
	$('#NAV').replaceWith(mega_menu_html);	
}
	
function publishFooter(footer_html){
	$('#FOOTER').replaceWith(footer_html);
}



//*** Utility Nav Functions

function getUsrLocale()
{
	region = jQuery.cookie("UsrLocale");

	if(region!=null && (region=="en_US" || region=="en_CA"))
	{
		return region;
	}else{
		return "en_US";
	}
}

function getLoggedIn()
{
	isLoggedIn = jQuery.cookie("isLoggedin");
	return isLoggedIn=="true";
}

function getShoppingCartCount()
{
	cartCount = jQuery.cookie("cartCount");
		if(cartCount==null || cartCount==""){
			return 0;
		}else{
			return cartCount;
		}
}

//*** Set the region cookie
function setRegionCookieToCA(toCanada)
{
		if(toCanada==true)
		{
			jQuery.cookie('UsrLocale', "en_CA", { path: '/', expires: 30, domain: '.lululemon.com' });
			//jQuery.cookie('UsrLocale', "en_CA",{expires: 30});
			showRegionAsCa(true);
		}else{
			jQuery.cookie('UsrLocale', "en_US", { path: '/', expires: 30, domain: '.lululemon.com' });
			//jQuery.cookie('UsrLocale', "en_US", {expires: 30});
			showRegionAsCa(false);
		}
		
		jQuery.cookie('cartCount', "0", { path: '/', domain: '.lululemon.com' });
		//jQuery.cookie('cartCount', "0");
		getExternalContent(JSONPath,errorCallBack);
}

function showRegionAsCa(isCanada)
{
	if(isCanada==true)
	{
		tempImg = imgServer  +"/flag-ca?$standard$";
		jQuery('#regImage').attr({'src':tempImg});		
	}else{
		tempImg = imgServer + "/flag-us?$standard$";
		jQuery('#regImage').attr({'src':tempImg});
		
	}
}

//*** IPAD onclick insted of hover
function swapRegionChangeBox()
{
	if(jQuery('#toCanada').css("display")=='block' || jQuery('#toUS').css("display")=='block')
	{
		hideRegionChangeBox()
	}else{
		showRegionChangeBox()
	}
}

function showRegionChangeBox()
{
	
	if(getUsrLocale()=="en_CA")
	{
		jQuery('#toCanada').css({display:'block'});
		jQuery('#toUS').css({display:'none'});
	}
	
	if(getUsrLocale()=="en_US")
	{
		jQuery('#toUS').css({display:'block'});
		jQuery('#toCanada').css({display:'none'});
	}
	
	jQuery("#regOverlay").addClass('on');
}

function hideRegionChangeBox()
{
	jQuery('.utilitySubMenu').css({display:'none'});
	jQuery("#regOverlay").removeClass('on');
}

//*** get external data

function getExternalContent(pageUrl,errorCallBack){
	
	try{
	
		jQuery.ajax({
		  url: pageUrl,
		  contentType:"application/json; charset=utf-8",
		  timeout:30000,
		  dataType: 'jsonp',
		  async: true,
		  error: errorCallBack,
		  jsonpCallback : "getNavigation"
		});	
	}catch(err)
		  {
		 //alert("inner:"+err);
		  updateScreenforErrors();
		  }
}
	
function getNavigation(data)
{
var isLoggedIn = false;
var region = "en_US";
var cartCount = 0;

//console.log(data);

		try{
			
				if(data.Navigation.menuHtml.length > 1)
				{
					megaNav = cleanUpResponse(data.Navigation.menuHtml);
					//console.log(megaNav);
					publishMegaMenu(megaNav);
					setupMegaNav();
					amplify.store.sessionStorage("megaNav",megaNav);
				}
				
				if(data.Navigation.footerHtml.length > 1)
				{
					footer = cleanUpResponse(data.Navigation.footerHtml);
					//console.log(footer);
					publishFooter(footer);
					
					setupFooter();
					amplify.store.sessionStorage("footer",footer);
				}


				if(data.Navigation.userInfo.region.length > 1)
				{
					if(data.Navigation.userInfo.region=="en_US" || data.Navigation.userInfo.region=="en_CA")
					{
						//alert("setting as "+ data.Navigation.userInfo.region);
						amplify.store.sessionStorage("region",data.Navigation.userInfo.region);
					}
				}	

		
			}
		catch(err)
		  {
		  //alert("inner:"+err);
		  updateScreenforErrors();
		  }

setupUtilBar();	  
}
	
var errorCallBack = function(data, textStatus, xhr)
{
	//alert(xhr + "\t" + textStatus);
	//updateScreenforErrors();
}	

function updateScreenforErrors()
{
	 //$('#FOOTER').css("height","50px");
}

//*** called from Iframe reloads
function sitePageReload()
{
	getExternalContent(JSONPath,errorCallBack);
}

// *** defaults
function showNavDefault()
{
$('#NAV').html('<ul>\
	<li class="logo" style="margin-left:323px;">\
		<a href="http://www.lululemon.com" onclick="s_objectID=&quot;http://www.lululemon.com/_1&quot;;return this.s_oc?this.s_oc(e):true">\
			<img alt="lululemon athletica" src="//images.lululemon.com/is/image/lululemon/logo-lululemon?$pngstandard$">\
		</a>\
	</li>\
	<li class="mnMain">\
		<div class="mnLeft">\
			<div class="mnRight"><a href="http://www.lululemon.com/education/?mnid=mn;education" onclick="s_objectID=&quot;http://www.lululemon.com/education/?mnid=mn;education_1&quot;;return this.s_oc?this.s_oc(e):true">education</a></div>\
		</div>\
	</li>\
	<li class="mnMain">\
      <div class="mnLeft">\
        <div class="mnRight"><a href="http://www.lululemon.com/community/?mnid=mn;community" onclick="s_objectID=&quot;http://www.lululemon.com/community/?mnid=mn;community_1&quot;;return this.s_oc?this.s_oc(e):true">community</a></div>\
      </div>\
    </li>\
	<li class="mnMain">\
      <div class="mnLeft">\
        <div class="mnRight"><a href="http://www.lululemon.com/community/blog/?mnid=mn;blog" onclick="s_objectID=&quot;http://www.lululemon.com/community/blog/?mnid=mn;blog_1&quot;;return this.s_oc?this.s_oc(e):true">blog</a></div>\
      </div>\
    </li>\
</ul>');    
}

function showFooterDefault()
{
$('#FOOTER').html('<div class="container"><ul class="global"><li class="copyright">&copy; 2011 lululemon athletica</li><li><a href="/privacy">privacy</a></li><li><a href="/terms">terms</a></li><li><a href="/sitemap">sitemap</a></li><li><a href="http://search.lululemon.com">search</a></li><li><a href="http://www.ivivva.com"> ivivva</a></li></ul></div>');
$('#FOOTER').css("background-image","none");
$('#FOOTER').css("background-color","#D3D1CE");
}

//*** helper

function cleanUpResponse(htmlRes)
{
	//htmlRes = htmlRes.replace(/(\r\n|[\r\n])/g, "");
	htmlRes = htmlRes.replace(/&amp;#034;/g, "\"");
	htmlRes = htmlRes.replace(/&#034;/g, "\"");
	htmlRes = htmlRes.replace(/\(&amp;#039;/g, "(\'");
	htmlRes = htmlRes.replace(/&amp;#039;\)/g, "\')");
	htmlRes = htmlRes.replace(/&#232;\)/g, "è");
	
	//htmlRes = htmlRes.replace(/&amp;/g, "&");
	//htmlRes = htmlRes.replace(/&#039;/g, "\'");

	return $.htmlDecode(htmlRes);	
}


jQuery(document).ready(function() {
      $("a.iframe").fancybox({
           'frameWidth'    :       390,
           'frameHeight'   :       640,
           'hideOnContentClick': false, 
		   'autoScale'     	: false,
           'type':'iframe'
      }); 
	  
	  
$("#shippingLink img").hover(
 function()
 {
  this.src = this.src.replace("_off","_on");
 },
 function()
 {
  this.src = this.src.replace("_on","_off");
 }
);	  
	  
	  
});

jQuery.extend( {
isHtmlEncoded: function(str) {
if(str == null) { return false; }
if(str.search(/&amp;/g) != -1 || str.search(/&lt;/g) != -1 || str.search(/&gt;/g) != -1)
return true;
else
return false;
},

htmlDecode: function(str) {
    if($.isHtmlEncoded(str))
      return str.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
    return str;
}
});

//*** Mega nav
jQuery('a.static').live('click', function(event) {
		event.preventDefault();
	});

//*** Ipad specific
jQuery('html, #HEADER, #NAV, #MAIN, #FOOTER').click(function() { /* ipad */ });


