 
/*--------------------------------
Package browser
--------------------------------*/

var pageSize = 10;
var currentPackage = 0;
var fromIndex = 0;
var toIndex = fromIndex + pageSize - 1;
var prevPages = $('div.prevpages a');
var nextPages = $('div.nextpages a');

$('nav#packageBrowser li').each(function (index) {
    if ($(this).hasClass('current')) {
        currentPackage = index;
    }
});

pageNo = (currentPackage - (currentPackage % pageSize)) / 10

fromIndex = pageNo * pageSize;
toIndex = fromIndex + pageSize - 1;

//$(document).pngFix();
drawPackageBrowser();
//bindNextPage();
//bindPrevPage();
//DD_belatedPNG.fix('#container');

$('nav#packageBrowser ol').delay(100).fadeIn(200);


$('nav#packageBrowser li').bind('mouseenter', function () {
    var offset = $(this).offset();
    $('#thumbnailViewer').html($(this).children('img').clone()).append("<div></div>").css('top', offset.top - 62).css('left', offset.left + 170);
});

$('nav#packageBrowser li').bind('mouseleave', function () {
    $('#thumbnailViewer').html(null).css('top', -1000).css('left', -1000);
});

function bindNextPage() {
    nextPages.bind('click', function () {
        paginatePackageBrowser(1);
        return false;
    });
    nextPages.css('cursor', 'pointer');
}

function bindPrevPage() {
    prevPages.bind('click', function () {
        paginatePackageBrowser(-1);
        return false;
    });
    prevPages.css('cursor', 'pointer');
}

function paginatePackageBrowser(direction) {
    var modifier = "";
    if (direction == "1") {
        modifier = "-";
    }
    newPageSize = pageSize * direction;
    var scrollShift = direction * 10;

    fromIndex = fromIndex + newPageSize;
    toIndex = toIndex + newPageSize;

    prevPages.unbind('click');
    nextPages.unbind('click');

    $('div.nextpages').animate({
        opacity: 0
    }, 200, function () {
        $('div.nextpages').animate({
            opacity: 1
        }, 200);
    });

    $('nav#packageBrowser ol').animate({
        opacity: 0,
        top: '+=' + modifier + '10'
    }, 200, function () {
        drawPackageBrowser();
        $('nav#packageBrowser ol').css('top', scrollShift).delay(50).animate({
            opacity: 1,
            top: '+=' + modifier + '10'
        }, 200);
    });
}

function drawPackageBrowser() {
    var toIndexLabel = toIndex + pageSize + 1;
    var olLength = $('nav#packageBrowser ol li').length;
    $('nav#packageBrowser li').each(function (index) {
        $(this).css('position', 'relative').css('left', 0).css('top', 0).css('opacity', 1).css('visibility', 'visible');
        if (index < fromIndex || index > toIndex) {
            $(this).css('position', 'absolute').css('left', -9999).css('top', -9999).css('opacity', 0).css('visibility', 'hidden');
        }
    });
    if (fromIndex - pageSize < 0) {
        prevPages.unbind('click').css('cursor', 'default').css('opacity', 0).css('visibility', 'hidden');
    } else {
        prevPages.unbind('click');
        bindPrevPage();
        prevPages.css('opacity', 1).css('visibility', 'visible');
    }
    
    if (((fromIndex + pageSize) + 1) > olLength) {
        nextPages.unbind('click').css('cursor', 'default').css('opacity', 0).css('visibility', 'hidden');
    } else {
        nextPages.unbind('click');
        bindNextPage();
        nextPages.css('opacity', 1).css('visibility', 'visible');
    }

    if (toIndex + pageSize + 1 > olLength) {
        toIndexLabel = olLength;
    }
    prevPages.html("Resources " + (fromIndex - pageSize + 1) + "-" + (toIndex - pageSize + 1) + " of " + olLength);
    nextPages.html("Resources " + (fromIndex + pageSize + 1) + "-" + toIndexLabel + " of " + olLength);

    $('#packageBrowser .loading').fadeOut('fast');
}


/*--------------------------------
 Current study level indicator
--------------------------------*/

// Get current level and apply class

var currentLevel = $('#levelSelect a span').html();

$('#levelSelect a span').addClass("level" + currentLevel);


// Level selector on/off

var levelSelect = $('#levelSelect ol');
var selectorButton = $('#levelSelect a#level');

selectorButton.click(function () {

    if (levelSelect.is(':visible')) {
        
        levelSelect.fadeOut('fast');

    } else {
        
        levelSelect.fadeIn('fast');

    }
	
});

// Hide level selector if a click outside selector is detected

var mouseInside = false;

levelSelect.hover(function () {
	mouseInside = true;
}, function () {
	mouseInside = false;
});

$('html').mouseup(function () {
	if(!mouseInside) { levelSelect.fadeOut('fast'); };
});

/*--------------------------------
 Infobar
--------------------------------*/

// initial load

var infobar = $('div#infobar');
var infotext = $('div#infobar p');
var infobutton = $('div#infobar a');

if (infobar.length) {

    infobar.slideDown('normal', 'swing', function () {

        infobutton.attr('class', 'hide');
        infotext.css('visibility', 'visible').hide().fadeIn('fast');

        // var totalHeight = ((infotext.height() + infobar.height()) - 48 + "px");
        var totalHeight = infotext.outerHeight(true);



        infobutton.click(function () {

            if (infotext.is(':visible')) { // if bar is open
                hideInfobar(totalHeight);
            } else { // if bar is closed
                showInfobar(totalHeight);
            }

        });
    });
};

function hideInfobar(totalHeight) {
    infotext.fadeOut('fast');
    infobar.css('height', totalHeight);
    infobar.delay(300).animate({ height: "22px", top: "-=50" }, 400);

    setTimeout(function () { // delay switching arrow direction and text until infobar is out of sight
        infobutton.attr('class', 'show');
        infobutton.html((infobutton).html().replace("Hide", "Show"));
    }, 600);
    
    infobar.animate({ top: "+=50" }, 700);
}

function showInfobar(totalHeight) {
    infobar.animate({ height: totalHeight }, 500);
    infotext.delay(300).fadeIn('fast').delay(1000);
    infobutton.delay(500).attr('class', 'hide');
    infobutton.html((infobutton).html().replace("Show", "Hide"));
}

/*--------------------------------
 Tabbed content
--------------------------------*/

// When page loads...

if ($('ul.tabNav li:first.active').length == 0) {
    // No tabs have had their classes set, so show the first tab
    $('.tabContent').hide(); //Hide all content
    $('ul.tabNav li:first').addClass("active").show(); //Activate first tab
    $('.tabContent:first').show(); //Show first tab content
};


// On Click Event
$('ul.tabNav li').click(function () {

    if ($(this).hasClass('active') == false) {

        $('ul.tabNav li').removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $('.tabContent').hide(); //Hide all tab content

        var activeTab = $(this).find('a').attr('href'); //Find the href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active ID content
        return false;
    } else {
        return false;
    }
});

// if tab button text wraps onto two lines, centralise text vertically

$('ul.tabNav li a').each(function () {

    var tabHeight = $(this).height();
    var singleLineHeight = "31"

    if (tabHeight > singleLineHeight) { $(this).addClass('doubleLine'); }

});


/*--------------------------------
 Home page - Equalise pod heights
--------------------------------*/


	$.fn.equalHeights = function(minHeight, maxHeight) {
		tallest = (minHeight) ? minHeight : 0;
		this.each(function() {
			if($(this).height() > tallest) {
				tallest = $(this).height();
			}
		});
		if((maxHeight) && tallest > maxHeight) tallest = maxHeight;
		return this.each(function() {
			$(this).height(tallest).css("overflow","auto");
		});
	}


$('section#getStarted div').equalHeights();


/*--------------------------------
 Image gallery asset
--------------------------------*/

// Overlay using modalPanel plugin

$('a.launchGallery').modalPanel();



// Image gallery

function runGallery(gallery) {

    //Speed of the slideshow
    var speed = 5000;

    //You have to specify width and height in .slider CSS properties
    //After that, the following script will set the width and height accordingly
    gallery.find('.mask-gallery, .gallery li').width(gallery.find('.slider').width());
    gallery.find('.gallery').width(gallery.find('.slider').width() * gallery.find('.gallery li').length);
    gallery.find('.mask-gallery, .gallery li, .mask-excerpt, .excerpt li').height(gallery.find('.slider').height());

    //Assign a timer, so it will run periodically
    var run = setInterval('imagescroller(0)', speed);

    gallery.find('.gallery li:first, .excerpt li:first').addClass('selected');

    $('.btn-pause').unbind('click');
    $('.btn-play').unbind('click');
    $('.btn-next').unbind('click');
    $('.btn-prev').unbind('click');
    //Pause the slidershow with clearInterval
    $('.btn-pause').click(function () {
        clearInterval(run);
        return false;
    });

    //Continue the slideshow with setInterval
    gallery.find('.btn-play').click(function () {
        run = setInterval('imagescroller(0)', speed);
        return false;
    });

    //Next Slide by calling the function
    gallery.find('.btn-next').click(function () {
        imagescroller(0, gallery);
        return false;
    });

    //Previous slide by passing prev=1
    gallery.find('.btn-prev').click(function () {
        imagescroller(1, gallery);
        return false;
    });

    clearInterval(run); // Stop animation by to begin with

};

// Run the gallery

$('a[class^="launchGallery"]').click(function () {

    var clickedLink = ($(this).attr('class'));

    var thisGallery = $(this).parent('p').next('.galleryContainer:first');
    thisGallery.css('display', 'block');

    runGallery(thisGallery);

});

function imagescroller(prev, gallery) {

	//Get the current selected item (with selected class), if none was found, get the first item
    var current_image = gallery.find('.gallery li.selected').length ? gallery.find('.gallery li.selected') : gallery.find('.gallery li:first');
    var current_excerpt = gallery.find('.excerpt li.selected').length ? gallery.find('.excerpt li.selected') : gallery.find('.excerpt li:first');

	//if prev is set to 1 (previous item)
	if (prev) {
		
		//Get previous sibling
	    var next_image = (current_image.prev().length) ? current_image.prev() : gallery.find('.gallery li:last');
	    var next_excerpt = (current_excerpt.prev().length) ? current_excerpt.prev() : gallery.find('.excerpt li:last');
	
	//if prev is set to 0 (next item)
	} else {
		
		//Get next sibling
	    var next_image = (current_image.next().length) ? current_image.next() : gallery.find('.gallery li:first');
	    var next_excerpt = (current_excerpt.next().length) ? current_excerpt.next() : gallery.find('.excerpt li:first');
	}

	//clear the selected class
	gallery.find('.excerpt li, .gallery li').removeClass('selected');
	
	//reassign the selected class to current items
	next_image.addClass('selected');
	next_excerpt.addClass('selected');

	//Scroll the items
	gallery.find('.mask-gallery').scrollTo(next_image, 800);
	gallery.find('.mask-excerpt').scrollTo(next_excerpt, 800);					
	
}

// Hide gallery if user clicks outside


var mouseInsideGal = false;
var galleryContainer = $('.galleryContainer');

galleryContainer.hover(function () {
	mouseInsideGal = true;
}, function () {
	mouseInsideGal = false;
});

$('html').mouseup(function () {
	if(!mouseInsideGal) { galleryContainer.fadeOut('fast'); };
});

// Hide when escape key hit

$(document).keyup(function(e) {
  if (e.keyCode == 27) {  galleryContainer.fadeOut('fast'); }   // esc
});




/*--------------------------------
 Drag & Drop
--------------------------------*/


$('.draggable div').draggable({
    appendTo: $(this).parent(), disabled: false,
    containment: $(this).parent(),
    revert: function (dropped) {
        var dropped = dropped && dropped[0].id == "droppable";
        return !dropped;
    }
});


$('.droppable div').droppable({
   
    accept: '.draggable div',
    hoverClass: 'hovered',
    drop: handleDropEvent
});



// handle drops

function handleDropEvent(event, ui) {


    var draggable = ui.draggable;


    ui.draggable.draggable( 'disable' );
    $(this).droppable( 'disable' );
    ui.draggable.position( { of: $(this), my: 'center middle', at: 'center middle' } );
    ui.draggable.draggable('option', 'revert', false);

    var droppedItem = (draggable.addClass('dropped'));

    

    $("div.dropped span").click(function () {

        $(this).parent().attr('class','ui-draggable');
        $(this).parent().removeAttr('aria-disabled');
        $(this).parent().removeAttr('style');
        $(this).parent().css('position','relative');
        $(this).parent().css('z-index','99999');

        $(this).parent().draggable({
            disabled: false, 
            containment: '.scene',
        
           revert:  function(dropped) {
               var dropped = dropped && dropped[0].id == "droppable";
               return !dropped;
               }
        
        });

        $('.droppable div').droppable({
            disabled: false
        });

        $(this).parent().draggable({
            appendTo: '.draggable', disabled: false,
            containment: $(this).parent().parent().parent(),
            revert: function (dropped) {
                var dropped = dropped && dropped[0].id == "droppable";
                return !dropped;
            }
        });


       
    });

};

/*--------------------------------
 True/false reveal asset
--------------------------------*/

// align every other section right

$('.statementAnswerPair:odd').addClass("odd");
$('section.statement').addClass("unflipped");

// reset background image position if out of place

$("body").delegate("section.unflipped a", "click", function () {

    var $this = $(this);

    $this.parents('section').removeClass('unflipped').addClass('flipped');

    var thisStatement = ($this.parents('.statement'));
    var answer = (thisStatement.children('p.answer'));
    
    // set colours for true or false

    if (answer.text().match("TRUE")) {

        var color = '#59bb63';

    } else { var color = '#d12627' };

    var cardAnswer = answer.clone(); // copy the answer 

    var answer = $("<p/>").prepend(cardAnswer); // move it to the answer panel

    thisStatement.flip({ // do flip

        direction: 'tb',
        content: answer,
        color: color,

        onBefore: function () { // during animation

            thisStatement.css('backgroundPosition', '-9999px -9999px');
        },

        onEnd: function () { // after animation

            thisStatement.children('.answer').fadeIn('normal');

            thisStatement.click(function () {

                if (thisStatement.hasClass('flipped')) {

                    thisStatement.revertFlip();

                    thisStatement.removeClass('flipped').addClass('unflipped');


                }


            });

        }

    });

});


/* Scene switcher */

var noOfScenes = $('article#stage div.scene').length;
var currentScene = 1;

if (noOfScenes > 1) {
    $('article#stage nav#paginationControls').css('display', 'block');
}

$('article#stage div.scene').each(function (index) {
    $(this).addClass('scene' + (index + 1));
    if (index != currentScene - 1) {
        $(this).css('display', 'none');
    }

});

writeSceneInfo();
bindNextScene();

function bindPrevScene() {
    $('article#stage nav#paginationControls div.prev a').unbind('click');
    if (currentScene > 1) {
        $('article#stage nav#paginationControls div.prev a').css('cursor', 'pointer').css('opacity', 1).bind('click', function () {
            $(this).unbind('click');
            changeScene(-1);
            return false; // Added to stop # being appended to URL
        });
    }
}

function bindNextScene() {
    $('article#stage nav#paginationControls div.next a').unbind('click');
    if (currentScene < noOfScenes) {
        $('article#stage nav#paginationControls div.next a').css('cursor', 'pointer').css('opacity', 1).bind('click', function () {
            $(this).unbind('click');
            changeScene(1);
            return false; // Added to stop # being appended to URL
        });
    }
}

function changeScene(modifier) {
    if (currentScene + modifier <= noOfScenes && currentScene + modifier > 0) {
        $('div.scene' + currentScene).animate({
            opacity: 0.25,
            left: '-=' + (728 * modifier)
        }, 1000, function () {
            // Animation complete.
        });
        currentScene = currentScene + modifier;
        $('div.scene' + currentScene).css('left', 728 * modifier).css('top', 0).css('display', 'block').css('opacity', 1).animate({
            left: '-=' + (728 * modifier)
        }, 1000, function () {
            /*if (window['scene' + currentScene]()) {
            window['scene' + currentScene](); 
            }*/
            bindPrevScene();
            bindNextScene();
        });
        writeSceneInfo();
        //hideInfobar();
    }

    if (currentScene == noOfScenes) {
        $('article#stage nav#paginationControls div.next a').unbind('click').css('cursor', 'default').css('opacity', 0.25);
    }
    if (currentScene == 1) {
        $('article#stage nav#paginationControls div.prev a').unbind('click').css('cursor', 'default').css('opacity', 0.25);
    }
}

function writeSceneInfo() {
    $('article#stage nav#paginationControls div.sceneInfo').html(currentScene + " of " + noOfScenes);
}


/* Multiple video players */


VideoJS.DOMReady(function () {
    var noOfVideos = $('article#stage div.video').length;
    var currentVideo = 1;
    var vPlayer = new Array();

    $('article#stage div.video').addClass('position');

    $('article#stage div.video').each(function (index) {
        if (!$('html').hasClass('ie6')) {
            vPlayer[index] = VideoJS.setup("video_" + (index + 1));
        }

        if (index == currentVideo - 1) {
            $(this).css('display', 'block');
        } else {
            $(this).css('display', 'none');
        }

        $(this).parent().find('span.label').css('cursor', 'pointer').bind('click', function () {
            $('ul.videoList li').removeClass('current');
            $(this).parent().addClass('current');
            $('article#stage div.video').removeClass('current');
            if (!$('html').hasClass('ie6') && !$('html').hasClass('ie7') && !$('html').hasClass('ie8')) {
                for (i = 0; i < noOfVideos; i++) {
                    vPlayer[i].pause();
                }
                //vPlayer[index].play();
            }

            currentVideo = (index + 1);
            $('article#stage div.video').each(function (index) {
                if (index != (currentVideo - 1)) {
                    $(this).parent().find('div.video').css('display', 'none');
                } else {
                    $(this).parent().find('div.video').css('display', 'block');
                }
            });

            $(this).parent().find('div.video').addClass('current');
            $('a.transcript').css('display', 'none');
            $(this).parent().find('a.transcript').css('display', 'block');
            $('div.transcript').addClass('closed');

            return false;
        });
    });

    $('div.transcript').addClass('closed');

    $('a.transcript').bind('click', function () {
        $(this).parent().parent().find('div.transcript').attr('style', '').toggleClass('closed');
        if ($(this).parent().parent().find('div.transcript').hasClass('closed')) {
            $(this).html('Show transcript');
            $('ul.videoList li').css('display', 'block');

        } else {
            $(this).html('Hide transcript');


            $('ul.videoList li').css('display', 'none');
            $(this).parent().css('display', 'block');
        }
        return false;
    });

});

/* Select module page styling */

$('section.module:odd').addClass('odd');

/*--------------------------------
Level select tip control
--------------------------------*/

/* Cookie setting function */

function setCookie(name, value, expires) {
    document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
};

function getCookie(name) {

    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
            end = dc.length;
        }
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/* Cookie checking function: show the tooltip if no cookie found */

function showTip() {
    var myCookie = getCookie("levelSelectTip");

    if (myCookie == null) {
        // do cookie doesn't exist stuff;
        setTimeout(function () {
            $('#levelSelectTip').fadeIn('normal');
        }, 750);
    }
    else {
        // do cookie exists stuff
    }
}

/* Set up the correct date and time for expiry purposes */
var exp = new Date();     //set new date object	
exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30));     //set it to expire (last number in the list) days ahead 


/* CHROME ONLY: HTML5 storage solution for level select tip */

/* Local storage checking function */

function showChromeTip() {

    if ((localStorage.levelTip) == null) { // if no local storage value found for the key "levelTip"

        setTimeout(function () {

            $('#levelSelectTip').fadeIn('normal'); // show the tip

        }, 750);

        $('#levelSelectTip a.close').click(function () {
            $(this).parents('#levelSelectTip').fadeOut('fast'); // hide the tip
            localStorage.setItem("levelTip", "seen"); // set a local storage value
        });
    }

    else { // do nothing 
    }
} // end showChromeTip function


var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; // check if the browser is Chrome

if (is_chrome == true) {

    showChromeTip();

} else {

    /* Study level tip - for all browsers except Chrome */

    $('#levelSelectTip a.close').click(function () { // when the tip has been seen, and the "close" link clicked

        $(this).parents('#levelSelectTip').fadeOut('fast'); // fade out the tip
        setCookie('levelSelectTip', 'seenTip', exp); // set the cookie

    });

    showTip();
};



/*------------------------------------
NAT progress bar
------------------------------------*/

var progressContainer = $('div.progress');
var progressBar = $('div.progress > div');
var progressIndicator = $('div.progress > div > span');

// create an array for the progress bar stages

var myArray = [];

var stages = $('.nat ol.stages');

stages.children('li').each(function () {
    var stageName = $(this).text();
    myArray.push({
        'name': stageName
    });
});

var noOfStages = (stages.children('li').size()) - 1; // minus one because "start" stage doesn't count
var progressBarHeight = $('ol.stages').outerHeight();

var stageHeight = (progressBarHeight / noOfStages) - 32; // minus 32 because this is the height of each stage text label

// vertically distribute stages evenly

stages.children().css({ 'margin-top': stageHeight });

// set progress indicator height

var seenStages = stages.children('.seen').size(); // the number of stages with class="seen"

indicatorHeight = ((seenStages * stageHeight) + (seenStages * 32));

progressIndicator.css('height', indicatorHeight);

var progressBarOuterHeight = $('ol.stages').height();
var progressBarOuterHeight = progressBarOuterHeight - 25;

$('.progress .bar').css('height', progressBarOuterHeight);

// NAT table zebra striping

/* For zebra striping */
$("table tr:nth-child(odd)").addClass("odd-row");
/* For cell text alignment */
$("table td:first-child, table th:first-child").addClass("first");
/* For removing the last border */
$("table td:last-child, table th:last-child").addClass("last");

/* Slider */

// Handle slider behaviour

$('.sliderControl').each(function (idx, elm) {

    $this = $(this);
    $this.attr("id", ('s' + (idx + 1) + 'Slider'));
    $this.prev('input').addClass('s' + (idx + 1));

    var name = elm.id.replace('Slider', '');
    $('#' + elm.id).slider({ // make a slider out of div with id of s1Slider
        value: 50,
        min: 0,
        max: 100,
        step: 1,
        slide: function (event, ui) {
            $('.' + name).val(ui.value);
        }
    });
    $('.sliderValue').attr('readonly', 'readonly');
});


var thisURL = $(location).attr('href');

if (thisURL.substring("Nat2Start") != -1) {

    ($('.progress #global a')).click(function (ev) {
        
        var link = $(this);

        bookmarkWarning(ev, link);

    });

} else {

    /* Exit warning messages */

    ($('.study .studyPlan a, .study #global a, .study footer a, .progress #global a, .progress footer a, .progress #main ol li a')).click(function (ev) {

        var link = $(this);

        printReminder(ev, link);

    });

}


function printReminder(ev, link) {

    var myCookie = getCookie("printReminder");

    if (myCookie == null) { // if cookie doesn't exist        

        /* Alert to remind users to download or print their study plan */

        ev.preventDefault(); // stop the link being followed

        var link = link.attr('href'); //store a reference to the anchor tag

        $('.reminder').css('display', 'block'); // show reminder box
        $('.reminder').centerInClient();

        $('.reminder a#continue').click(function (ev) { // when "continue" link is clicked

            if ($('.reminder input#return').is(':checked')) { // if user chooses "return me"

                $('.reminder').fadeOut('fast'); // hide popup
                ev.preventDefault(); // stop the link being followed
            }
            
            if ($('.reminder input#saved').is(':checked')) {

                $('.reminder').fadeOut('fast'); // hide popup

                $('.reminder a#continue').attr({href: link}); // continue to link destination
            }

            if ($('.reminder input#doNotShowAgain').is(':checked')) {

                setCookie('printReminder', 'doNotShowAgain', exp); // store cookie
            }

        });

    }

    else {
        // if cookie exists, do not show popup (do nothing)
    }
}

function bookmarkWarning(ev, link) {

    var myCookie = getCookie("bookmarkWarning");

    if (myCookie == null) { // if cookie doesn't exist        

        /* Alert to remind users to download or print their study plan */

        ev.preventDefault(); // stop the link being followed

        var link = link.attr('href'); //store a reference to the anchor tag

        $('.exitWarning').css('display', 'block'); // show reminder box
        $('.exitWarning').centerInClient();

        $('.exitWarning a#continue').click(function (ev) { // when "continue" link is clicked

            if ($('.exitWarning input#reviewNow').is(':checked')) { // if user chooses "return me"

                $('.exitWarning').fadeOut('fast'); // hide popup
                ev.preventDefault(); // stop the link being followed
            }

            if ($('.exitWarning input#yes').is(':checked')) {

                $('.exitWarning').fadeOut('fast'); // hide popup

                $('.exitWarning a#continue').attr({ href: link }); // continue to link destination
            }

            if ($('.exitWarning input#doNotShowAgain').is(':checked')) {

                setCookie('bookmarkWarning', 'doNotShowAgain', exp); // store cookie
            }

        });

    }

    else {
        // if cookie exists, do not show popup (do nothing)
    }
}

/* Label highlighting when radio button selected - Interest page */

$('.interest li.group input').click(function () {

    $('.interest li.group label').attr('class', '');

    if ($(this).is(':checked')) { $(this).siblings('label').addClass('selected'); }

});

/* Print */

$('<a href="#" class="print">Print your study plan</a>').insertAfter('body.study .keepCopy strong'); // Insert link when JS is enabled
$('<a href="#" class="print">Print your progress report</a>').insertAfter('body.progress .keepCopy strong'); // Insert link when JS is enabled

$('div.keepCopy a.print').click(function () {
    window.print();
    return false;
});


/* NAT-Interest: Disable continue button until checkbox selected */

var interestFormOl = $('.interest ol.form');
var interestContinue = $('.interest .formContinue');

interestContinue.attr('disabled', 'disabled').addClass('disabled');

$.each(interestFormOl.find(':checkbox'), function () {
    $(this).change(function () {

        if (interestFormOl.find(':checkbox').is(':checked')) {
            interestContinue.removeAttr('disabled').removeClass('disabled');
        } else {
            interestContinue.attr('disabled', 'disabled').addClass('disabled');
        }
    });
});

/* NAT-Interest: Disable continue button until checkbox selected */

var perceptionFormOl = $('.perception ol.form');
var perceptionContinue = $('.perception .formContinue');

perceptionContinue.attr('disabled', 'disabled').addClass('disabled');

$.each(perceptionFormOl.find(':radio'), function () {
    $(this).change(function () {

        if (perceptionFormOl.find(':radio').is(':checked')) {
            perceptionContinue.removeAttr('disabled').removeClass('disabled');
        } else {
            perceptionContinue.attr('disabled', 'disabled').addClass('disabled');
        }
    });
});

/* Audio player - view transcript */

$('.showTranscript').click(function () {

    var $this = $(this)
    transcript = $this.parents('.scene').children('.audioTranscript');
    transcriptLink = $this.parents('.scene').children('.showTranscript');

    if (transcript.css('visibility') == 'hidden') {
        transcript.css('visibility', 'visible');
        transcriptLink.html(transcriptLink.html().replace("View a transcript of this clip", "Hide transcript"));
    } else {
        transcript.css('visibility', 'hidden');
        transcriptLink.html(transcriptLink.html().replace("Hide transcript", "View a transcript of this clip"));
    }
});


/* Bookmark link */

$('a.bookmark').click(function () {
    createBookmark($(location).attr('href'), '');
    return false;
});

function createBookmark(sURL, sTitle) {
    if (document.all && window.external) {
        window.external.AddFavorite(sURL, sTitle);
    }
    else if (window.sidebar) {
        window.sidebar.addPanel(sTitle, sURL, '');
    }
    else {
        alert('The web browser you are using to view this page is not compatible with our bookmarking function.\n\nIf you\'d still like to bookmark this page, please press control and D (or command and D on a Mac).');
    }
}


/* NAT - when exit button clicked, warn user */

function exitWarning(ev, link) {

    /* Alert to check that users want to exit */

    ev.preventDefault(); // stop the link being followed

    $('.exitWarning').css('display', 'block'); // show reminder box
    $('.exitWarning').centerInClient();

    $('.exitWarning a.no').click(function (ev) { // when "no" link is clicked

        $('.exitWarning').fadeOut('fast'); // hide popup
        //return false;

    });

    $('.exitWarning a.yes').click(function (ev) { // when "yes" link is clicked

        $('.exitWarning').fadeOut('fast'); // hide popup
        $('.nat .exit').unbind('click');
        $('.nat .exit').trigger('click');

    });
}

($('.nat .exit')).click(function (ev) {

    var link = $(this);

    exitWarning(ev, link);

});

/* NAT - when Home button clicked, warn user */

function homeWarning(ev, link) {

    /* Alert to check that users want to exit */

    ev.preventDefault(); // stop the link being followed

    $('.homeWarning').css('display', 'block'); // show reminder box
    $('.homeWarning').centerInClient();

    $('.homeWarning a.no').click(function (ev) { // when "no" link is clicked

        $('.homeWarning').fadeOut('fast'); // hide popup
        //return false;

    });

    $('.homeWarning a.yes').click(function (ev) { // when "yes" link is clicked

        $('.homeWarning').fadeOut('fast'); // hide popup
        $('.nat .backHome').unbind('click');
        $('.nat .backHome').trigger('click');

    });
}

($('.nat .backHome')).click(function (ev) {

    var link = $(this);

    if ($('body').hasClass('interest')) { // if on the first page of the study planner
        // do nothing (go to home page as per default)
    } else {

    homeWarning(ev, link);
    }

});


$('#relatedLinks li:even').addClass('leftItem');

$('#relatedLinks li.leftItem').each(function (index) { // equalises the heights of each set of two items (by comparing heights, of left item with the item which immediately follows it)

    var leftItem = $(this);
    var leftHeight = leftItem.height();
    var nextItem = leftItem.next();
    var nextItemHeight = nextItem.height();

    if (leftHeight > nextItemHeight) {
        nextItem.height(leftHeight);
    } else {
        leftItem.height(nextItemHeight);
    }

});


/* ABBR tag formatting fix */

$('abbr').each(function () {
    $(this).attr('title', $(this).attr('title').replace(/\s+/g, " "));
});

/* ABBR tag formatting fix */

$('abbr').each(function () {
    $(this).attr('title', $(this).attr('title').replace(/\s+/g, " "));
});

/* insert video link beneath video */

$(".scene .video-js-box").each(function (x) {

    if (x == 0) { x = (x + 1); };

    var objectCode = $(this).find('video');
    var objectCode = objectCode.html();
    var directUrl = objectCode.substring(objectCode.indexOf('src'));
    directUrl = directUrl.replace(/&quot;/g, '"');

    directUrl = directUrl.substring(5);
    directUrl = directUrl.substring(0, directUrl.indexOf('mp4'));
    directUrl = (directUrl + "mp4");

    var videoLink = $("<p class='videoLink vlink" + (x) + "'>If you're working offline and/or having problems viewing this video, you can <a target='_blank' title='Watch this video on your computer&#8217;s default media player' href='" + directUrl + "'>watch it using your computer&#8217;s default media player</a>.</p>");

    var thisScene = $(this).closest('.scene');
    $(this).prepend(videoLink);

    /* Exceptions */

    /* Fix Module 3.1 Package 14 Slide 3 */
    if ($(this).parents('.scene').find(".slideTitle:contains('expertise of families')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 4.2 Package 31 Slide 5 */
    if ($(this).parents('.scene').find(".slideTitle:contains('Monitoring and developing feeding skills')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('top', 255);
    }

    /* Fix Module 2.3 Package 35 Slide 5 */
    if ($(this).parents('.scene').find(".slideTitle:contains('A real impact on each pupil')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 1.2 Package 13 Slide 1 */
    if ($(this).parents('.scene').find(".slideTitle:contains('Marley\'s review (1)')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 1.2 Package 27 Slide 5 */
    if ($(this).parents('.scene').find(".slideTitle:contains('Children\'s needs')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', 202);
    }

    /* Fix Module 1.3 Package 14 Slide 2 */
    if ($(this).parents('.scene').find(".slideTitle:contains('The sibling relationship')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 1.4 Package 13 Slide 6 */
    if ($(this).parents('.scene').find(".slideTitle:contains('Material wellbeing')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 1.4 Package 26 Slide 1 */
    if ($(this).parents('.scene').find(".slideTitle:contains('proxy respondents and information from each child')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 2.1 Package 4 Slide 2 */
    if ($(this).parents('.scene').find(".slideTitle:contains('Planning for a diverse range of pupils')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 2.1 Package 17 Slide 3 */
    if ($(this).parents('.scene').find(".slideTitle:contains('Case study: Anthony (1)')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', 261);
    }

    /* Fix Module 2.1 Package 19 Slide 4 */
    if ($(this).parents('.scene').find(".slideTitle:contains('A science lesson (2)')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', 202);
    }

    /* Fix Module 2.2 Package 17 Slide 6 */
    if ($(this).parents('.scene').find(".slideTitle:contains('Interventions in action')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 2.2 Package 30 Slide 9 + 10 */
    if ($(this).parents('.scene').find(".slideTitle:contains('Identifying learning objectives')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', 255);
    }

    /* Fix Module 2.2 Package 44 Slide 5 + 6 */
    if ($(this).parents('.scene').find(".slideTitle:contains('an issue for partnership')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 2.2 Package 45 Slide 5 */
    if ($(this).parents('.scene').find(".slideTitle:contains('Involving the pupil: the review')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 2.3 Package 7 Slide 4 */
    if ($(this).parents('.scene').find(".slideTitle:contains('Some questions')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 2.3 Package 12 Slide 2 */
    if ($(this).parents('.scene').find(".slideTitle:contains('The power of music')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 2.3 Package 20 Slide 5 */
    if ($(this).parents('.scene').find(".activity p:contains('Anthony Munday and Dean Cooke')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 3.2 Package 16 Slide 1 */
    if ($(this).parents('.scene').find(".slideTitle:contains('Focus on engagement')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 3.2 Package 21 Slide 2 */
    if ($(this).parents('.scene').find(".slideTitle:contains('The Engagement Profile in action (2)')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 4.1 Package 8 Slide 7 */
    if ($(this).parents('.scene').find(".slideTitle:contains('Addressing health needs (2)')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 4.1 Package 9 Slide 3 */
    if ($(this).parents('.scene').find(".slideTitle:contains('A new family member')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 4.1 Package 11 Slide 9 */
    if ($(this).parents('.scene').find(".slideTitle:contains('Child health services')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 4.1 Package 14 Slide 4 */
    if ($(this).parents('.scene').find(".slideTitle:contains('Speech and language therapists (2)')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 4.1 Package 15 Slide 2 */
    if ($(this).parents('.scene').find(".slideTitle:contains('The importance of communication')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 4.1 Package 18 Slide 5 */
    if ($(this).parents('.scene').find(".slideTitle:contains('Case study: Jade')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 4.1 Package 27 Slide 1 */
    if ($(this).parents('.scene').find(".slideTitle:contains('Sharing information')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

    /* Fix Module 4.2 Package 22 Slide 4 */
    if ($(this).parents('.scene').find(".slideTitle:contains('Listening to pupils (1)')").length == 1) {
        $(this).parents('.scene').find("p.videoLink").css('position', 'absolute').css('top', -9999);
    }

});

