// CONTENTS ====================================================================
/*
- DEFAULT 							- common code that runs on every page.
- NAV 								- setup top drop down nav.
- HOME								- inits a bunch of layout fixes
- QUICK MARKETS						- open / close & show key markets functionality.
- EXPAND / CONTRACT LISTINGS		- what it sez on the box really.
- SECTION HIGHLIGHTS ROTATOR		- rotates the section highlights. YARLY.
- VIDEO PLAYER						- handles playing multiple video files
*/

// DEFAULT --------------------------------------------------------------
function InitDefault() {

	// make forms submit by pressing enter in a text field.
	InitSubmitOnEnter();

	// THEME SWITCHER: for testing only
	$(".theme-switcher a").click(function() {
		$("body").attr("class", $(this).text())
		return false;
	})

	// CHROME DETECTION: just for positioning top search stuff nicely
	var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
	if (is_chrome) $("body").addClass("chrome");

	// NAV COLUMN: size nav column to full height of page for those instances where there are two main columns
	if ($("#col-main-lrg").length > 0 && $("#col-main").length > 0) {
		$("#col-nav").height($("#col-main-lrg").height() + 100)
	}
	
	// VIDEOS: set up video player if on page
	InitFlash();

	SetExternalLinks();

	// DATA TABLES: add a class to col-scoped th's so we can style them
	$("table th[scope='col']").addClass("row-head");

	// FEATURE HEADERS: floats copy up next to the img by setting a width, formats caption
	$(".feature .copy").width($(".feature").width() - $(".feature img").width());
	$(".feature .image").css("margin", 0);
	$(".feature .image p").css("width", $(".feature img").width() - 60);
	$(".feature .image p").css("left", 20);

	// NON-GRID POD LISTINGS: floats copy up next to the img by setting a width, centers image vertically if abstract is pushing out bottom
	$(".jon-martins:not(.grid-jon-martins) li").each(function() {
		if ($(this).find("img").length > 0) {
			var pad = parseInt($(this).children(".copy").css("padding-left")) + parseInt($(this).children(".copy").css("padding-right"))
			$(this).children(".copy").width($(this).width() - $(this).find("img").width() - pad);

			var imgHeight = $(this).find("img").outerHeight();
			var divHeight = $(this).innerHeight();
			if (divHeight > imgHeight) $(this).find("img").css("margin-top", (divHeight - imgHeight) / 2);
		}
	})

	// GRID POD LISTINGS: works out how many should be in row, adds a class to last in row, EQ's the pods
	$(".grid-jon-martins").each(function() {
		var inRow = Math.floor($(this).parent().width() / 250);
		var i = 0;
		$(this).children("li").each(function() {
			i++;
			if (i % inRow == 0) $(this).addClass("row-end");
		})
		// Equalise( $(this).children("li") );
		// EQ by row
		var items = $(this).children("li");
		for (var i = 0; i < ($(items).length / inRow); i++) {

			var max = 0;
			var start = (i * inRow);
			for (var j = start; j < start + inRow; j++) {
				//console.log( "> " + $( $(items)[j] ).height() );
				if ($($(items)[j]).height() > max) max = $($(items)[j]).height();
			};
			for (var k = start; k < start + inRow; k++) {
				$($(items)[k]).height(max);
			};

		};
	});

	// COUNTRY STATUS: float country status alongside the country name
	$("#status").prev().css("float", "left");
	$("#status").prev().width($("#status").prev().width());
	$("#status").width(510 - 10 - $("#status").prev().width() - parseInt($("#status").css("padding-left")));
	$("#status").addClass("active");

	// CONTENT IMAGES: size captions around variable-sized images
	$(".content-image").each(function() {
		$(this).width($(this).children("img:first").width());
	})

	// DISABLING PREV / NEXT: on pagination
	$("a.disabled").click(function() { return false; })

	// HOMEPAGE MISSING IMAGES: in featured news pod & mini pods

	if ($("#home-latest-news li:first img").length == 0) {
		$("#home-latest-news li:first p").css("margin-left", 0);
	}

	$(".mini-pods li").each(function() {
		if ($(this).find("img").length == 0) {
			$(this).find("a.pod-title, p").css("margin-left", 10);
		}
	})

}


function InitNav() {

	// collapse space-holder
	$("#main-nav-wrapper").height(0);
	// hide second level
	$("#main-nav .level-2-nav").hide();

	// hide "Latest" label from breadcrumbs
	var breadrelstr = $("#breadcrumbs li:eq(2)").text();
	breadrelstr = breadrelstr.replace(/Latest Releases/, "Releases");
	$("#breadcrumbs li:eq(2) a").html(breadrelstr);
	
	// hack to enable Christchurch Earthquake selected state
	$("#section-nav > li > a").each(function() {
		var nodeName = $(this).text();
		if ($("#ContentPlaceHolderDefault_MainContent_FilterInput").val() == nodeName) {
			
			$(this).addClass("selected");
			$("#section-nav li a").not(this).removeClass("selected ");
		};
	})
	

	var breadnewstr = $("#breadcrumbs li:eq(2)").text();
	breadnewstr = breadnewstr.replace(/Latest News/, "News");
	$("#breadcrumbs li:eq(2) a").html(breadnewstr);

	// auto-widthener - works out width of item based on char no in title.
	var widths = [];
	var noItems = 0;
	$("#main-nav > li > a").each(function() {
		var charLength = $(this).text().length - $(this).children("span").text().length;
		var newWidth = Math.max(100, charLength * 7);
		SizeItem($(this), newWidth);
		noItems++;
	})

	// If the full width is less than the container, distribute the remaining space among the items
	if ($("#main-nav").width() < $("#main-nav-wrapper").width()) {
		var remainder = $("#main-nav-wrapper").width() - $("#main-nav").width();
		var extra = Math.floor(remainder / noItems);

		$("#main-nav > li > a").each(function() {
			var newWidth = $(this).width() + extra;
			SizeItem($(this), newWidth);
		});
	}

	// take bg (dotted vert line) off item preceeding selected one
	$("#main-nav li.selected").prev().children("a:first").addClass("no-background");

	// mouseover / out
	$("#main-nav > li")
	.mouseover(function() {
		$(this).addClass("hover");
		$(this).prev().children("a:first").addClass("no-bg");
		$(this).children(".level-2-nav").show();
		if ($.browser.msie && $.browser.version < 8) $("#page").css("z-index", "-1");
	})
	.mouseout(function() {
		$(this).removeClass("hover");
		$(this).prev().children("a:first").removeClass("no-bg");
		$(this).children(".level-2-nav").hide();
		$("#page").css("z-index", "1");
	})

	// mouseover for sub a's also, as IE7 doesn't respect the hover on the li
	$(".level-2-nav a").mouseover(function() {
		$(this).parent().parent().show();
	})

}

function SizeItem(_item, _newWidth) {
	// items being resized in multiple places, therefore this helper function
	$(_item).width(_newWidth);
	// propgate widths to children
	$(_item).parent().children(".level-2-nav").width(_newWidth + 30);
}

// HOME ---------------------------------------------------------------------------
function InitHome() {

	// eq news listing items

	if (!$('.emergency-pod, .home-sidebar-news-pod').length) {
		
		Equalise($("#home-latest-news li").not("#home-latest-news li.first"));
		var i = 0;
		$("#home-latest-news li").not("#home-latest-news li.first").each(function () {
			i++;
			if (i % 3 == 0) $(this).addClass("row-end");
			if (i % 3 == 1) $(this).css("clear", "both");
		});
	}

	// styling for min-pod style listing
	$(".mini-pods ul li:last-child").addClass("last");

	// EQing promo pod & tile
	if ($("#promo-pod").height() < $("#promo-tile").height()) $("#promo-pod").height($("#promo-tile").height() - 20);

	// init campaign trail rotator
	$("#home-rotator .controls").show();
	$("#home-rotator ul").width($("#home-rotator li").length * 360)
	// size to highest of contained items
	var highest = 0;
	$("#home-rotator li").each(function() {
		if ($(this).height() > highest) highest = $(this).height();
	})
	$("#home-rotator").height(highest);
	// set button actions
	$("#home-rotator .prev").click(function() {
		HomeRotate(1);
		return false;
	})
	$("#home-rotator .next").click(function() {
		HomeRotate(-1);
		return false;
	})
	// disable the back button to start with
	$("#home-rotator .prev").css("opacity", 0.5);
	$("#home-rotator .prev").attr("disabled", "disabled");

	// making sure the "markets" heading in the diebar lines up with "what's new"
	var offsetSide = $("#markets h2").offset().top;
	var offsetMain = $("#whats-new h2").offset().top;
	var diff = parseInt(Math.max(offsetSide, offsetMain) - Math.min(offsetSide, offsetMain));
	if (offsetMain < offsetSide) {
		// extend the height of the 'latest news' pod above
		if (!$('.emergency-pod, .home-sidebar-news-pod').length) {
			$("#home-latest-news").height($("#home-latest-news").height() + diff);
		}
	} else {
		// increase the top margin on the 'markets' pod
		$("#markets").css("margin-top", 20 + diff)
	}

}

function HomeRotate(_dir) {
	var moveDist = 360;
	var gotoLeft = parseInt($("#home-rotator ul").css("left")) + (moveDist * _dir);
	$("#home-rotator ul").animate(
		{ left: gotoLeft },
		{ duration: 500 }
	);
	if (gotoLeft >= 0) {
		// no more back
		$("#home-rotator .prev").css("opacity", 0.5);
		$("#home-rotator .prev").attr("disabled", "disabled");
	} else {
		$("#home-rotator .prev").css("opacity", 1);
		$("#home-rotator .prev").attr("disabled", "");
	}
	if (gotoLeft <= 0 - ($("#home-rotator ul").width() - moveDist)) {
		// no more fwd
		$("#home-rotator .next").css("opacity", 0.5);
		$("#home-rotator .next").attr("disabled", "disabled");
	} else {
		$("#home-rotator .next").css("opacity", 1);
		$("#home-rotator .next").attr("disabled", "");
	}
}

// QUICK MARKETS ------------------------------------------------------------------
function InitQuickMarkets() {

	// key markets toggle
	$(".quick-market-access .key-markets").toggle(function() {
		$(this).text("Reveal All Markets");
		$(".quick-market-access li a").each(function() {
			if (!$(this).hasClass("key")) {
				$(this).stop().animate(
					{ opacity: 0.2 },
					{ duration: 500 }
				);
			}
		})
	}, function() {
		$(this).text("Show Key Markets");
		$(".quick-market-access li a").each(function() {
			if (!$(this).hasClass("key")) {
				$(this).stop().animate(
					{ opacity: 1 },
					{ duration: 500 }
				);
			}
		})
	});

	// switch up expand text for sidebar context
	$("#col-sidebar .quick-market-access .show-hide").text("-");

	// open / close toggle
	$(".quick-market-access .show-hide").data("state", "open");
	$(".quick-market-access .show-hide").toggle(function() {
		$(this).text("Show +");
		$("#col-sidebar .quick-market-access .show-hide").text("+");
		$(this).data("state", "closed");
		OpenMarkets();
	}, function() {
		$(this).text("Hide -");
		$("#col-sidebar .quick-market-access .show-hide").text("-");
		$(this).data("state", "open");
		CloseMarkets()
	});

}

function OpenMarkets() {
	$(".quick-market-access .col1").slideUp();
	$(".quick-market-access .col2").slideUp();
	$(".quick-market-access").addClass("QM-closed");
}

function CloseMarkets() {
	$(".quick-market-access .col1").slideDown();
	$(".quick-market-access .col2").slideDown();
	$(".quick-market-access").removeClass("QM-closed");
}

// EXPAND / CONTRACT CONTENT -------------------------------------------------------------------
function InitExpandContent() {

	var skip = 0;
	var previewText = '';

	$("#col-main .expand-content > *").each(function() {
		if (skip != 1) {
			var tag = this.tagName.toLowerCase();
			var tagOpen = '<' + tag + '>';
			var tagClose = '</' + tag + '>';
			var content = $(this).html();
			previewText = previewText + tagOpen + content + tagClose;

			if (tag == 'p') {
				skip = 1;
			}
		}
	});

	var showTextFull = "Show full content";
	var showTextMin = "Show less content";
	var showHtml = '<p class="expand-show"><strong><a class="arrow-link" href="#"><span>' + showTextFull + '</span></a></strong></p>'
	var previewHTML = '<div class="expand-preview">' + previewText + '</div>';

	if (previewText != null) {
		$("#col-main .expand-content").addClass("hidden");
		$("#col-main .expand-content").before(previewHTML);
		$("#col-main .expand-content").after(showHtml);
		$("#col-main .expand-show a").toggle(
			function() {
				$(this).parents("p").prev(".expand-content").prev(".expand-preview").addClass("hidden");
				$(this).parents("p").prev(".expand-content").removeClass("hidden");
				$(this).children("span").text(showTextMin);

			}, function() {
				$(this).parents("p").prev(".expand-content").prev(".expand-preview").removeClass("hidden");
				$(this).parents("p").prev(".expand-content").addClass("hidden");
				$(this).children("span").text(showTextFull);
			}
		);
	}
}

// EXPAND / CONTRACT LISTINGS ------------------------------------------------------------------
function InitExpandList() {

	var anchor = location.hash.substring(1, location.hash.length),
		openSingleExpanderItem = false;
	
	// close up listing
	$("#expand-listing li li").each(function () {
		var self = $(this),
			expandClass = (anchor !== this.id) ? "closed" : "open",
			show = (expandClass === "closed") ? "none" : "block";

		if (expandClass === "open") { openSingleExpanderItem = true; }
		self.addClass(expandClass);
		self.find('.item-content').css("display", show);
		if ($('.emergency-detail').length && $.browser.mozilla && expandClass === "open") {
			var top = self.position().top;
			$('html,body').scrollTop(top);
		}
	}); 

	// set up open / close
	$("#expand-listing li h3").toggle(function () {
		
		// open it
		if ($.browser.msie && jQuery.browser.version > 7) {
			$(this).siblings(".item-content").show();
		} else {
			$(this).siblings(".item-content").slideDown("fast");
		}
		$(this).parent().removeClass("closed");

		// keep track of open items in collection, if all are open change "Hide all" link to "Show all""
		var ascShowHide = $(this).parent().parent().siblings(".show-hide-all");
		$(ascShowHide).data("open", $(ascShowHide).data("open") + 1);
		if ($(ascShowHide).data("open") == $(ascShowHide).data("count")) {
			$(ascShowHide).data("state", "hide");
			$(ascShowHide).text("Hide All");
		}
	}, function () {
		// close it
		if ($.browser.msie && jQuery.browser.version > 7) {
			$(this).siblings(".item-content").hide();
		} else {
			$(this).siblings(".item-content").slideUp("fast");
		}
		$(this).parent().addClass("closed");

		// keep track of open items in collection, if all are NOT open change "Show all" link to "Hide all""
		var ascShowHide = $(this).parent().parent().siblings(".show-hide-all");
		$(ascShowHide).data("open", $(ascShowHide).data("open") - 1);
		if ($(ascShowHide).data("open") < $(ascShowHide).data("count")) {
			$(ascShowHide).data("state", "show");
			$(ascShowHide).text("Show All");
		}
	})

	// set up show / hide all
	$(".show-hide-all").each(function () {
		var count = $(this).siblings("ul").find("h3").length,
			currentOpen = openSingleExpanderItem ? 1 : 0;
		$(this).data("count", count);
		$(this).data("open", currentOpen);
		$(this).data("state", "show")
	})
	$(".show-hide-all").click(function () {
		if ($(this).data("state") == "show") {
			$(this).siblings("ul").children("li").each(function () {
				if ($(this).hasClass("closed") || $(this).hasClass("open")) $(this).children("h3").trigger("click");
				if ($(this).hasClass("open")) { $(this).removeClass("open"); } 
			});
			$(this).text("Hide All");
			$(this).data("state", "hide")
		} else {
			$(this).siblings("ul").children("li").each(function () {
				if (!$(this).hasClass("closed")) $(this).children("h3").trigger("click");
			});
			$(this).text("Show All");
			$(this).data("state", "show")
		}
		return false;
	})
}

// SECTION HIGHLIGHTS ROTATOR ------------------------------------------------------------------
var moveDist = 0;
function InitSectionHighlights() {
	$("#section-highlights li:last").css("margin-right", 0);
	var totalWidth = 0;
	$("#section-highlights li").each(function() {
		totalWidth += $(this).outerWidth(true);
	})
	$("#section-highlights ul").width(totalWidth);
	if ($("#section-highlights li").length > 4) {
		moveDist = $("#section-highlights li:first").outerWidth(true);
		// more than four, fire up controls
		$("#section-highlights").addClass("active");
		$("#section-highlights .back").click(function() {
			Rotate(1);
			return false;
		})
		$("#section-highlights .forward").click(function() {
			Rotate(-1);
			return false;
		})
	}
	// disable the back button to start with
	$("#section-highlights .back").css("opacity", 0.5);
	$("#section-highlights .back").attr("disabled", "disabled");
}

function Rotate(_dir) {
	var gotoLeft = parseInt($("#section-highlights ul").css("left")) + (moveDist * _dir);
	$("#section-highlights ul").animate(
		{ left: gotoLeft },
		{ duration: 500 }
	);
	if (gotoLeft >= 30) {
		// no more back
		$("#section-highlights .back").css("opacity", 0.5);
		$("#section-highlights .back").attr("disabled", "disabled");
	} else {
		$("#section-highlights .back").css("opacity", 1);
		$("#section-highlights .back").attr("disabled", "");
	}
	var farLeft = $("#section-highlights li").length * moveDist - (4 * moveDist);
	if (gotoLeft <= 30 - farLeft) {
		// no more fwd
		$("#section-highlights .forward").css("opacity", 0.5);
		$("#section-highlights .forward").attr("disabled", "disabled");
	} else {
		$("#section-highlights .forward").css("opacity", 1);
		$("#section-highlights .forward").attr("disabled", "");
	}
}

// VIDEO PLAYER ------------------------------------------------------------------
function InitFlash() {

	//$("form:first").after("<form></form>");
	//$("div:first").before("<form><!-- hi --></form>");

	/*
	var vars 		= {};
	var params 		= { allowFullScreen:'true' };
	var attributes 	= { id: 'vplayer', name: 'vplayer' };
	swfobject.embedSWF("/flash/NZTVideoPlayer.swf", "player", "510", "382", "9.0.0", "/flash/expressInstall.swf", vars, params, attributes, function(){
	//
	});
	window.["vplayer"] = document.forms[0].["vplayer"] ;
	//swfobject.addDomLoadEvent(fixReference);
	*/
	($(".video-list li").length == 1) ? $(".video-list").hide() : $(".video-list").show();
	$("#flash-video-player").height(382);
}

function fixReference() {
	window["vplayer"] = document.forms[0]["vplayer"];
}


function thisMovie(movieName) {
	// return flash obj to address
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	}
	else {
		return document[movieName];
	}
}

function FlashPlayerReady() {
	// called from flash video player once it's initialised - call back into flash for the data for the first vid in the list
	thisMovie("vplayer").InitFirst($(".video-list li:first .vid-image-path").text(), $(".video-list li:first a").attr("href"));
	$(".video-list li:first a").addClass("selected");
	SetText($(".video-list li:first a"));
	// set up clicks on other items
	$(".video-list li a").click(function() {
		$(".video-list li a").removeClass("selected");
		$(this).addClass("selected");
		thisMovie("vplayer").PlayVideo($(this).attr("href"), $(this).find(".vid-aspect-ratio").text());
		SetText($(this));
		return false;
	})
}

function SetText(_selected) {
	// set title / abstract for the selected video
	var title = $(_selected).clone().children().remove().end().text();
	$(".video h5:first").text(title);
	$(".video p:first").text($(_selected).children(".vid-abstract").text());
}


// ======================================================================

// Twitter Reader =======================================================

$.fn.tweetify = function() {
	this.each(function() {
		$(this).html(
			$(this).html()
				.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi, '<a href="$1/index.htm">$1</a>')
				.replace(/(^|\s)#(\w+)/g, '$1<a href="../../search.twitter.com/search_C14ADE23">#$2</a>')
				.replace(/(^|\s)@(\w+)/g, '$1<a href="../../www.twitter.com/$2/index.htm">@$2</a>')
		);
	});
	return $(this);
}

var Twitter = {
    Init: function(list, twitterAcct) {
        var maxTweets = 2;
        list.find("li").remove();
        $.getJSON('http://twitter.com/statuses/user_timeline/' + twitterAcct + '.json?count=' + maxTweets + '&callback=?', function(data) {
            if (data != null) {
                for (var i = 0; i < data.length && i < maxTweets; i++) { //tweets[i].text.substring(0, 2) == "RT" ||
                    //!tweets[i].text.search("RT @")) || tweets[i].text.substring(0, 2) == "RT" ||
                    //if (tweets[i].from_user != twitterAcct) { maxTweets++; }

                    var statusHtml = $('<li> ' + data[i].text + ' <em>' + timeAgo(data[i].created_at) + '</em></li>').tweetify();
                    list.append(statusHtml);
                }
                Twitter.Balance();
            } else {}
        });
    },
    Balance: function() {
        Equalise($("#promo-and-twitter .item"));
        $("#twitter-pod").height(($("#twitter-pod").height() + 1));
        if ($.browser.msie && parseInt(jQuery.browser.version) == 7) {
            $("#twitter-pod").height(($("#twitter-pod").height() - 1));
        }
    }
}

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) { 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"; }
}

// Google Analytics File Download Tracker =================================================
var GA_FileDownload = {
    Init: function() {
        $("a[href$=.zip],a[href$=.pdf],a[href$=.doc],a[href$=.docx],a[href$=.xls],a[href$=.xlsx],a[href$=.ppt],a[href$=.pptx]").click(function() {
            if (typeof(pageTracker) != "undefined") {
                pageTracker._trackPageview($(this).attr("href"));
            }
        });
    }
}
