// CONTENTS ====================================================================

/*
	- DEFAULT 							- common code that runs on every page.
	- NAV	 							- ind animations
	- SUB NAV							- 'drop down' code for subnav
	- ACTIVITIES						- rotating feature images
	- LISTING							- expand / collapse functionality
	- IMAGE GALLERY						- lightbox for image gallery
*/

// VARS --------------------------------------------------------------
noFeatureImgs 	= 0;
currFeatureImg 	= -1;

// DEFAULT --------------------------------------------------------------
function InitDefault(){
	InitNav();
	InitSubNav();
	InitActivitiesNav();
	Equalise( $("#promo-pods li") );
	
	// if an img is on a D1 _without_ a youtube vid present, add a left margin to it
	if( $(".youtube-holder").length == 0 ) {
		$(".detail-image").css("margin-left", 20);
	}
	
	// if a listing item doesnt have an img, remove the width constraint on the text
	$(".listing li").each(function() {
		if ($(this).find("img").length == 0) {
			$(this).children(".copy").css("width", "auto");
			$(this).css("padding-top", "7px");
		}
	});
}

// NAV --------------------------------------------------------------
function InitNav(){
	var speed = 300;
	$("#main-nav a").not(".selected a").hover(function(){
		$(this).stop().animate({paddingTop: '41px'}, speed);
	}, function(){
		$(this).stop().animate({paddingTop: '28px'}, speed);
	});
	
	$("#activities-nav a").not(".selected a").hover(function(){
		$(this).stop().animate({paddingTop: '35px'}, speed);
	}, function(){
		$(this).stop().animate({paddingTop: '22px'}, speed);
	});
}

function InitActivitiesNav(){
	$("#activities-sub-nav li.selected").append("<span class='ind'></span>");
}

function InitSubNav() {
	$("#sub-navigation ul").addClass("enabled");
	$("#sub-navigation").css("margin-bottom", 0);
	$(".enabled").hide();
	$(".select-one").hover(function(){
		$(".enabled").show();
	}, function(){
		$(".enabled").hide();
	});
	$(".enabled a").hover(function(){
		$(".enabled").show();
	}, function(){
		$(".enabled").hide();
	});
}

//HOME
function WrapUrls(text) {
	var urlPattern = /(http:\/\/[A-Za-z0-9\.\-\/]+)/g;
	var urlsAdded = text.replace(urlPattern, '<a rel="external" href="$1">$1</a>');
	var usernames = /(@[A-Za-z0-9_]{1,15})/g;
	var usernamesAdded = urlsAdded.replace(usernames, '<a rel="external" href="http://www.twitter.com/$1">$1</a>');
	return usernamesAdded;
}

function InitTwitter() {
	var maxTweets = 1;
	var twitterAcct;
	if ($('body').hasClass('gravity')) {
		twitterAcct = "gravitycanyon";
	} else {
		twitterAcct = "taupobungy";
	}
	$.getJSON('http://search.twitter.com/search.json?q=' + twitterAcct + '&callback=?',
            function(data) {
            	$.each(data, function(i, tweets) {
            		if (tweets.length != undefined) {
            			if (tweets[0] != undefined) {
            				if (tweets[0].created_at != undefined) {
            					for (var i = 0; i < tweets.length && i < 1; i++) {
            						var extraInfo = '<span class="small italic">  - ' + timeAgo(tweets[i].created_at) + '</span>'
            						+ '<a target="_blank" href="http://www.twitter.com/' + twitterAcct + '" class="twitter-follow">Follow us on Twitter</a>';

            						$("<p>"
								        + WrapUrls(tweets[i].text) +
								        extraInfo +
							        "</p>").appendTo(".twitter-holder");
            					}
            				}
            			}
            		}
            	});
            	if ($('.twitter-holder p').length == 0 && twitterAcct == "gravitycanyon") { //If no tweets outputted, still output link to twitter
            		$('.twitter-holder').append('<p><a target="_blank" href="http://www.twitter.com/' + twitterAcct + '" class="twitter-follow">Follow us on Twitter</a></p>');
            	}
            	$('.twitter-holder p a').click(function(event) {
            		window.open(this.href);
            		event.preventDefault();
            	});
            }
        );
           }

function timeAgo(dateString) {
	var rightNow = new Date();
	var then = new Date(dateString);
	if ($.browser.msie) {
		// IE can't parse these crazy Ruby dates
		then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
	}
	var diff = rightNow - then;
	var second = 1000, minute = second * 60, hour = minute * 60, day = hour * 24, week = day * 7;
	if (isNaN(diff) || diff < 0) {
		return ""; // return blank string if unknown
	}

	if (diff < second * 7) {
		// within 7 seconds
		return "right now";
	}

	if (diff < minute) {
		return Math.floor(diff / second) + " seconds ago";
	}

	if (diff < minute * 2) {
		return "about 1 minute ago";
	}

	if (diff < hour) {
		return Math.floor(diff / minute) + " minutes ago";
	}

	if (diff < hour * 2) {
		return "about 1 hour ago";
	}

	if (diff < day) {
		return Math.floor(diff / hour) + " hours ago";
	}

	if (diff > day && diff < day * 2) {
		return "yesterday";
	}

	if (diff < day * 365) {
		return Math.floor(diff / day) + " days ago";
	}

	else {
		return "over a year ago";
	}
}


// ACTIVITIES --------------------------------------------------------------
function RotateFeatureImages(){
	$("#activity-feature-img").append('<div id=\"cover\"></div>');
	$("#cover").hide();
	noFeatureImgs = $("#activity-feature-images-src li").length;
	NewFeatureImg();
}

function NewFeatureImg(){
	
	var img = new Image();
		
		currFeatureImg ++;
		if(currFeatureImg == noFeatureImgs) currFeatureImg = 0;
		
		$(img)
		.load(function () {
			
			// img is loaded
			$("#cover").fadeIn('slow', function(){
				$("#activity-feature-img").css('background', 'url('+$(img).attr("src")+') no-repeat');
				$(this).fadeOut('slow');
				if(noFeatureImgs > 1) setTimeout(NewFeatureImg, 10000);
			})
			
		})
		.attr("src", $($("#activity-feature-images-src li")[currFeatureImg]).text() );
	
}


// ACTIVITY COUNT DETAILS -----------------------------------------------
//The webmethod called here returns the JSON data as a string representation (ie in quotes) so a
//Function is used here to return this info into a variable and therefore transform it
//Into a usable JSON structure. :D  
function InitActivityCounts() {

	$.ajax({
		url: '/webmethods/bungy.asmx/getactivitycounts',
		type: 'POST',
		contentType: 'application/json; charset=utf-8',
		dataType: 'json',
		data: '{}',
		success: function (data) {

			var jsonActivities = (new Function("return " + data.d))();

			if (jsonActivities != null) {
				$("#counts").show();
				$("#currentJumpCount").text(jsonActivities.Bungy);
				$("#currentSwingCount").text(jsonActivities.Swing);
			}
		}
	}); 
   
}

// LISTING --------------------------------------------------------------
function InitExpandListing(){
	
	// remove any empty <p>'s tinyMCE puts in there
	$(".expand-listing li .copy p").each(function(){
		if( $(this).text().length < 5 ) $(this).remove();
	});
	
	$(".expand-listing li").each(function(){
		if( $(this).find("p").length > 1 ){
			//$(this).find("p").not("p:first").hide();
			$(this).find(".expand").css("display", "block");
			/* $(this).find(".expand").toggle(function(){
				$(this).removeClass("expand");
				$(this).addClass("collapse");
				$(this).text("Collapse");
				$(this).parent().children("p").fadeIn();
			}, function(){
				$(this).removeClass("collapse");
				$(this).addClass("expand");
				$(this).text("Expand");
				$(this).parent().children("p").not("p:first").fadeOut();
			}); */
		}
	});
}


// IMAGE GALLERY --------------------------------------------------------------
var Frontend = {

	initLightbox: function() {
		$(".images li a[rel='image-gallery']").each(
			function() {
				$(this).colorbox({
					close: "Close",
					transition: 'none'
				},
				function() {
					$('#cboxTitle').css(
					{						
						'top': function() { return $('#cboxPrevious').position().top; }
					});
				}
			);
		});
	}
}

// ======================================================================

