// hide article text until paginated
if($('.article_text').length > 0) {
	$('.article_text').addClass("hidden");
}

$('html').addClass('js');

/* set variables used by international pages/navigation */
	var is_jquery = (typeof($.fn)!="undefined");
	var country = ((window.location && window.location.host && window.location.host.toString().match(/(uk|au|in)$/i)) ? (RegExp.$1+'').toLowerCase() : ( (window.location && window.location.search && ( (window.location.search+'').match(/intl_test=(uk|au|in)/i) ) )?RegExp.$1:"us"));
	var intl = (country == "uk" || country == "in" || country == "au") ? true : false;
	if( (typeof(intl)!="undefined" && typeof(is_jquery)!="undefined") && (intl==true && is_jquery==true) ) {
		var subsURLs = {
			uk_url: "https://w1.buysub.com/servlet/OrdersGateway?cds_mag_code=NGM&cds_page_id=37881&cds_misc_5=UKSUBSPAGE9",
			au_url: "https://w1.buysub.com/pubs/NG/NGM/AustraliaOfferPage.jsp?cds_page_id=43433&cds_mag_code=NGM&id=1257202432253&lsid=93061649559028839&vid=4&cds_misc_5=AUSPAGE3",
			in_url: "https://w1.buysub.com/pubs/NG/NGM/31671.jsp?cds_page_id=31671&cds_mag_code=NGM&id=1265136534789&lsid=30331244387037068&vid=6&cds_misc_5=OTHER3"
		};
		var tvURLs = {
			uk_url: "http://www.natgeochannel.co.uk",
			au_url: "http://natgeotv.com.au",
			in_url: "http://www.natgeotv.co.in"
		};
		var homeURLs = {
			uk_url: "http://www.nationalgeographic.co.uk",
			au_url: "http://nationalgeographic.com.au",
			in_url: "http://www.nationalgeographic.co.in"
		}
		$('body').addClass('intl');
		subsURL = subsURLs[country+'_url'];
		tvURL = tvURLs[country+'_url'];
		homeURL = homeURLs[country+'_url'];
	}

/* $(document).ready() code -- executed after page load completes */

$(document).ready(function() {
	/*---- DL Code ----*/
	if( ($('div.dl').length > 0) && (typeof($.fn.dynamiclead) != "undefined") ) {
		$('div.dl h3').addClass('hidden');
		$('div.dl .credit').removeClass('hidden');
		
		$('div.dl ul').dynamiclead({
			slideArray: ((typeof(DLslides)!="undefined")?DLslides:[{url:'',link:'',headline:'',caption:''}])   
        });
        		
	}
	
	/*---- Put label text inside input for Newsletters ----*/
	if($("#newsletter input").length > 0) { 
		$("#newsletter input").labelify({ text: "label" });
	}
	
	/*---- Initialize Carousels ----*/
	if($('div.carousel').length > 0) {
		$('div.carousel .fact_slides').jcarousel({
	   		scroll: 1,
	   		visible: 1,
	   		initCallback: fact_slides_initCallback, 
	   		itemFirstInCallback: fact_slides_itemFirstInCallback
		});
		if($('div.fact_slides .jcarousel_prev').length > 0) {
			$('div.fact_slides .jcarousel_prev').after()
		}
		$('div.carousel .three').jcarousel({
			scroll: 3,
			visible: 3
		});
	
		$('div.carousel .seven').jcarousel({
			scroll: 7,
			visible: 7
		});
		$('div.carousel .five').jcarousel({
			scroll: 5,
			visible: 5
		});
	    $('div.carousel .one').jcarousel({
			scroll: 1,
			visible: 1
	    });
	    $('div.carousel .two').jcarousel({
			scroll: 2,
			visible: 2
	    });
	    $('div.carousel .four').jcarousel({
			scroll: 4,
			visible: 4
	    });
    	
		$('div.carousel .magazine').jcarousel({
			scroll: 5
		});
	
		$('ul.magazine li:nth-child(5n), ul.magazine li:last').css('border', 'none');
	
		if ($('ul.magazine li').length == 5) {
		    $('.magazine div.jcarousel-prev, .magazine div.jcarousel-next').hide();
	    }else{
	        $('.magazine div.jcarousel-prev, .magazine div.jcarousel-next').show();
		};
	}
	/*---- Build link list columns ----*/
	if($('.columns ol, .columns ul').length > 0) {
		$(' .columns ol, .columns ul').each(function() {
	    	if (!($(this).parent().parent().hasClass('full_width'))) {
	        	$(this).columns({
	            	cols:2
	        	});
	    	}else {
	        	$(this).columns({
	            	cols:3
	        	});
	    	}
		});
	}
	/*---- Share Button Home Code ----*/
	if($('body.home #share, body.level_2 #share').length > 0) {
		$('body.home #share, body.level_2 #share').addClass('collapsed');
	}
	if($('#nav_share').length > 0) {
		$('#nav_share li a').addClass('hiddenText');
		$('#nav_share li').slice(4).addClass('hidden');
		$('#nav_share').append('<li class="more_link"><a href="">More</a></li>');
		var moreLink = $('#nav_share .more_link');
		moreLink.click(function () { 
			$('#share').toggleClass('collapsed');
			$('#nav_share li').slice(4, -1).toggleClass('hidden');
			if (moreLink.text() =='More'){
				moreLink.html('<a href="">Collapse</a>');				
			} else {
				moreLink.html('<a href="">More</a>');
			}
			return false;
		});
	}
	/*---- Hide Share Email Form ----*/
	if($('#share_email').length > 0) {
		$('#share_email').addClass('hidden');
	}
	/*---- Prepend Print Link to Article Rating div ----*/
	// Causing some error, possibly related to Share Links scripts; user not affected - LB 061009
	if($('#article_rating').length > 0) {
		$('#article_rating').before('<div id="print_link"><a href="#" onclick="ngsprint();return false;">Printer Friendly</a></div>');
	}
	/*---- Most Popular Tabs Code ----*/
	if($('div.tabbed_box').length > 0) {
		$('div.tabbed_box').each(function() {
			// Show just the first tab
			var sections = $('.popularity_type', this);
			sections.hide();
			$(sections[0]).show();
	
			// Build the tab-links
			var ul = $('<ul class="nav nav_tabbed">');
			sections.each(function(index) {
				var section_obj = $(this);
				var heading = $('h4', this).html();
				var li = $('<li class="nav_0'+(index+1)+'">');
				$('h4', this).remove();
				li.append(
					$('<h4><a href="#">'+heading+'</a></h4>').click(function() {
						// Show just this section.
						sections.hide();
						section_obj.show();
				
						// And mark just this tab
						tabs.removeClass('selected');
						li.addClass('selected');
						return false;					
				}));
				ul.append(li);
			})
		
			$('div.wrap', this).before(ul);
	
			// Compile the list of new tabs we just made, and select the first one.
			var tabs = $('li', ul);
			$(tabs[0]).addClass('selected');
		});
	}
	/*---- Table Striping ----*/
	if($('table.striped').length > 0) {
		$('table.striped tr:odd').css('background-color','#f4f4f4');
	}
	/*---- Article Rating functionality ----*/
	

	/*---- Article Pagination functionality ----*/
	// check for the article content container by class
	if(typeof pageSet != "undefined" && $('.article_text').length > 0) {
		// create a new pageSet object
		articlePages = new pageSet({
			oPageContainer:((typeof($)!="undefined")?$(".article_text")[0]:document.getElementsByClassName('article_text')[0]),
			oMatchRE:new RegExp("page_*break"),
			strMatchTagName: "comment",
			activePageIndex:jss.current_page(),
			pageItemClass: "article-page-item",
			callback: function(delaySecs) { 
				delaySecs=((delaySecs&&!isNaN(parseInt(delaySecs)))?parseInt(delaySecs):.5);
				if(typeof(ngsPageView)!="undefined") {
					// WORKAROUND FOR AddThis & Omniture 's' variable name conflict
					//s=((typeof(s)=="undefined")?{}:s);
					//s.t=((typeof(s.t)=="undefined")?function(){ if(typeof(ngsAdvertisingRefresh)!="undefined") { ngsAdvertisingRefresh(); } }:s.t);
					if(typeof(callTmr)!="undefined"){ 
						clearTimeout(callTmr); 
					};
					callTmr = setTimeout("ngsPageView();",(delaySecs*1000));
				}
			}
		});

		if(articlePages.pages.length>1) {
			$($(".article_text").get(0)).append('<div class="nav-article-pages pagination"></div>');
			$(".nav-article-pages").pagination(Math.ceil(articlePages.pages.length), {
				items_per_page:1,
				num_display_entries: 14,
				current_page: jss.current_page(),
				callback:articlePages.viewPage,
				link_to: "#"+articlePages.hashVar+"=__id__",
				prev_text: "&laquo; Previous",
				next_text: "Next &raquo;"
			});
			articlePages.viewPage(articlePages.activePageIndex);
			articlePages.readyState = "4:COMPLETED";
		}
		$('.article_text').removeClass("hidden");
	}
	
	if(FlashApps[0] != undefined){ loadFlashApps();}
	if(rssFeeds[0] != undefined){ loadRssReaders();}
	if(typeof(VEMaps)!="undefined" && typeof(VEMaps[0]) != "undefined" && VEMaps[0] != undefined) {loadVEMaps();}
	
	/*---- Set Equal Heights on Columns ----*/
	$('.homepage .subsection, .homepage #content_page_specific, .article .subsection, .small_article .subsection, .home .subsection, .article #content_page_specific, .small_article #content_page_specific, .home #content_page_specific, .level_2 #content_page_specific, .level_2 #content_page_specific .subsection, .a_z #content_page_specific').equalHeights(true);	
	
	getLoadTimes();
});

/*---- Print function ----*/
function ngsprint() {
	window.print();
}

jQuery.expr[':'].regex = function(elem, index, match) {
  	var matchParams = match[3].split(','),
	validLabels = /^(data|css):/,
	attr = {
		method: matchParams[0].match(validLabels) ? matchParams[0].split(':')[0] : 'attr',
		property: matchParams.shift().replace(validLabels,'')
	},
	regexFlags = 'ig',
	regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
	return regex.test(jQuery(elem)[attr.method](attr.property));
}

getLeadingZeros  = function(opts) {
	var n = ((typeof(opts['n'])!="undefined"&&!isNaN(parseInt(opts['n'])))?opts['n']:0);
	var digits = ((typeof(opts['digits'])!="undefined"&&!isNaN(parseInt(opts['digits'])))?opts['digits']:3);
	return ((n.toString().length>=digits)?n:( (n + 1) * parseFloat( parseFloat('0').toFixed( digits - 1 ) + 1 ) ).toFixed(digits).toString().split('.')[1]);
}

/* FUNCTION: wrapByRegEx({parentSelectorText:[STRING],matchRegEx:[REGULAR EXPRESSION or ARRAY OF REGULAR EXPRESSIONS],wrapHTML:[STRING or ARRAY OF STRINGS],idDigits:[NUMBER]})
--- wraps matching text nodes with supplied HTML snippet, using id attribute if [[id]] is present in the HTML snippet and idDigits > 0  ---
*/
wrapByRegEx = function(opts) {
	var parentSelectorText = ((typeof(opts["parentSelectorText"])!="undefined")?opts["parentSelectorText"]:null);
	if(parentSelectorText==null) {
		return false;
	}
	var idDigits = ((typeof(opts["idDigits"])!="undefined"&&!isNaN(parseInt(opts["idDigits"])))?parseInt(opts["idDigits"]):-1);
	var matchRegEx = ((typeof(opts["matchRegEx"])!="undefined")?((typeof(opts["matchRegEx"])!="string"&&typeof(opts["matchRegEx"].length)!="undefined")?opts["matchRegEx"]:[opts["matchRegEx"]]):null);
	var wrapHTML = ((typeof(opts["wrapHTML"])!="undefined")?((typeof(opts["wrapHTML"])!="string"&&typeof(opts["wrapHTML"].length)!="undefined")?opts["wrapHTML"]:[opts["wrapHTML"]]):null);
	var s_regExCombined = "";
	var is_ignoreCase = false;
	$(matchRegEx).each(function(i){
		s_regExCombined += "("+this.source + ")"+((i==matchRegEx.length-1)?"":"|");
		is_ignoreCase = ((this.ignoreCase)?true:is_ignoreCase);
	});
	var combinedMatchRegEx = new RegExp(s_regExCombined,((is_ignoreCase)?"i":""));
	var n = 1;
	var a_allNodes = $(parentSelectorText)
	.contents()
	.filter( function() {
		if((this.nodeType == Node.TEXT_NODE) && (this.data+'').match(combinedMatchRegEx)!=null) {
			var s_nodeData = (this.data+'');
			var o_textNode = this;
			$(matchRegEx).each(function(i){
				if(s_nodeData.match(this)) {
					var s_matchFlags = ( (this.ignoreCase) ? "i":"" ) + ( (this.global) ? "g":"" ) + ( ( this.multiline)?"m":"" );
					var matchRE = ( ( (this.source+'').match(/(^|[^\\])\(|[^\\]\)/) ? this : new RegExp( "(" + this.source + ")" , s_matchFlags ) ) );
					var is_useMatchText = (wrapHTML[i].match(/\[\[matchText\]\]/) != null);
					var s_wrapped = ( (idDigits) ? 
						wrapHTML[i].replace( /\[\[id\]\]/g, getLeadingZeros({n:n,digits:idDigits}) ) :
					 	wrapHTML[i] );
					var s_wrapped = ( (is_useMatchText) ? s_wrapped.replace(/\[\[matchText\]\]/gi,"\$1") : s_wrapped);
						var s_replaceText = s_nodeData.replace( matchRE , s_wrapped );
						$(o_textNode).replaceWith(s_replaceText);
					n++;
				}
			});
		} 
	});
}

parseXML = function(xml) {
	if( window.ActiveXObject && window.GetObject ) {
		var dom = new ActiveXObject( 'Microsoft.XMLDOM' );
		dom.loadXML( xml );
		return dom;
    }
    if( window.DOMParser ) {
		return new DOMParser().parseFromString( xml, 'text/xml' );
	}
    throw new Error( 'No XML parser available' );
}


// NG RICH MEDIA FUNCTIONS
var FlashApps = [];
addFlashApp = function(dataObj){
	FlashApps.push(dataObj);
}

loadFlashApps = function(){
	var totApps = FlashApps.length;
	for(var i=0;i<totApps;i++){
		createFlashObject(FlashApps[i]);
	}
}
createFlashObject = function(dataObj){
	$(dataObj.div).css("visibility","visible");
	if(dataObj.customXML){
		loadSWF();
	} else {
		var richMediaXML;
		parseRichMediaXML();
	}
	function parseRichMediaXML(){
		try {
			richMediaXML = parseXML(dataObj.currentXML);
		} catch(err) {
			$(dataObj.div).append("<p><strong>ERROR PARSING XML</strong></p>");
		}
		loadSWF();
	}
	function loadSWF(){
	
		var params = {};
		params.allowscriptaccess = "always";
		params.wmode = (dataObj.type == "Quiz") ? "transparent" : "opaque";
		params.menu = "false";
		params.quality = "best";
		params.bgcolor = "#FFFFFF";
		params.base = dataObj.filePath;
		
		//Javascript workaround until the Object tag is working
		var tempSite = window.location.host;
		var siteDomain = "http://" + tempSite;
		
		var flashvars = {};
		flashvars.css = dataObj.css;
		flashvars.siteDomain = siteDomain;
		
		// For Dynamic content that needs dimensions\\\\\\\\\\\\\\\\\
		flashvars.width = dataObj.width;
		flashvars.height = dataObj.height;
	
		// QUIZ ////////////////////////////////////////////////////
		if(dataObj.type == "Quiz"){
			flashvars.cssFile = flashvars.css;
			flashvars.imagePath = dataObj.filePath;
			flashvars.parentDiv = dataObj.parentDiv;
		}
		// END QUIZ \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
	
		if(dataObj.customXML){
			flashvars.xml = dataObj.xmlURL;
			flashvars.xmlfile = dataObj.xmlURL;// for quizzes
			flashvars.xmlFile = dataObj.xmlURL;// for other interactives
		} else {
			if(dataObj.xml != ""){
				flashvars.xml = dataObj.xml;
				flashvars.xmlfile = flashvars.xml;// For quizzes
				flashvars.xmlFile = flashvars.xml;// For other interactives
			}
			$(richMediaXML).find("richmedia").children().each(function(){
				flashvars[this.tagName] = $(this).text();
			});
		};
	
		var attributes = {};
		attributes.id = dataObj.slug;
		
		if(dataObj.width == undefined||dataObj.width == ""||dataObj.height == ""||dataObj.height == undefined||dataObj.version == ""||dataObj.version == undefined){
			$(dataObj.div).append("<p><strong>ERROR IN RICH MEDIA TYPE: Please check your settings</strong></p>");
			return;
		} else {
			swfobject.embedSWF(dataObj.flashURL, dataObj.slug, dataObj.width, dataObj.height, dataObj.version, false, flashvars, params, attributes);
		}
	}
}

loadVideo = function(div,slug){
	var params = {allowfullscreen:true,allowscriptaccess:"always",wmode:"opaque",menu:"false",quality:"best",bgcolor:"#FFFFFF"};
	var flashvars = {vid:slug};
	var attributes = {id:slug};
	swfobject.embedSWF("http://video.nationalgeographic.com/video/player/flash/syndicatedVideoPlayer.swf", div, "400", "334", "8", false, flashvars, params, attributes);
}

// INTERACTIVE MAP FUNCTIONS
var VEMaps = [];
addMapToPage = function(mapObj){
	VEMaps.push(mapObj);
}

loadVEMaps = function(){
	for(var i=0;i<VEMaps.length;i++){
		renderVEMap(VEMaps[i]);
	}
}

renderVEMap = function(mapObj){
	var bingMap = null;
	bingMap = new VEMap(mapObj.div);
	bingMap.LoadMap(new VELatLong(mapObj.latitude,mapObj.longitude), mapObj.zoom, mapObj.viewType, mapObj.lockMap);
	if(mapObj.showMini)bingMap.ShowMiniMap(mapObj.miniXposition, 5);
	if(!mapObj.showTools)bingMap.HideDashboard();
}

//Carousel Callback

function fact_slides_initCallback(carousel) {
    var count = $('ul.fact_slides li').length;
    $('div.fact_slides .jcarousel-prev').after('<p class="count"><span class="current"></span> of '+count+'</p>');
};


function fact_slides_itemFirstInCallback(carousel, idx, item) {
   $('div.fact_slides span.current').html(item);

};

var taxonomy;
var hasTaxonomy = false;
function highlightNavItem(){
	var navClass;
	if(taxonomy.site == 'environment.nationalgeographic.com'){
		navClass = '#navigation_tophat_primary li.nav3 ul li:contains('+taxonomy.name+')';
		if($(navClass).length == 0)return;
	} else if(taxonomy.site == 'photography.nationalgeographic.com'){
		navClass = '#navigation_tophat_primary li.nav2 ul li:contains('+taxonomy.name+')';
		if($(navClass).length == 0)return;
	} else if(taxonomy.site == 'travel.nationalgeographic.com'){
		navClass = '#navigation_tophat_primary li.nav4 ul li:contains('+taxonomy.name+')';
		if($(navClass).length == 0)return;
	} else {
		return;
	}
	
	$(navClass).addClass('highlighted');
	
}

var loadTimes = {}
timerCount = function(prop){
	var curTime = new Date().getTime();
	var elapsedTime = curTime - startTime;
	loadTimes[prop] = elapsedTime;
}

getLoadTimes = function(){
	for(var timeStamp in loadTimes){
		$('#test_comments').append('<p>'+timeStamp+' = '+loadTimes[timeStamp]+' ms</p>')
	}
}

var rssFeeds = [];
addRSSFeed = function(rssObj){
	rssFeeds.push(rssObj);
}

loadRssReaders = function(){
	if(typeof($.jGFeed)=="undefined"){
		$('div.rssReader').remove();
		return;
	}
	var totFeeds = rssFeeds.length;
	for(var i=0;i<totFeeds;i++){
		var itemCount = rssFeeds[i].count;
		var resultsDiv = rssFeeds[i].div;
		var rssURL = rssFeeds[i].feed;
		
		$.jGFeed(rssURL,
		function(feeds){
			if(!feeds){
				$('#'+resultsDiv).append("<p>ERROR LOADING RSS FEED</p>");
				return false;
			}
			$('#rss_loading').remove();
			var html = '<ul class="bullets">';
			for(var j=0; j<itemCount; j++){
				var item = feeds.entries[j];
				html += '<li><a href="'+item.link+'">'+item.title+'</a>'+'</li>';
			}
			html += '</ul>';
			$('#'+resultsDiv).append(html);
		}, itemCount);
	}
}