$(function() {
    // ExpandNav();
    Format();
    //EmailPagePrivacyPolicyCheck();
    InitCollapseList();
    PrintPage.Init();
    AddThis.Init();

    if ($('.people-listing').length > 0) {
        InitPeopleList();
    }
    if ($(".map-list-view").length > 0 && $(".map-list-view").attr('id') != 'compare-country-form') { /* Don't run for Compare Country list form page */
        InitExploreExportMarketsMap();
        mapJumpListInit(); //should rename?
    }
    if ($(".region-list").length > 0) {
        Frontend.RegionalMap.init();
    }
    if ($(".pod-gallery").length > 0) {
        Frontend.ImageGallery.Init();
    }
    if ($(".grants-selection").length > 0) {
        grantSelectionResult();
    }
    if ($(".toolkit").length > 0) {
        Frontend.ToolKit.Init();
    }
    InitVideoPlayer();
});

// GLOBAL FUNCTIONS ===============================================================

function IsCookiesEnabled()
{
	var cookieEnabled = (navigator.cookieEnabled) ? true : false;
    var TEST_COOKIE = "testcookie";
    
	if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled)
	{ 
		document.cookie = TEST_COOKIE;
		cookieEnabled = (document.cookie.indexOf(TEST_COOKIE) != -1) ? true : false;
	}
	
	return (cookieEnabled);
}

//function ExpandNav(){
//	$("#expand-button").show();
//	
//	$("#expand-button").hover(function(){
//		$(this).css("text-decoration", "underline");
//	},function(){
//		$(this).css("text-decoration", "none");
//	});
//	
//	$("#expand-button").click(function(){
//		$(this).css("text-decoration", "none");
//		if($(this).hasClass("expand")){
//			$(this).removeClass("expand");
//			$(this).addClass("collapse");
//			$("#expanded-navigation").slideDown("fast");
//			$(this).text("Hide Full Menu");
//		}
//		else {
//			$(this).removeClass("collapse");
//			$(this).addClass("expand");
//			$("#expanded-navigation").slideUp("fast");
//			$(this).text("See Full Menu");
//		}
//	});
//}

function EmailPagePrivacyPolicyCheck(){
       
    if($("#ctl00_PageHolder_ContentPlaceHolder_EmailThisPageForm_DisplayModePanel_ReadPrivacyStatementCheckBox").length > 0){
        if($("#ctl00_PageHolder_ContentPlaceHolder_EmailThisPageForm_DisplayModePanel_ReadPrivacyStatementCheckBox").is(":checked")){
        $('#ctl00_PageHolder_ContentPlaceHolder_EmailThisPageForm_DisplayModePanel_imgbtnSubmit').removeAttr('disabled');
        }
	    else {
            $('#ctl00_PageHolder_ContentPlaceHolder_EmailThisPageForm_DisplayModePanel_imgbtnSubmit').attr('disabled', true);
        } 
    }
    
    $("#ctl00_PageHolder_ContentPlaceHolder_EmailThisPageForm_DisplayModePanel_ReadPrivacyStatementCheckBox").click(function(){
		if($(this).is(":checked")){
            $('#ctl00_PageHolder_ContentPlaceHolder_EmailThisPageForm_DisplayModePanel_imgbtnSubmit').removeAttr('disabled');
		}
		else {
            $('#ctl00_PageHolder_ContentPlaceHolder_EmailThisPageForm_DisplayModePanel_imgbtnSubmit').attr('disabled', true);
        }
	});
}

function Format(){
	// general ops to format various items
	
	// search box 
	// set the default "Search" text 
	$("#search .text-field").focus(function(){
		$(this).val("");
	});
//	$("#search .text-field").blur(function(){
//		$(this).val("Search");
//    });

    // format listing paragraphs to col if they have image
    $(".listing > ul > li").each(function() {
    	if ($(this).find('img').length > 0) {
    		$(this).children("p, ul.hilited-links, div.full-copy").each(function() {
    			if ($(this).hasClass('back-to-top') != true) {
    				var marginwidth = ($(this).parent('li').find('img').width() + 13);
    				var paragraphwidth = $(this).parent('li').width() - marginwidth; // 506
    				$(this).css('margin-left', marginwidth);
    				$(this).css('width', paragraphwidth);
    			}
    		});
    	}
    });
}

// hover behaviours
function InitExploreExportMarketsMap() {

    $('#landing-content').removeClass('country-list');
    if ($("#landing-content .map-list-view-hide").length > 0) {
        $("#map-nav li").removeClass("selected");
        $("#landing-content p.abstract").hide().attr("style", "width:840px;");
        $("#landing-content .map-list-view").attr("style", "visibility:visible;").hide();
    } else {
        var el = $(".map-list-view");
        $("#landing-content .map-list-view").attr("style", "visibility:visible;");
        el.removeClass("map-list-view");
        el.addClass("map-viewport");
        $(".country").removeClass("hidden");
        $("h4").removeClass("hidden");
        Frontend.ExportMap.init();

        $("li.list-view-tab").removeClass("selected");
        $('#landing-content p.abstract').show()
        //$(this).addClass("selected");
    }

    $('div.country-compare').show();
    $('.country').mouseover(mapHoverPanel);

    $(".map-nav .tab").click(
    function() {
        if (!$(this).hasClass("list-view-tab")) { // if map-view clicked
            $('div#landing-content').show();
            var el = $(".map-list-view");
            el.parent().removeClass("country-list");
            el.removeClass("map-list-view");
            el.addClass("map-viewport");

            $(".map-list-view").show();
            $(".map-viewport").show();

            $(".country").removeClass("hidden");
            $("h4").removeClass("hidden");
            Frontend.ExportMap.init();

            $("li.list-view-tab").removeClass("selected");
            $(this).addClass("selected");

            $('.country').mouseover(mapHoverPanel);

        } else {

            $('div.map-info-panel').remove();
            $(".country").unbind("mouseover");
            $('div#landing-content').show();
            var el = $(".map-viewport");
            el.parent().addClass("country-list");
            el.removeClass("map-viewport");
            el.addClass("map-list-view");

            $(".map-list-view").show();
            $(".map-viewport").show();

            $("h4.zoom").each(function() {
                $(this).find("span:first").replaceWith($(this).find("span:first").html());
                $(this).find("span").remove();
            });

            $(".country").fadeIn(50).removeClass("hidden");
            $("h4").fadeIn(50).removeClass("hidden");
            $(".map-view").css("display", "block");
            $(".zoom-out").remove();

            $("li.map-view-tab").removeClass("selected");
            $(this).addClass("selected");

        } return false;
    });

    $(".map-nav-close li.close a").click(function() {
        $('div#landing-content').hide();
    });

    // MAP - COUNTRY INFO ON ROLLOVER  
    function mapHoverPanel() {

        $('div#world-view').addClass('disabled');
        $('div.map-info-panel').remove();
        $('.country').show();

        var elClass = $(this).attr("class").replace(/country /, "");
        var elPos = $(this).position();
        var elWidth = $(this).width();
        var elLink = $(this).find("a:first");
        var elHref = elLink.attr('href');
        var elTitle = elLink.text();
        var elFlag = $(this).prev().html();

        if (($(elLink).hasClass("rightind") && elPos.left > 160) || ($(elLink).attr('class') == '' && elPos.left > 762)) {
            var floatSide = 'float-right';
            var leftPos = elPos.left - (187 - elWidth);
        } else {
            var floatSide = '';
            var leftPos = elPos.left;
        }

        if (elPos.top > 187) {

            if ($(".map-info-panel." + elClass).length == 0) {
                $("#world-view").after('<div class="map-info-panel ' + elClass + '"><span class="top"></span><div class="self-clear down"><h5>' + elFlag + '<a href="' + elHref + '" onclick=dcsMultiTrack("DCSext.map_zoom_loc",' + elTitle + ');>Country overview</a></h5></div></div>');

                var el = $(".map-info-panel." + elClass);
                var btmPos = 375 - (elPos.top + 47);

                el.find("div:first").append($(this).find("ul:first").clone()); // Clone the UL content and add to div
                el.find("div.down").after('<div class="down-title ' + floatSide + '"><h4><span><a href="' + elHref + '" onclick=dcsMultiTrack("DCSext.map_zoom_loc",' + elTitle + ');>' + elTitle + '</a></span></h4><span class="end"></span></div>'); // Add country name to H5 tag after div
                $(el).css({ 'top': 'auto', 'bottom': btmPos, 'left': leftPos });
            }
        } else {

            if ($(".map-info-panel." + elClass).length == 0) {
                $("#world-view").after('<div class="map-info-panel ' + elClass + '"><div></div><span class="bottom"></span></div>');

                var el = $(".map-info-panel." + elClass);

                el.find("div:first").append('<div class="title ' + floatSide + '"><h4><span><a href="' + elHref + '" onclick=dcsMultiTrack("DCSext.map_zoom_loc",' + elTitle + ');>' + elTitle + '</a></span></h4><span class="end"></span></div><h5>' + elFlag + '<a href="' + elHref + '" alt="' + elTitle + '">Country overview</a></h5>'); // Insert heading div with title 
                el.find("h5").after($(this).find("a:first").next().clone()); // Clone the <ul> which follows the country name
                $(el).css({ 'left': leftPos });
            }
        }

        var cName = $(this);
        $(el).stop(true, true).fadeIn(500);

        $("div.map-info-panel").hover(function() {
            $(cName).hide();
        },
		function() {
		    $(this).remove();
		    $(cName).show();
		});
    }

}



    //************commented out and replaced with mapHoverPanel function as part of Terabyte update 1.30
//    $(".country").unbind("mouseover");
//    $(".country").mouseover(function() {

//        var elClass = $(this).attr("class").replace(/country /, "");

//        if ($(".map-info-panel." + elClass).length == 0) {
//            $("#world-view").after('<div class="map-info-panel ' + elClass + '"><div></div><span></span></div>');
//            var el = $(".map-info-panel." + elClass);
//            el.find("div:first").append($(this).find("a:first").text())
//            .prepend($(this).prev().html())
//            .wrapInner("<h5></h5>");
//            el.find("div:first").append($(this).find("a:first").next().clone());
//        }

//        $(".map-info-panel." + elClass).stop(true, true).fadeIn(500);

//        //$(".zoom-out").stop(true, true).fadeOut(500);

//    });

//    $(".country").unbind("mouseout");
//    $(".country").mouseout(function() {
//        $(".map-info-panel." + $(this).attr("class").replace(/country /, ""))
//        .remove();
//        //$(".zoom-out").stop(true, true).fadeIn(500);
//    });
//}



/* Collapsing list */
function InitCollapseList() {
	$('#content a.open-all, #content p.open-all a').addClass("open-items");
    $('#content a.open-all, #content p.open-all a.NZTEcloseall').removeClass("open-items");

    // apply the following code only if all, or none expandable items are open
      $("#content .collapse-listing").each(function() {
            if ($(this).hasClass('NZTEsomeopen') == false) {
	            if ($(this).hasClass('collapse-open')) {
		            $(this).children(".item-holder").addClass("open");
	            } else {
		            $(this).children(".item-holder").addClass("closed");
	            }
            }
    });


   $(".collapse-listing .closed .item-content").hide();
   $(".collapse-listing .open .item-content").show();
     
    $(".collapse-listing .item-holder h3").hover(
	    function(){
		    $(this).addClass("hover");
	    },
	    function(){
		    $(this).removeClass("hover");
	    }
    );

    $(".collapse-listing .item-holder h3").each(function() {
        var title = $(this).html();
        $(this).html('<a title="click to expand and collapse" href="#">' + title + '</a>');
    });
	
    // pre expand items selected via the #
    if(location.hash)
    {
        $(location.hash).next(".item-content").slideDown("fast");
        $(location.hash).removeClass("hover");
        $(location.hash).addClass("open");
    }
    
    $("#content .collapse-listing h3").click(
	    function() {
	        if ($(this).parent().hasClass("open")) {
	            $(this).siblings(".item-content").slideUp("fast");
	            $(this).parent().removeClass("open");
	            $(this).parent().addClass("closed");
	        } else {
	            $(this).siblings(".item-content").slideDown("fast");
	            $(this).parent().removeClass("hover");
	            $(this).parent().removeClass("closed");
	            $(this).parent().addClass("open");
	        }
	        if ($("#content .collapse-listing .open").length == 0) { 
	    	    $('#content .pagination .open-all, #content .collapse-listing .open-all a').html('Open all').addClass('open-items');
	        } else if ($("#content .collapse-listing .closed").length == 0) {
			    $('#content .pagination .open-all,  #content .collapse-listing .open-all a').html('Close all').removeClass('open-items');
	        }
	        return false;
	    }
	);

	$('#content .pagination a.open-all').click(
        function() {
            if ($(this).hasClass("open-items") ) {
                $(this).html('Close all');
                $(this).removeClass('open-items');
                $(this).parent('.pagination').next('.collapse-wrapper').children(".collapse-listing").children(".closed").children("h3").trigger("click");
            } else {
                $(this).html('Open all');
                $(this).addClass('open-items');
                $(this).parent('.pagination').next('.collapse-wrapper').children(".collapse-listing").children(".open").children("h3").trigger("click");
            }
            return false;
        }
	);

        $("#content .collapse-listing p.open-all a").click(
		function() {
			if ($(this).hasClass("open-items")) {
				$(this).html('Close all');
				$(this).removeClass('open-items');
				$(this).parent("p.open-all").siblings(".closed").children("h3").trigger("click");
			} else {
				$(this).html('Open all');
				$(this).addClass('open-items');
				$(this).removeClass('NZTEcloseall');
				$(this).parent("p.open-all").siblings(".open").children("h3").trigger("click");
			}
			
			return false;
		}
	);
}

function InitPeopleList() {

    var listItemClosedHeight = 98; //90 for image + 8 for image margin

    //set closed height for each li
    $('.people-listing li').each(function() {
    	if ($(this).height() > listItemClosedHeight) {
    		$(this).addClass('closed');
    		SetUpPeopleListItem($(this));
    	} else if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "6") {
    		$(this).css("height", "98px");
       	}
    });

    if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "6") {
    	$(this).parent('h4').siblings('.full-copy').show();
    }
    
    //create anchors to bind
    $('.people-listing li.closed h4').each(function() {
        var title = $(this).html();
        $(this).html("<a title=\"click to get more information about: " + title + "\" href=\"#\">" + title + "</a>");
    });
    
    //set click to the h4
    $('.people-listing li h4 a').click(function() {
        if ($(this).parent('h4').parent('li').hasClass('closed')) {
            $(this).parent('h4').parent('li').removeClass('closed');
            $(this).parent('h4').parent('li').addClass('open');

            $(this).parent('h4').siblings('p.intro').hide();
            if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "6") {
                $(this).parent('h4').siblings('.full-copy').show();
            } else {
                $(this).parent('h4').siblings('.full-copy').slideDown(500);
            }
        } else if ($(this).parent('h4').parent('li').hasClass('open')) {
            $(this).parent('h4').parent('li').removeClass('open');
            $(this).parent('h4').parent('li').addClass('closed');

            $(this).parent('h4').siblings('.full-copy').hide();
            $(this).parent('h4').siblings('p.intro').show();
            
        }
        return false;
    });
    Format();
    $('.people-listing li .full-copy').hide();
}
//Set up the intro and bodycopy for the list item
function SetUpPeopleListItem(listItem) {
    //inrto
    var firstPara = listItem.children('p:not(".job-title"):first').html();
    var MAX_WORDS = 20;
    var firstParawords = firstPara.split(' ');
    if (firstParawords.length > MAX_WORDS) {
        firstPara = '';
        for (i = 0; i <= MAX_WORDS; i++) {
            firstPara += (' ' + firstParawords[i]);
        }
    }
    
    firstPara = "<p class=\"intro\">" + firstPara + "...</p>";
    //full copy
    var fullCopy = '';
    listItem.children('p:not(".job-title,.back-to-top")').each(function() { fullCopy += '<p>' + $(this).html() + '</p>'; });
    fullCopy = "<div class=\"full-copy\">" + fullCopy + "</div>";
    //out with the old in with the new
    listItem.find('p:not(".job-title,.back-to-top")').remove();
    listItem.append(firstPara);
    listItem.append(fullCopy);
}

/***** Home page version 2 *************************************************/
//twitter link

function BlogClicked() {
    dcsMultiTrack("WT.ti", "nzte%20blogs%20promo%20link", "DCS.dcsuri", "/nzte-blogs-promo-link", "WT.ac", "NZTE blogs");
}

function TwitterClicked() {
    dcsMultiTrack("WT.ti", "twitter%20promo%20link", "DCS.dcsuri", "/twitter-promo-link","WT.ac","Twitter");
}

// Sign Up for latest Export News link
function SignUpExportNewsClicked() {
    dcsMultiTrack("WT.ti", "Export%20News%20Promo%20Link", "DCS.dcsuri", "/Export-News-promo-link");
}

// following Preview Pane Links
function PreviewPaneClicked() {
    dcsMultiTrack("WT.ti", "Preview%20Pane%20-" + pageTitle, "DCS.dcsuri", "/Preview-pane-" + pageURL);
}

// following Homepage pods
function HomepagePodClicked() {
    dcsMultiTrack('WT.ti','Homepage%20Link%20-%20' + pageTitle, 'DCS.dcsuri', 'Homepage-Link-' + destinationPageURL);
}

// following Bottom pods
function BottomPodClicked() {
    dcsMultiTrack('WT.ti', 'Bottom%20Pod%20-%20' + pageTitle, 'DCS.dcsuri', 'Bottom-Pod-Link-' + destinationPageURL);
}

/***** Sharing Tools ***********************************************************/
// LinkedIn link
function LinkedInClicked() {
    dcsMultiTrack("WT.ti", "Send%20to%20LinkedIn", "DCS.dcsuri", "/share/LinkedIn", "WT.z_share", "LinkedIn");
}

// Digg This Link
function DiggThisClicked() {
    dcsMultiTrack("WT.ti", "Send%20to%20DiggThis", "DCS.dcsuri", "/share/DiggThis", "WT.z_share", "DiggThis");
}

// Facebook Link
function FaceBookClicked() {
    dcsMultiTrack("WT.ti", "Send%20to%20FaceBook", "DCS.dcsuri", "/share/FaceBook", "WT.z_share", "FaceBook");
}

// Twitter Link
function TweetThisClicked() {
    dcsMultiTrack("WT.ti", "Send%20to%20Twitter", "DCS.dcsuri", "/share/Twitter", "WT.z_share", "Twitter");
}

/***** Video Player *****************************************************************/

function InitVideoPlayer(){
	
	// Show video pod if javascript enabled
	$("#content .video-pod").show();

	// Add default video player content
	var VideoPlayerNum = 1;
	var VideoFlashMessageHtml = '<h2>Flash Required</h2><p>Your browser needs Adobe Flash Player (version 9 or higher) installed in order to view this video. You can download the plugin for free on the <a href="http://www.adobe.com/products/flashplayer/" rel="external">Adobe website</a></p>';
	var VideoMissingMessageHtml = '<h2>Unable to load video</h2><p>To view this video you need Flash Player installed and enable javascript in your browser.</p><p>You can download the Flash Player for free on the <a href="http://www.adobe.com/products/flashplayer/" rel="external">Adobe website</a></p>';

	$(".video-player").each(function() {

		if ($(this).find("a[rel=video-download][href!=]").length > 0) {
			var VideoPlayer = "video-" + VideoPlayerNum;
			var VideoSource = $(this).find("a[rel=video-download]").attr("href").split("?img=")[0];
			var ImageSource = $(this).find("a[rel=video-download]").attr("href").split("?img=")[1];

			$(this).find(".error-javascript").replaceWith(VideoFlashMessageHtml);
			$(this).find(".video").attr("id", VideoPlayer);

			ActivateVideoPlayer(VideoPlayer, VideoSource, ImageSource);

			// Increment Player Number
			VideoPlayerNum++;
			
		} else {
			$(this).find(".error-javascript").siblings("p").remove();
			$(this).find(".error-javascript").replaceWith(VideoMissingMessageHtml);
		}
	});
	
	$("#content .video-pod").each(function() {
		$(this).before('<div class="video-media">' +
			'<div class="content">' +
				'<div class="video-player">'+
					'<div class="video" id="video-' + VideoPlayerNum + '">' + VideoFlashMessageHtml + '</div>' +
				'</div>' +
				'<div class="extras">' +
					'<p class="collapse"><a href="#" title="Click here to close the video">Close Video Player</a></p>' +
				'</div>' +
			'</div>' +
		'</div>');
		
		// Reset external links
		SetExternalLinks();

		// Move transcript link/paragrpah into video player content
		var VideoTranscriptHtml = $(this).siblings("p.video-transcript").clone();
		$(this).siblings("p.video-transcript").remove();
		$(this).siblings(".video-media").children(".content").children(".extras").prepend(VideoTranscriptHtml);
		
		// Increment Player Number
		VideoPlayerNum++;
	});
	
	// Show / Hide video player content using Video Pod
	$(".video-pod,.video-media .collapse a").click(function() {
		if ($(this).hasClass("video-expanded")) {
			$(this).prev(".video-media").hide();
			$(this).removeClass("video-expanded");
			$(this).children(".content").children(".video-hide").remove();
			$(this).siblings(".video-media").children(".content").children(".video-player").html('<div class="video" id="video-' + VideoPlayerNum + '">' + VideoFlashMessageHtml + '</div>');
			$(this).children(".content").children(".video-show").show();
			VideoPlayerNum++;

			// Reset external links
			SetExternalLinks();
			return false;

		} else if ($(this).parent().hasClass("collapse")) {
			$(this).parent().parent().parent().parent(".video-media").hide();
			$(this).parent().parent().parent().parent(".video-media").siblings(".video-pod").removeClass("video-expanded");
			$(this).parent().parent().parent().parent(".video-media").siblings(".video-pod").children(".content").children(".video-hide").remove();
			$(this).parent().parent().parent().parent(".video-media").siblings(".video-pod").children(".content").children(".video-show").show();
			$(this).parent().parent().siblings(".video-player").html('<div class="video" id="video-' + VideoPlayerNum + '">' + VideoFlashMessageHtml + '</div>');
			VideoPlayerNum++;

			// Reset external links
			SetExternalLinks();
			return false;

		} else {

			$(this).prev(".video-media").show();
			$(this).children(".content").children(".video-show").hide();
			$(this).children(".content").children("img").after('<p class="video-hide"><a href="#" title="Click here to close the video">Close Video Player</a></p>');
			$(this).addClass("video-expanded");

			var VideoPlayer = $(this).prev(".video-media").children(".content").children(".video-player").children().attr("id");
			var VideoSource = $(this).children(".content").children(".video-show").children("a").attr("href").split("?img=")[0];
			var ImageSource = $(this).children(".content").children(".video-show").children("a").attr("href").split("?img=")[1];

			ActivateVideoPlayer(VideoPlayer, VideoSource, ImageSource);

			return false;
		}
	});

	$("p.video-transcript a").click(function() {
		window.open(this.href); return false;
	});
	
	$(".video-pod").hover(
		function(){$(this).attr("style", "cursor:pointer;"); }, 
		function(){$(this).removeAttr("style")}
	);
}

function ActivateVideoPlayer(VideoPlayer,VideoSource,ImageSource) {
	
	var VideoFlashVars = {};
	VideoFlashVars.videoToPlay = VideoSource;
	VideoFlashVars.imageToLoad = ImageSource;

	var VideoParams = {};
	VideoParams.allowFullScreen = "true";
	VideoParams.menu = "false";
	VideoParams.wmode = "transparent";
	VideoParams.scale = "showall";
	VideoParams.quality = "high";
	VideoParams.loop = "true";
	VideoParams.allowscriptaccess = "sameDomain";

	var VideoAttributes = {};
	VideoAttributes.id = VideoPlayer;
	VideoAttributes.name = VideoPlayer;

	swfobject.embedSWF("/_catalogs/masterpage/Flash/video_player.swf", VideoPlayer, "480", "400", "9.0.115", false, VideoFlashVars, VideoParams, VideoAttributes);

}

// PRINT PAGE ===============================================================
var PrintPage = {
	Init: function() {
		var thisUrl = document.location.href;
		var paramaterIndex = thisUrl.indexOf('?');
		var anchorIndex = thisUrl.indexOf('#');
		var paramaterMedia = "media=print&rpo=off";

		// Remove any page anchors from url
		if (anchorIndex > 0) {
			thisUrl = thisUrl.substring(0, anchorIndex);
		}

		// Check for parameters in existing url
		if (paramaterIndex > 0) {
			paramaterMedia = "&" + paramaterMedia;
		} else {
			paramaterMedia = "?" + paramaterMedia;
		}
		
		// Inject Print Button HTML into Menu
		$("#side-menu .page-tools ul").prepend('<li class="print-page"><a href="#" title="Print this page">Print this page</a></li>');
		
		// Open new window in print view
		$(".print-page a,.toolkit .print-page a, a.print-page").click(function() {
//			window.open(thisUrl + paramaterMedia, "PrintView", "menubar=1,resizable=0,width=900,height=700,scrollbars=1,location=1");
		    dcsMultiTrack('DCSext.br_btn_click', 'Print');
		    window.print();
			return false;
		});
	}
}

// NZ MAP REGIONAL DEVELOPEMENTS =============================================
var RegionalMap = {
    init: function() {
        $(".region").hide();
        $(".region-list li a").click(
        function() {
            Frontend.RegionalMap.showRegion($(this).parent().attr("class"));
        });
    },
    showRegion: function(regionName) {
        $(".region").hide();
        $(".region-preamble").hide();
        $("#" + regionName).show();
    }
}
// Initialise regional developements map

// MAP ======================================================================
var ExportMap = {
    state: String,
    init: function() {
        this.state = "#world-view";


        $(".country a span.tab-end").remove();
        $(".country a").append('<span class="tab-end"></span>');

        $("li.fta").each(function() {
            $(this).parent().parent().find("a:first").addClass("pad-right");
        });


        $("h4.zoom").each(function() {
            $(this).find("span:first").replaceWith($(this).find("span:first").html());
            $(this).find("span").remove();
        });

        $("h4.zoom").append('<span></span>');
        $("h4.zoom").wrapInner("<span></span>");

        $(".country").fadeIn(500).removeClass("hidden")
        $("h4.zoom").fadeIn(500).removeClass("hidden")


        $(".map-view").css({ left: 962 });
        $("#world-view .map-view").append('<div class="zoom-out"><a href="#world-view"></a></div>');

        $("#world-view").css({ left: 0 });

        $(".map-view .zoom").unbind("click");
        $(".map-view .zoom").click(function() {
            $('div.map-info-panel').remove();
            Frontend.ExportMap.swapView("#" + $(this).find("span:first").html().toLowerCase().replace(/<span[^>]*><\/span>/, "").replace(/ /g, "") + "-view");
            return false;
        });

        $(".map-view .zoom-out").unbind("click");
        $(".zoom-out").click(function() {
            $('div.map-info-panel').remove();
            Frontend.ExportMap.swapView("#world-view");
            return false;
        });
    },
    swapView: function(new_view) {

        if (new_view != "#world-view") {
            $(new_view).css("display", "block");
            if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "6") {
                $(this.state + " > div > dl > dd.country").addClass("hidden");
                $(this.state + " > div > h4.zoom").addClass("hidden");
                $(new_view).css("left", 0);
            } else {
                $(this.state + " > div > dl > dd.country").fadeOut(200, function() { $(this).addClass("hidden"); });
                $(this.state + " > div > h4.zoom").fadeOut(200, function() { $(this).addClass("hidden"); });
                $(new_view).animate({ left: 0 }, 500);
            }

            $(new_view + " > dd.country").removeClass("hidden");
            //track click
            dcsMultiTrack("DCSext.map_zoom_loc", new_view);
        } else {

            if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "6") {
                $(this.state).css("left", 968);
                $(this.state).css("display", "none");
                $(new_view).css("display", "block");
                $(this.state + " > div > dl > dd.country").addClass("hidden");
                $(this.state + " > h4.zoom").addClass("hidden");
                $(new_view + " > div > dl > dd.country").removeClass("hidden");
                $(new_view + " > div > h4.zoom").removeClass("hidden");
            } else {
                $(this.state).animate({ left: 968 }, 500, function() { $(this).css("display", "none"); });
                $(this.state + " > div > dl > dd.country").addClass("hidden");
                $(this.state + " > h4.zoom").addClass("hidden");
                $(new_view + " > div > dl > dd.country").removeClass("hidden").fadeIn(800);
                $(new_view + " > div > h4.zoom").removeClass("hidden").fadeIn(800);   
            }
        }
        this.state = new_view;
    }
}

// IMAGE GALLERY =============================================
var ImageGallery = {
	Init: function() {
		$("#content .pod-gallery").each(function() {
			var expandText = 'View image gallery';
			var collapseText = 'Close image gallery';
			var expandLinkHtml = '<a class="arrow-down" href="#">' + expandText + '</a>';
			
			$(this).show().addClass("gallery-expand");
			$(this).find(".pod-content").append(expandLinkHtml).toggle(
				function() {
					$(this).find("li").removeClass("hide");
					$(this).find("a.arrow-down").text(collapseText);
				}, function() {
					Frontend.ImageGallery.HideImages(".pod-gallery");
					$(this).find("a.arrow-down").text(expandText);
				}
			);
			Frontend.ImageGallery.HideImages("#content .pod-gallery");
		});
	},
	HideImages: function(target) {
		var num = 0;
		$(target + " li").each(function() {
			if (num > 2) {
				$(this).addClass("hide");
			}
			num++;
		});
	}
}



// Initialise methods onto Frontend Object ================================================================================
var Frontend = { 
    ExportMap: ExportMap, 
    RegionalMap: RegionalMap,
    ImageGallery: ImageGallery,
    PrintPage: PrintPage
};

// <OLIE MAP CODE START> //
function mapJumpListInit() {
    $('.jump-target').hide();
    $('.jump-target.instructions').show();
    $('.pod-jump-list-holder').addClass('pod-jump-list-holder-java');
    $('.pod-jump-list-holder').removeClass('pod-jump-list-holder');
    $('.pod-jump-list-holder-footer').addClass('pod-jump-list-holder-footer-java');
    $('.pod-jump-list-holder-footer').removeClass('pod-jump-list-holder-footer');
    $('.pod-map-jump-list ul li a').click(function() {
    	$('.jump-target:visible').hide();
    	//ie6 fails to render...
    	if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "6") {
    		$($(this).attr('href')).show();
    	} else {
    		$($(this).attr('href')).show();
    	}
    	//add select style
    	$('.pod-map-jump-list ul li a').removeClass('selected');
    	$(this).addClass('selected');
    	return false;
    });

    // pre open items selected via the #
    if (location.hash) {
        $('.pod-map-jump-list ul li a').each(function() {
            var anchor = $(this);
            var target = location.hash;

            if (anchor.attr('href') == target) {
                anchor.trigger('click');
            }
        });
    }
}
// <OLIE MAP CODE END> //


// ARE YOU READY TO EXPORT ======================================================

function calculateScoreAndRedirect() {
    if (Page_ClientValidate()) {

        var intScore = 0;
        $("input:radio:checked").each(function() {
            intScore += parseInt($(this).attr("value"));
        });

        if (intScore > 90) {
            window.location = "/get-ready-to-export/Starting-to-Export/are-you-ready-to-export-results/Pages/Result1.aspx"; 
        }
        else if (intScore >= 70 && intScore <= 90) {
            window.location = "/get-ready-to-export/Starting-to-Export/are-you-ready-to-export-results/Pages/Result2.aspx";
        }
        else if (intScore >= 45 && intScore <= 69) {
            window.location = "/get-ready-to-export/Starting-to-Export/are-you-ready-to-export-results/Pages/Result3.aspx";
        }
        else {
            window.location = "/get-ready-to-export/Starting-to-Export/are-you-ready-to-export-results/Pages/Result4.aspx";
        }
    }
}

// GRANT SELECTION GUIDE ======================================================

function grantSelectionResult() {
	$(".grant-result").hide();
	$("#DefaultGrantResult").show();
	
	$(".grants-selection input").click(function(){
		$(".grant-result").hide();
		if($(this).val() == "CB"){
			$("#CBGrantResult").fadeIn("fast");
			window.location="#CBGrantResult";
		}
		if($(this).val() == "MD"){
			$("#MDGrantResult").fadeIn("fast");
			window.location="#MDGrantResult";
		}
	});
}


function popUp(url,width,height) {
    if (width == -1) var width = 550;
    if (height == -1) var height = 500;
    day = new Date();
    id = day.getTime();
    window.open(url, id, 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=' + width + ',height=' + height + ',left = 385,top = 212');
}

// ADD THIS SIDEBAR  ======================================================

var AddThis = {

    // Page tools functions
    PageTools: function() {
        $('#page-tools a.print').click(function() {
            window.print();
            return false;
        });

//        $('#page-tools a.bookmark').click(function() {
//            var title = document.title;
//            var url = document.URL;

//            if (document.all) {
//                window.external.AddFavorite(url, title);
//            }
//            else if (window.sidebar) {
//                alert('Press "CTRL+D" or "CMD + D" for Mac, to add this page to your bookmarks.');
//            };
//            return false;


//        });

        $('#share-container ul li a').click(function() {
            dcsMultiTrack('DCS.dcsuri', this.ownerDocument.location.href, 'WT.ti', 'Share%20This%20Page:%20' + this.text);
            return true;
        });
    },

    // Slide down list of recent pages
    DisplayRecentPages: function() {
        $('#recently-viewed').toggle(
			function() {
			    $(this).addClass('selected'); ;
			    $('#recent-pages').slideDown('medium');
			},
			function() {
			    $(this).removeClass('selected');
			    $('#recent-pages').slideUp('medium');
			    return false;
			}
		);
    },

    // Show thankyou message if user clicks 'Yes' button
    UsefulYes: function() {
        $('#useful-yes').click(function() {
            $('#useful-container').fadeOut('medium', function() {
                $('#thanks-container').fadeIn('medium');
            });
            return false;
        });
    },

    // Show comments area if user clicks 'No' button
    UsefulNo: function() {
        $('#useful-no').click(function() {
            $('#useful-container').fadeOut('fast', function() {
                $('#comment-container').slideDown('medium');
            });
            return false;
        });
    },

    // Submit button action
    CommentSubmit: function() {
        $('#comment-submit').click(function() {
            $('#comment-container').fadeOut('medium', function() {
                $('#thanks-container').fadeIn('medium');
            });
            return false;
        });
    },

    // Add This dropdown
    AddThisToolbox: function() {
        $('.custom_button').toggle(
			function() {
			    if ($.browser.msie) {
			        $('.hover_menu').show();
			    } else {
			        $('.hover_menu').slideDown('medium');
			    };
			    $('#share-container').addClass('active round-cnrs');
			    $(this).data('in', true);
			    $('.hover_menu').data('hidden', false);
			    dcsMultiTrack('DCSext.br_btn_click', 'Share%20this%20page');
			},

			function hideMenu() {
			    if ($.browser.msie) {
			        $('.hover_menu').hide();
			    } else {
			        $('.hover_menu').slideUp('medium');
			    };
			    $('#share-container').removeClass('active round-top');
			    $('.hover_menu').data('hidden', true);
			}
		);
    },

    // Add hover effect to buttons in IE6
    ButtonHoverIE6: function() {
        $('#ie6 #useful-yes, #ie6 #useful-no').hover(
			function() {
			    $(this).addClass('hover');
			},
			function() {
			    $(this).removeClass('hover');
			}
		);
    },

    GetRecentlyViewed: function(target) {

        var RECENTLYVIEWED_COOKIE_NAME = "NZTE_RecentlyViewed";
        var pageUrl = location.pathname;
        var pageTitle = jQuery.trim(document.title);
        var recentViewedDelimitedList = '';
        var recentlyViewedItemsHtml = '';
        var pageItems = '';
        var pageAlreadyAdd = false;

        if ($.cookie(RECENTLYVIEWED_COOKIE_NAME) != null) {
            recentViewedDelimitedList = $.cookie(RECENTLYVIEWED_COOKIE_NAME);
            pageItems = recentViewedDelimitedList.split(";#");

            //create 10 links  
            for (i = 1; i <= 10; i++) {
                if (pageItems.length > i) {
                    var pageItem = pageItems[i].split("||");
                    recentlyViewedItemsHtml += '<li><a class="link" href="' + pageItem[0] + '">' + pageItem[1] + '</a></li>';
                    //check if already exists
                    if (pageItem[0].toLowerCase() == pageUrl.toLowerCase()) {
                        pageAlreadyAdd = true;
                    }
                }
            }

        }

        if (pageAlreadyAdd == false && pageUrl.indexOf("404.aspx") == -1) {
            //if list has more then 10 links/11 segments then trim off last. 
            if (pageItems.length >= 11) {
                var index = recentViewedDelimitedList.lastIndexOf(";#");
                recentViewedDelimitedList = recentViewedDelimitedList.substring(0, index);
                index = recentlyViewedItemsHtml.lastIndexOf("<li>");
                recentlyViewedItemsHtml = recentlyViewedItemsHtml.substring(0, index);
            }

            //prepend the link to the cookie
            recentViewedDelimitedList = ";#" + pageUrl + "||" + pageTitle + recentViewedDelimitedList;

            //prepend the link to the html output
            var newLinkHtml = '<li><a class="link" href="' + pageUrl + '">' + pageTitle + '</a></li>';
            recentlyViewedItemsHtml = newLinkHtml + recentlyViewedItemsHtml;
        }

        $.cookie(RECENTLYVIEWED_COOKIE_NAME, recentViewedDelimitedList, { path: '/', expires: 9999 });
        $("#recent-pages li.no-links").remove();
        $("#recent-pages").append(recentlyViewedItemsHtml);


    },

    Init: function() {
        this.PageTools();
        this.DisplayRecentPages();
        this.UsefulYes();
        this.UsefulNo();
        this.CommentSubmit();
        this.AddThisToolbox();
        this.ButtonHoverIE6();

        var cookiesDisabledMsg = "Recently Viewed disabled.";

        //check if user has cookies enabled
        if (IsCookiesEnabled()) {

            //Recent Pages
            AddThis.GetRecentlyViewed($("#recent-pages li a"));

        }
        else {
            $("#recent-pages li").attr("title", cookiesDisabledMsg + " To enable, see the 'Help' page.");
        }

        // Bind Toolkit Email Page
        $(".page-tools li.ico a.email").click(function() {
            dcsMultiTrack("DCSext.br_btn_click", "Email Page", "DCSext.pg_t", jQuery.trim(document.title), "DCSext.pg_u", location.pathname);
            var hostname = location.protocol + "//" + location.host;
            window.location = hostname + "/email-this-page/pages/email-this-page.aspx?pageurl=" + location.pathname;
            return false;
        });
    }
}

/* Add Favourites Function */

eval(function(p, a, c, k, e, r) { e = function(c) { return (c < a ? '' : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36)) }; if (!''.replace(/^/, String)) { while (c--) r[e(c)] = k[c] || e(c); k = [function(e) { return r[e] } ]; e = function() { return '\\w+' }; c = 1 }; while (c--) if (k[c]) p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]); return p } ('(7($){$.8.9=7(d){g e=$.v({},$.8.9.k,d);g f=e.l;2.w(7(){5(!$(2).3(\'4\')||$(2).3(\'4\')=="#"){$(2).3(\'4\',j.x.4)}5(!$(2).3(\'6\')){$(2).3(\'6\',y.6)}5($.h.z){$(2).3(\'m\',$(2).3(\'4\')).3(\'4\',\'\').3(\'4\',\'A:B(0)\').3(\'C\',\'$.8.9.n(2,"\'+$(2).3(\'6\')+\'","\'+$(2).3(\'m\')+\'")\')}i{$(2).o(p)}});7 p(a){g b=$(2).3(\'4\');g c=$(2).3(\'6\');b=b.E("q:///","F://q/");5($.h.G){j.H.I(b,c)}i 5($.h.J){j.r.K(c,b,\'\')}i 5(L.M.N().O(\'P\')>-1){s(f)}i 5($.h.Q){s(f)}a.R()};t 2};$.8.9.k={l:\'S "T + D" U "V + D" W X, u Y 2 Z u 10 11.\'};$.8.9.n=7(e,a,b){e.12="r";e.6=a;e.4="";e.4=b;e.o();t 13}})(14);', 62, 67, '||this|attr|href|if|title|function|fn|jFav|||||||var|browser|else|window|defaults|msg|link|OperaBookmark|click|addToFavorites|file|sidebar|alert|return|to|extend|each|location|document|opera|javascript|void|onClick||replace|http|msie|external|AddFavorite|mozilla|addPanel|navigator|userAgent|toLowerCase|indexOf|chrome|safari|preventDefault|Press|Ctrl|or|CMD|for|MAC|add|page|your|bookmarks|rel|false|jQuery'.split('|'), 0, {}))

