// R: 20101029

// Home page silo opened
var homeSilo = false;

// Activate Global SIFR variables
var avenir = { src: 'js/sIFR3/avenir_436.swf' };
var avenir_h1 = { src: 'js/sIFR3/avenir_436_h1.swf' };
var avenir_current = { src: 'js/sIFR3/avenir_436_current.swf' };
sIFR.activate(avenir, avenir_h1);

// Initiate vertical measures
var leftSiloOneHeight, leftSiloTwoHeight, contentHeight;

// Set colour scheme
var bgImage;

function file_name_only(str) {
	str = str.toLowerCase();
	if (str.lastIndexOf('?')>0)
	{
	    str = str.substring(0, str.lastIndexOf('?'));
	}
	
	var slash = '/';
	if (str.match(/\\/)) {
		slash = '\\';
	}
	return str.substring(str.lastIndexOf(slash) + 1, str.lastIndexOf('.'));
}

function sub_cat_only(str) {	
	var hashChar = '#';
	
	if (str.lastIndexOf(hashChar) > 0)
	{
		str = str.substring(str.lastIndexOf(hashChar) + 1, str.length);
		return str;
	}
	else {
		return null;
	}
}

Array.prototype.exists = function(search){
  for (var i=0; i<this.length; i++)
    if (this[i] == search) return true;
		
  return false;
} 

String.prototype.replaceAll = function(pcFrom, pcTo){
	var i = this.indexOf(pcFrom);
	var c = this;
	
	while (i > -1){
		c = c.replace(pcFrom, pcTo); 
		i = c.indexOf(pcFrom);
	}
	return c;
};

// NOTE to change file size
// ANOTHER NOTE

function singleWord(str) {
	str = str.replaceAll('/', '-');
	str = str.replaceAll(' ', '-');
	str = str.replaceAll("•", '-');
	str = str.replaceAll("·", '-');
	str = str.replaceAll('"', '-');
	str = str.replaceAll('?', '-');
	str = str.replaceAll(",", '-');
	//str = str.replaceAll(".", '-');
	str = str.replaceAll("'", '-');
	
	return str;
}
var colourScheme;
var smallscreenin = false;
var birdwordin = false;

var myWidth = 0, myHeight = 0;
setupBackground = function() {
	// should call this on window.resize (in final.js)
	
	colourScheme = file_name_only(document.getElementById("colourCSSBase").href);
	var bgColor = $("body").css('background-color');
	
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	
	
	//var vpWidth = screen.width; // based on screen width
	var vpWidth = myWidth; // based on viewport width
	var vpHeight = myHeight; // based on viewport height
	//alert(vpWidth);
	
    if (vpWidth <= 1024) {
		if(!smallscreenin) {
			smallscreenin = true;
			var css1024 = document.createElement("link");
			css1024.id = 'css1024';
			css1024.href = "css/1024";
			if($('#market').attr('market')!='OUTDOOR') {
				css1024.href += "-" + $('#market').attr('market');
			}
			css1024.href += ".css";
			css1024.rel = "stylesheet";
			css1024.type = "text/css";
			document.getElementsByTagName("head")[0].appendChild(css1024);
		}
    }
	else {
		if(smallscreenin) {
			smallscreenin = false;
			$("#css1024").remove();
		}
	}


	if(vpWidth <= 1024 && vpHeight <= 768) {
		bgImage = "url(css/bgphotos/1024x768/" + colourScheme + ".jpg)";
	}
    else if (vpWidth <= 1280 && vpHeight <= 1024) {
		bgImage = "url(css/bgphotos/1280x1024/" + colourScheme + ".jpg)";
	}
	else if (vpWidth <= 1440 && vpHeight <= 1050) {
		bgImage = "url(css/bgphotos/1440x1050/" + colourScheme + ".jpg)";
	}
	else if (vpWidth <= 1680 && vpHeight <= 1200) {
		bgImage = "url(css/bgphotos/1680x1200/" + colourScheme + ".jpg)";
	}
	else if (vpWidth <= 1920 && vpHeight <= 1200) {
		bgImage = "url(css/bgphotos/1920x1200/" + colourScheme + ".jpg)";
	}
	else {
		bgImage = "url(css/bgphotos/2560x1600/" + colourScheme + ".jpg)";
	}
	
	
	if (vpWidth > 1024 && $("#market").attr('market') == "OUTDOOR" && document.getElementById("PageName").content == 'HOME') {
		if(!birdwordin) {
			birdwordin = true;
			var cssHome = document.createElement("link");
			cssHome.id = 'cssBirdword';
			cssHome.href = "css/birdword.css";
			cssHome.rel = "stylesheet";
			cssHome.type = "text/css";
			document.getElementsByTagName("head")[0].appendChild(cssHome);
		}
	}
	else {
		if (birdwordin) {
			birdwordin = false;
			$("#cssBirdword").remove();
		}
	}
	
    document.body.style.background =  bgImage + " " + bgColor + " fixed no-repeat top center";
};

/* CHECK FOR FLASH */

var MM_contentVersion = 6;
var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
if ( plugin ) {
		var words = navigator.plugins["Shockwave Flash"].description.split(" ");
	    for (var i = 0; i < words.length; ++i)
	    {
		if (isNaN(parseInt(words[i]))) {
			continue;
		}
		var MM_PluginVersion = words[i]; 
	    }
	var MM_FlashCanPlay = MM_PluginVersion >= MM_contentVersion;
}
else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 && (navigator.appVersion.indexOf("Win") != -1)) {
	document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n'); //FS hide this from IE4.5 Mac by splitting the tag
	document.write('on error resume next \n');
	document.write('MM_FlashCanPlay = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & MM_contentVersion)))\n');
	document.write('</SCR' + 'IPT\> \n');
}

$(document).ready(function() {
	$("noscript").hide();
	
    setupBackground();
	
	// Initalize sIFR headlines
	sifrInit();
	
	// Set theme coloured rss Icon in silo
	var rssIcon = 'css/rss-icons/' + colourScheme + '.png';
	$("#rssIcon").attr('src', rssIcon);
	
	// Hide submenus and attach menu behaviours
	$(".menuSubCat").hide();
	
	// Show current menu's submenus
	$(".current").siblings(".menuSubCat").show();
	
	// Attach footer function behaviours
	$(".footerFunction").click(function() {
		var targetFunction = $(this).attr('target');
		
		if ($("#" + targetFunction).css('display') == 'block')
		{
			$("#" + targetFunction).slideUp("normal", function() {sizeVerticals();});
			$("#footerMinimize").fadeOut();
			
		}
		else
		{
			$(".footerSubContent").slideUp();
			$("#" + targetFunction).slideToggle("normal", function() {sizeVerticals();});
			$("#footerMinimize").fadeIn();
			pageTracker._trackEvent('footer','/footerOpen/' + targetFunction);
		}
	});
	$("#footerMinimize").click(function() { $(".footerSubContent").slideUp("normal", function() {sizeVerticals();}); $("#footerMinimize").fadeOut(); });
	
	// Attach form field background-image behaviours
	$("#search").focus(function() { if($(this).val() == "") { $(this).css('background-image','none'); } });
	$("#search").blur(function() { if($(this).val() == "") { $(this).css('background-image','url(graphics/' + language + '/search.gif)'); } });
	
	$("#EMail").focus(function() { if($(this).val() == "") { $(this).css('background-image','none'); } });
	$("#EMail").blur(function() {	if($(this).val() == "") { $(this).css('background-image','url(graphics/' + language + '/email.gif)'); } });
	
	$("#EMailHeader").focus(function() { if($(this).val() == "") { $(this).css('background-image','none'); } });
	$("#EMailHeader").blur(function() {	if($(this).val() == "") { $(this).css('background-image','url(graphics/' + language + '/email.gif)'); } });
	
	// Clear the background for any textbox or password that has something in it
	$("input[type=text], input[type=password]").each(function() {
		if($(this).val() != ""){ $(this).css('background-image','none'); }
	});
	
	$("#UserLogin").focus(function(){ $(this).siblings('label').hide(); });
	$("#UserPwd").focus(function(){ $(this).siblings('label').hide(); });
	
	
	/*$("#UserLogin").focus(function() { if($(this).val() == "") { $(this).css('background-image','none'); } });
	$("#UserLogin").blur(function() {	if($(this).val() == "") { $(this).css('background-image','url(graphics/' + language + '/email-username.gif)'); } });
	
	$("#UserPwd").focus(function() { if($(this).val() == "") { $(this).css('background-image','none'); } });
	$("#UserPwd").blur(function() { if($(this).val() == "") { $(this).css('background-image','url(graphics/' + language + '/password.gif)'); } });
	
	$("#formTW").submit(function() {
		$("#UserLogin").val(""); 
		$("#UserLogin").css('background-image','url(graphics/email-username.gif)');
		
		$("#UserPwd").val("");
		$("#UserPwd").css('background-image','url(graphics/password.gif)');
	});*/
	
	// Show tooltips on any links or searchResults that have titles set
	$("a, .searchResult, .thumb, div:not(#footerMinimize)").tooltip();
	
	//alert(file_name_only(window.location.href));
	switch(document.getElementById("PageName").content) {
		case 'product':
		case 'PRODUCT':
			$("div.searchResult").click(function() {
				var targetURL = this.id; // Product.aspx?Mens/Jackets-Vests/Alpha-SL-Jacket
				var catURL = targetURL.substring(0, targetURL.lastIndexOf('/')); // Product.aspx?Mens/Jackets-Vests
				var subCatURL = sub_cat_only(window.location.href); // Insulated-Shell
				var prodURL = targetURL.substr(targetURL.lastIndexOf('/')); // /Alpha-SV-Jacket
				
				
				if (subCatURL != null) {
					targetURL = targetURL + "#" + subCatURL;
				}
				
				//alert(targetURL);
				window.location = targetURL;
			});
			
			break;
		case 'athletes':
		case 'ATHLETES':
			$(".searchResult").hover(
				function() {
					$(this).children().children(".athleteSRLinks").slideDown('fast');
				},
				function() {
					$(this).children().children(".athleteSRLinks").slideUp('fast');
				}
			);
			
			$("div.searchResult:not(.athleteNews, .athleteSRLink)").click(function() {
				window.location = "Athlete.aspx?" + lang + '/' + this.id;
			});
			
			$("div.athleteNews").click(function() {
				window.location = "Article.aspx?" + lang + "&article=" + this.id;
			});
			break;
		case 'athlete':
		case 'ATHLETE':
			
			break;
		case 'news':
		case 'NEWS':
			$(".searchResult").click(function() {
				window.location = "Article.aspx?" + lang + "&article=" + this.id;
			});
			break;
		case 'partners':
		case 'PARTNERS':
			$("div.searchResult").click(function() {
				window.open ('http://'+$(this).attr('lightboxtitle'));
				pageTracker._trackEvent('outbound','/partners/' + $(this).attr('lightboxtitle'));
			});
			break;
		case 'events':
		case 'EVENTS':
			$("div.searchResult").click(function() {
				window.open ('http://'+$(this).attr('lightboxtitle'));
				pageTracker._trackEvent('outbound','/events/' + $(this).attr('lightboxtitle'));
			});
			break;
		case 'online-dealers':
		case 'ONLINE-DEALERS':
			$("div.searchResult").click(function() {
				window.open ('http://'+$(this).attr('id'));
				pageTracker._trackEvent('outbound','/online-dealers/' + $(this).attr('id'));
			});
			break;
		case 'where-to-buy':
		case 'WHERE-TO-BUY':
			$("div.searchResult").click(function() {
				window.open ($(this).attr('id'));
				pageTracker._trackEvent('outbound','/where-to-buy/' + $(this).attr('id'));
			});
			break;
		case 'service-forms':
		case 'SERVICE-FORMS':
			//alert('case: service-forms');
			
			var iframe = document.getElementById('frameService');
			var service = $("#frameService").attr('src');
			var formName = querySt("subject",service.substr(service.lastIndexOf("?")+1, service.length));				
			//console.log(formName); // ASKSPCL
			if (!formName) {
				formName = service.substr(service.lastIndexOf("?")+1,service.length);
			}
			
			if(formName.indexOf("PROPRCH") > -1) {
				iframe.style.height = "2000px";
			}
			else if(formName.indexOf("LEAFFRM") > -1) {
				iframe.style.height = "1400px";
			}
			else {
				iframe.style.height = "1200px";
			}
			
			break;
		case 'article':
		case 'ARTICLE':
			$("div.searchResult").click(function() {
				window.open ('http://'+$(this).attr('lightboxtitle'));
				pageTracker._trackEvent('outbound','/article/' + $(this).attr('lightboxtitle'));
			});
			break;
		case 'compare':
		case 'COMPARE':
			$('div.compareResult').click(function() {
				window.location = this.id;
			});
			break;
		case 'video':
		case 'VIDEO':
			
			if(typeof(launchVideo) != 'undefined')
			{
				//alert(launchVideo.HREF);
				Shadowbox.init();
				//Shadowbox.open({content: launchVideo.HREF });
				
				Shadowbox.open({
								title: launchVideo.title,
								content: launchVideo.HREF,
								moreBeta: launchVideo.moreBeta,
								gallery: launchVideo.gallery
							   }, { gallery: launchVideo.gallery} );
				
			}
			
			$(".videoLauncher").click(function() {
				//$(this).children().children('a').click();
				//alert(this.id);
				//alert($(this).attr('lightboxtitle'));
				Shadowbox.open({
								title: $(this).attr('lightboxtitle'),
								content: this.id,
								moreBeta: $(this).attr('moreBeta'),
								gallery: 'Videos'
							   }, { gallery: 'Videos'} );
			});
						
			break;
			
		case '.com/':
		case 'home':
		case 'HOME':
			$("div.newsSiloArticle").click(function() {
				window.location = this.id;
			});
			$("div.newsSiloVideo").click(function() {
				//$(this).children().children('a').click();
				var galleryName = (this.id.indexOf("Season")) ? "Season" : "Videos";
				Shadowbox.open({
								title: $(this).children('.searchResultName').children('a').attr('lightboxtitle'),
								content: this.id,
								gallery: galleryName,
								moreBeta: $(this).children('.searchResultName').children('a').attr('moreBeta')
							   }, { gallery: galleryName} );
			});
			
			if($('#market').attr('market')=='URBAN' && MM_FlashCanPlay && 0) // DISABLE THIS AS OF f10
			{
				
				$("#content").append('<div id="homeVR"><div id="homeVRviewer"></div></div>');
				
				if(navigator.appName=="Microsoft Internet Explorer")
				{
					/* Set explicit z-index for home content parent divs for IE only */
					$(".centreColumnHome, #mainContentEmpty, #divHomeContent").css("z-index", 3);
				}
				
				//var bgColor = $("body").css('background-color');
				$("body").css('background-image','none');
				//document.body.style.background =  bgImage + " " + bgColor + " fixed no-repeat top center";
				
				$("#homeVRviewer").jmedia(
					{version:"9,0"
					},
					{
						src:"pano/krpano.swf",
						flashVars:'pano=pano/krpano-bridge.xml&license=pano/license.xml',
						width: "100%",
						height: "100%",
						wmode: 'transparent',
						id: "krpano"
					}
				);
				/* KRPANO DRAG FIX CODE */
				$(document).mouseup(function(event)
				  {
					  //alert('mouseup');
					if (!$(event.target).is("#krpano")) { document.getElementById("krpano").sendToKrpano(); }
				  });
				/* END KRPANO DRAG FIX CODE */
			}
			break;
		case 'maintenance':
		case 'MAINTENANCE':
			if($('#market').attr('market')=='URBAN' && MM_FlashCanPlay)
			{
				$("#content").append('<div id="homeVR" style="top: 0; bottom: 0;"><div id="homeVRviewer"></div></div>');
					
				if(navigator.appName=="Microsoft Internet Explorer")
				{
					/* Set explicit z-index for home content parent divs for IE only */
					$(".centreColumnHome, #mainContentEmpty, #divHomeContent").css("z-index", 3);
				}
				
				//var bgColor = $("body").css('background-color');
				//$("body").css('background-image','none');
				//document.body.style.background =  bgImage + " " + bgColor + " fixed no-repeat top center";
				
				/*$("#homeVRviewer").jmedia(
					{version:"9,0"
					},
					{
						src:"pano/krpano.swf",
						flashVars:'pano=pano/krpano-bridge.xml&license=pano/license.xml',
						width: "100%",
						height: "100%",
						wmode: 'transparent',
						id: "krpano"
					}
				);
				*/
				/* KRPANO DRAG FIX CODE */
				$(document).mouseup(function(event)
				  {
					  //alert('mouseup');
					if (!$(event.target).is("#krpano")) { document.getElementById("krpano").sendToKrpano(); }
				  });
				/* END KRPANO DRAG FIX CODE */
			}
			break;
	}
});

function openSignup(targetForm, event) {
	//alert(event.type == 'click');
	if (event.keyCode == 13 || event.type == 'click')
	{
		var email = $('#EMail').val();
		
		if (email == '' || email == null) {
			email = $('#EMailHeader').val();
		}
		
		
		var simplify = '';
		switch($('#market').attr('market')) {
			case "URBAN":
				simplify = "V";
				break;
			case "OUTDOOR": 
			case "LEAF":
				simplify = "Y";
				break;
		}
		
		if(email)
		{
			if(targetForm.indexOf("?") > 0) {
				email = '&EMail=' + email;
			}
			else {
				email = '?EMail=' + email;
			}
		}
		else {
			email = '';
		}

		Shadowbox.open({
			player:'iframe',
			title: textSignupLightboxTitle,
			/*content:'http://tasweb.arcteryx.com/endusersignup.aspx' +'?Simplify=Y&EMail='+email,*/
			
			/*content:targetForm +'?Simplify=' + simplify + '&EMail=' + email,*/
			content:targetForm + email,
			width:'900',
			height:'900'
		}, {viewportPadding: 20});
		pageTracker._trackEvent('footer','/footerOpen/' + targetForm);
	}
}

function slideSubMenu(cat) {
	$('.menuCat > li > h3#'+cat).siblings(".menuSubCat").slideToggle('normal', function() {
		sizeVerticals();
	}); 
}

function setupStores() {
	$(".storeDetails").each(function() {
		//alert("index: " + $("div.storeDetails").index(this) + ", % 4 = " + ($("div.storeDetails").index(this) % 4) + ", %4== " + ($("div.storeDetails").index(this) % 4 == 0) );
		 if ($("div.storeDetails").index(this) % 4 == 0)
		 {
			 $(this).css('clear','both');
		 }
	});	
}

function openSilo(targetSilo) {
	// Hide both silos
	$(".silo").css('display', 'none');
	// Show the target silos
	$(".silo[PBType=" + targetSilo + "]").css('display','block');
	// resize verticals
	sizeVerticals();
	// re-initialize sIFR fonts
    sifrInit();
	
	if ($("#divSearchResultsList").is(':visible')){
		moveDrop();
	}
}

function firstFade(targetSilo) {
	if (homeSilo == false)
	{
		$(".silo").css('display', 'none');
		$(".silo[PBType=" + targetSilo + "]").fadeIn('normal', function() { sifrInit(); sizeVerticals(); });
		homeSilo = true;
	}
	else
	{
		openSilo(targetSilo);
	}
}

function searchIt(query) {
	//alert(query);
	query = query.replace(' ', '_');
	query = query.replace('/', '-');
	window.location.href = "Product.aspx?search=" + query;
}

// make divs and other elements clickable
function goTo(address) {
	window.location.href = address;
}

function sifrInit() {
	// H1 (non-current)
	var offsetTopV = -5;
	switch($('#market').attr('market'))
	{
		case 'OUTDOOR':
			offsetTopV = 2;
			break;
		case 'LEAF':
		case 'URBAN':
			offsetTopV = -2;
			break;
	}
	
	sIFR.replace(avenir_h1, {
		selector: 'h1:not(.current)',
		css: { 
			'.sIFR-root': { 'color': '#000000' },
			'a': { 'color': '#CCCCCC', 'text-decoration': 'none' },
			'a:link': { 'color': '#CCCCCC' },
			'a:hover': { 'color': '#FFFFFF' }
			},
		transparent: 1,
		offsetTop: offsetTopV,
		tuneHeight: -5,
		forceSingleLine: true,
		onReplacement : function(){
			//alert('replace');
			//sizeVerticals();
			this.sIFR.doCompleteCheck();
			} 
	});
	
	// H1 (current)
	sIFR.replace(avenir_current, {
		selector: 'h1.current',
		css: { 
			'.sIFR-root': { 'color': sIFRcurrentColor },
			'a': { 'color': sIFRcurrentColor, 'text-decoration': 'none' },
			'a:link': { 'color': sIFRcurrentColor },
			'a:hover': { 'color': sIFRcurrentHover }
			},
		transparent: 1,
		offsetTop: offsetTopV,
		tuneHeight: -5,
		forceSingleLine: true,
		onReplacement : function(){
			//alert('replace');
			//sizeVerticals();
			this.sIFR.doCompleteCheck();
			} 
	});
	
	// H2 (non-current)
	sIFR.replace(avenir, {
		selector: 'h2:not(.current)',
		css: { 
			'.sIFR-root': { 'color': '#000000' },
			'a': { 'color': '#CCCCCC', 'text-decoration': 'none' },
			'a:link': { 'color': '#CCCCCC' },
			'a:hover': { 'color': '#FFFFFF' }
			},
		transparent: 1,
		offsetTop: -3,
		tuneHeight: -2,
		onReplacement : function(){
			//alert('replace');
			//sizeVerticals();
			this.sIFR.doCompleteCheck();
			} 
	});
	
	// H2 (current)
	sIFR.replace(avenir_current, {

		selector: 'h2.current',
		css: { 
			'.sIFR-root': { 'color': sIFRcurrentColor },
			'a': { 'color': sIFRcurrentColor, 'text-decoration': 'none' },
			'a:link': { 'color': sIFRcurrentColor },
			'a:hover': { 'color': sIFRcurrentHover }
			},
		transparent: 1,
		offsetTop: -3,
		tuneHeight: -2,
		onReplacement : function(){
			//alert('replace');
			//sizeVerticals();
			this.sIFR.doCompleteCheck();
			} 
	});
	
	// H3 (current)
	sIFR.replace(avenir_current, {
		selector: 'h3.current',
		css: { 
			'.sIFR-root': { 'color': sIFRcurrentColor },
			'a': { 'color': sIFRcurrentColor, 'text-decoration': 'none' },
			'a:link': { 'color': sIFRcurrentColor },
			'a:hover': { 'color': sIFRcurrentHover }
			},
		transparent: 1,
		offsetTop: -2,
		onReplacement : function(){
			//alert('replace');
			//sizeVerticals();
			this.sIFR.doCompleteCheck();
			} 
	});
	
	// H3 (non-current)
	sIFR.replace(avenir, {
		selector: '#minorContent h3:not(.current)',
		css: { 
			'.sIFR-root': { 'color': '#CCCCCC' },
			'a': { 'color': '#CCCCCC', 'text-decoration': 'none' },
			'a:link': { 'color': '#CCCCCC' },
			'a:hover': { 'color': '#FFFFFF' }
			},
		transparent: 1,
		offsetTop: -2,
		onReplacement : function(){
			//alert('replace');
			//sizeVerticals();
			this.sIFR.doCompleteCheck();
			} 
	});
	
		// H3 (non-current)
	sIFR.replace(avenir, {
		selector: 'h3:not(.current)',
		css: { 
			'.sIFR-root': { 'color': '#000000' },
			'a': { 'color': '#CCCCCC', 'text-decoration': 'none' },
			'a:link': { 'color': '#CCCCCC' },
			'a:hover': { 'color': '#FFFFFF' }
			},
		transparent: 1,
		offsetTop: -2,
		onReplacement : function(){
			//alert('replace');
			//sizeVerticals();
			this.sIFR.doCompleteCheck();
			} 
	});
	
}

sIFR.replacedCount = 0;
sIFR.doCompleteCheck = function(){
	this.replacedCount++;
	if(this.replacedCount>=this.replacements.length)
	{
		this.isDone = true;
		sizeVerticals();
		
		if ($("#divSearchResultsList").is(':visible')){
			moveDrop();
		}
		//alert('done');
	}
}; 


function showText(div) {
	// div = 'divAthleteNews'
	$(".athleteText:not(#" + div + ")").hide();
	$("#" + div).show();
	sizeVerticals();
}

function login_form() {
	document.formTW.submit();
	document.formTW.reset();
	$("#UserLogin").blur();
	$("#UserPwd").blur();
}


function sizeVerticals () {
	
	// detect which silo is shown
	var curSilo = $(".silo:visible").attr('id');
	// reset any inline height styles
	$("#mainContent").removeAttr('style');
	$(".silo").removeAttr('style');
	// re-show a silo that was visible
	$("#" + curSilo).show();
	
	
	// calculate content heights for vertical div heights
	/* CALCULATE ONLY THE HEIGHT IF THAT SILO IS SHOWN */
	leftSiloOneHeight = $("#leftSiloOne").is(':visible') ? $("#leftSiloOne").height() : 0;
	if($("#leftSiloOne").is(':visible') && $("#leftSiloOne").attr('pbtype')=='Headlines' && $("#rss").is(':visible'))
	{
		// on Headlines silo, if RSS link is there, add extra padding to bottom to compensate for absolutely positioned RSS div
		leftSiloOneHeight += 28;
	}
	leftSiloTwoHeight = $("#leftSiloTwo").is(':visible') ? $("#leftSiloTwo").height() : 0;
	
	
	/* CALCULATE THE HEIGHT OF BOTH SILOS 
	leftSiloOneHeight = $("#leftSiloOne").height();
	leftSiloTwoHeight = $("#leftSiloTwo").height();
	*/
	
	/*
	leftSiloOneHeight += parseInt($("#leftSiloOne").css('padding-top')) + $("#leftButtonOne").height();
	leftSiloTwoHeight += parseInt($("#leftSiloTwo").css('padding-top')) + $("#leftButtonTwo").height();
	*/
	leftSiloOneHeight += 58;
	leftSiloTwoHeight += 58;
	
	contentHeight = $("#mainContent").height();
	
	// Calculate viewport height and width
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	
	// Set vertical heights
	//alert($("#footer").height());
	var vertHeight = myHeight - $("#header").height() - $("#footer").height();
	//alert("vertHeight: " + vertHeight + ", contentHeight: " + contentHeight + ", leftSiloOneHeight: " + leftSiloOneHeight + ", leftSiloTwoHeight: " + leftSiloTwoHeight);
	var maxContentHeight = Math.max(vertHeight, contentHeight, leftSiloOneHeight, leftSiloTwoHeight);
	$("#mainContent").css('height', maxContentHeight + "px");
	var siloHeight = maxContentHeight - $("#leftButtonOne").height() - 27;
	$(".silo").css('height', siloHeight + "px");
}

function disableEnterKey(e)
{
     var key;

     if(window.event) {
          key = window.event.keyCode;     //IE
	 }
     else {
          key = e.which;     //firefox
	 }
	
     if(key == 13)
	 {
		 login_form();
          return false;
	 }
     else {
          return true;
	 }
}

/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
	var dumped_text = "";
	if(!level) { level = 0; }
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) { level_padding += "    "; }
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function querySt(ji,or) {
	hu = (or) ? or : window.location.search.substring(1);
	gy = hu.split("&");
	for (i=0;i<gy.length;i++) {
		ft = gy[i].split("=");
		if (ft[0] == ji) {
			return ft[1];
		}
	}
}

function addOnLoad(functionToLoad) {
	if (window.addEventListener)
	{
	  window.addEventListener('onload', functionToLoad, false); 
	} 
	else if (window.attachEvent)
	{
	  window.attachEvent('onload', functionToLoad);
	}	
}

function createCookie(name,value,days,domain) {
	var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	
	if (domain)
	{
		domain = "; domain=" + domain;
	}
	else { domain = ""; }
	var cookie = name+"="+value+expires+"; path=/"+domain;
	document.cookie = cookie;
	return cookie;
	
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') { c = c.substring(1,c.length); }
		if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length,c.length); }
	}
	return null;
}

function eraseCookie(name, domain) {
	createCookie(name,"",-1, domain);
}

function are_cookies_enabled()
{
	//var cookieEnabled = (navigator.cookieEnabled) ? true : false; // this returned true in Chrome, when cookies were enabled but an exception was added for Arc'teryx.com
	var cookieEnabled = false;
	//if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled)
	if(1) // always do it, as the above causes an escape in Chrome where navigator.cookieEnabled returns true
	{ 
		document.cookie="testcookie";
		cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
	}
	return (cookieEnabled);
}

function changeShadowboxSeason(episode) {
	var epTitle = "The Season - Episode " + episode + " - ";
	switch(episode)
	{
		case 1: epTitle += "Intro"; break;
		case 2: epTitle += "Meet Paul Kuthe, Kayaker"; break;
		case 3: epTitle += "Meet Anya Miller, Boulderer"; break;
		case 4: epTitle += "Meet Jonaven Moore, Snowboarder"; break;
		case 5: epTitle += "Meet Dr. Scott Petett, Mountain Biker"; break;
		case 6: epTitle += "Meet Matt Maddaloni, Rock Climber"; break;
		case 7: epTitle += "Anya Miller, Boulderer"; break;
		case 8: epTitle += "Paul Kuthe, Kayaker"; break;
		case 9: epTitle += "Matt Maddaloni, Rock Climber"; break;
		case 10: epTitle += "Jonaven Moore, Snowboarder"; break;
		case 11: epTitle += "Dr. Scott Petett, Mountain Biker"; break;
		case 12: epTitle += "Paul Kuthe, Kayaker"; break;
		case 13: epTitle += "Jonaven Moore, Snowboarder"; break;
		case 14: epTitle += "Anya Miller, Boulderer"; break;
		case 15: epTitle += "Matt Maddaloni, Rock Climber"; break;
		case 16: epTitle += "Dr. Scott Petett, Mountain Biker"; break;
		case 17: epTitle += "Jonaven Moore, Snowboarder"; break;
		case 18: epTitle += "Anya Miller, Boulderer"; break;
		case 19: epTitle += "Paul Kuthe, Kayaker"; break;
		case 20: epTitle += "Dr. Scott Petett, Mountain Biker"; break;
		case 21: epTitle += "Matt Maddaloni, Rock Climber"; break;
		case 22: epTitle += "Matt Maddaloni, Rock Climber"; break;
		
	}
	var href = "http://images.arcteryx.com/videos/season/Season_Episode_" + episode + ".flv";
	Shadowbox.open({
		title: epTitle,
		content: href,
		moreBeta: "The Season follows five athletes through the course of a single season in the Pacific Northwest.<br/>Watch previous episodes: <a href='javascript:changeShadowboxSeason(22)'>22</a> <a href='javascript:changeShadowboxSeason(21)'>21</a> <a href='javascript:changeShadowboxSeason(20)'>20</a> <a href='javascript:changeShadowboxSeason(19)'>19</a> <a href='javascript:changeShadowboxSeason(18)'>18</a> <a href='javascript:changeShadowboxSeason(17)'>17</a> <a href='javascript:changeShadowboxSeason(16)'>16</a> <a href='javascript:changeShadowboxSeason(15)'>15</a> <a href='javascript:changeShadowboxSeason(14)'>14</a> <a href='javascript:changeShadowboxSeason(13)'>13</a> <a href='javascript:changeShadowboxSeason(12)'>12</a> <a href='javascript:changeShadowboxSeason(11)'>11</a> <a href='javascript:changeShadowboxSeason(10)'>10</a> <a href='javascript:changeShadowboxSeason(9)'>9</a> <a href='javascript:changeShadowboxSeason(8)'>8</a> <a href='javascript:changeShadowboxSeason(7)'>7</a> <a href='javascript:changeShadowboxSeason(6)'>6</a> <a href='javascript:changeShadowboxSeason(5)'>5</a> <a href='javascript:changeShadowboxSeason(4)'>4</a> <a href='javascript:changeShadowboxSeason(3)'>3</a> <a href='javascript:changeShadowboxSeason(2)'>2</a> <a href='javascript:changeShadowboxSeason(1)'>1</a>",
		gallery: "Season"
	   }, { gallery: "Season"} );
}
