﻿$("html").addClass("js");
$(document).ready(initPage);

function initPage() {

    /*Puts site search text in textbox and activates the focus/blur events*/
    $(".searchLabel").hide();
    var searchLabel = $(".searchLabel").text();
    $("#siteSearch").val(searchLabel);
    $("#siteSearch").focus(searchFocus);
    $("#siteSearch").blur(searchBlur);

    /*Puts keyword course search text in textbox and activates the focus/blur events*/
    $("#keywordSearchLabel").hide();
    var keywordSearchLabel = $("#keywordSearchLabel").text();

    if ($("#keywordSearchBox").val() == "") $("#keywordSearchBox").val(keywordSearchLabel);
    $("#keywordSearchBox").focus(keywordSearchFocus);
    $("#keywordSearchBox").blur(keywordSearchBlur);

    /*dropdown navigation*/
    $("#topNav").children("ul").children("li").hoverIntent(
		function() {
		    $(this).children("a").addClass("hover");
		    $(this).children("ul").slideDown("fast");
		},
		function() {
		    $(this).children("ul").slideUp("fast");
		    $(this).children("a").removeClass("hover");
		}
	);

    /* Handles the course search/order a prospectus open/close animations*/

    $(".courseSearchLinks").children("li").children("a").attr("href", "#");
    $(".searchOptions").children("ul").children("li").children("a").attr("href", "#");

    $("#courseSearchLink").click(setCourseFormState);
    $("#orderProspectusLink").attr("title", "Show order a prospectus.");
    $("#orderProspectusLink").click(setOrderProspectusState);
    $("#rssFeedsLink").click(setRssFeedsState);
    $(".prospectusForm:not(#prospectusFormDefault)").hide();
    $(".prospectusForm:not(#prospectusFormDefault)").children(".prospectusType").css({ width: "0%" });
    $(".feedsForm:not(#feedsFormDefault)").hide();
    $(".feedsForm:not(#feedsFormDefault)").children(".feedsType").css({ width: "0%" });
    $(".searchOption").click(openSearchTypeBox);
    $(".prospectusOption").click(openProspectusTypeBox);
    $(".rssFeedsOption").click(openRssFeedsTypeBox);

    if (window.location.href.indexOf("search/search.php") == -1) {
        $("#courseSearchLink").attr("title", "Show course search.");
        $(".courseForm:not(#courseFormDefault)").hide();
        $(".courseForm:not(#courseFormDefault)").children(".searchTypeBox").css({ width: "0%" });
    }

    /* Replicates the state of common form elements across the forms when switching between course search modes*/
    $(".courseForm").children(".searchBox").children(".formFields").children(".formField").children("input:radio").change(replicateFormChange);

    /* Handles the JS version of the A-Z course search*/
    $("#letterFields").addClass("jsVersion");
    $("#letterFields").children(".letterField").children("label").each(function() { if ($(this).siblings("input:checked").length != 0) { $(this).addClass("selected"); } }).click(setLetterCheckboxState);

    /* Handles validation of the course search tool */
    $("#keyword_submit").click(checkKeywordForm);
    $("#subjectarea_submit").click(checkSubjectAreaForm);
    $("#atoz_submit").click(checkAToZForm);

    /* Puts the appropriate label text in the order a prospectus address fields and activates the focus/blur states */
    $(".prospectus_address").prev("label").hide();
    $(".prospectus_address").each(setAddressFieldContent);

    /* Puts the appropriate label text in the order a order a prospectus email address field and activates the focus/blur states */
    $(".prospectus_email").prev("label").hide();
    var emailLabel = $(".prospectus_email").prev("label").text();
    $(".prospectus_email").val(emailLabel);
    $(".prospectus_email").focus(emailFocus);
    $(".prospectus_email").blur(emailBlur);

    /* Handles validation of the order a prospectus tool */
    $("#prospectus_submit").click(checkProspectusForm);

    /* Handles validation of the rss feeds tool */
    $(".newsButton").click(checkNewsRssForm);
    $(".eventsButton").click(checkEventsRssForm);

    /* Handles the marketing panel animations */
    $(".mpLink").hoverIntent(openMarketingSection, function() { });

    initCourseSearchResults();

    /* course search refine toggle */
    $("#refineBox .title a").toggle(openRefineBox, closeRefineBox);

    /*Set homepage images*/
    for (var i = 1; i < 6; i++) {
        $(".mpBg" + i + "Bg1").hide().removeClass("mpBg" + i + "Bg1");

        var randomNumber = Math.ceil(Math.random() * 3);

        $("#mpBg" + i).addClass("mpBg" + i + "Bg" + randomNumber).show();
    }


    /** START OF INIT COURSE INFO (put in another function)*/
    initCoursePage();
    /* END OF COURSE MEDIA INIT */

    /* update news article pages within section areas */
    if ($(".content .content.newsArticleFull").length > 0) {
        $(".content h2:not(.content .content h2)").hide();
    }

    //Cannot center images in IE6 with CSS for the PhotoGallery functionality, so doing it in Javascript
    if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "6") {
        CenterImagesInIE6(".photoGalleryImageList ul#mycarousel a img");
        CenterImagesInIE6("div.photoGalleryContent div.imageContainer div.innerImageContainer img");
    }

    //Set up the PhotoGallery functionality, if required
    try {
        InitPhotoGallery("div.photoGalleryImageListThreeCols", 2, 6);
    } catch (e) { }

    setUpSlides();

    stabliseColumnHeight();

    //    $('div.showhide.closed:first').removeClass('closed');
    $('div.showhide.closed .collapsible').hide();
    $('div.showhide h2, div.showhide h3, div.showhide h4').click(function() {
        $(this).parents('.showhide').toggleClass('closed').find('.collapsible').slideToggle("slow");
    });
}

/**
* Used to ensure the nav column and the the content column are the same 
* height 
**/
function stabliseColumnHeight() {

    var heightCols = $(".setHeight");
    var maxHeight = 0;
    for (i = 0; i < heightCols.length; i++) {
        if ($(heightCols[i]).height() > maxHeight)
            maxHeight = $(heightCols[i]).height();
    }
    $(".setHeight").each(function() { $(this).height(maxHeight) });
}

/**
* initialises the course information page
**/
function initCoursePage() {

    $("#studentTabs").show();
    $("#courseOutline .tabPanel").hide();
    $("#courseOutline .courseDetails").show();
    $("#courseOutline .studentType h3").addClass("hidden");
    $("#courseOutline .tabPanel h4").addClass("hidden");
    $("#courseOutline .tabs").show();

    if ($("#courseOutline .videos").length > 0)
        $("#courseOutline .videos").show();

    if ($("#courseOutline .videos").length == 0 && $("#courseOutline .images").length > 0)
        $("#courseOutline .images").show();

    $(".studentType").hide();
    $("#uk").show();

    // highliths the clicked tab
    $("#courseOutline .tabs a").click(function() {

        var parentPanel = $(this).parent().parent().parent();

        // set the appropriate tab
        parentPanel.find(".tabs li").removeClass("current");
        $(this).parent().addClass("current");

        return false;
    });

    // displays the appropriate content for tabs in each student type
    $("#courseOutline .courseInfo .tabs a").click(function() {

        var id = $(this).attr("href").replace("#", "");
        var selector = "#courseOutline #" + id.split("_")[0] + " .courseInfo ." + id.split("_")[1];
        var parentPanel = $(this).parent().parent().parent();

        // show the appropriate panel
        parentPanel.find(".tabPanel").hide();
        $(selector).show();

        return false;
    });

    // displays the appropreiate content for the studen ttype tabs
    $("#studentTabs a").click(function() {

        var id = $(this).attr("href").replace("#", "");
        displayStudentTab(id);
        return false;
    });

    $(".mediaSelector .viewport").css("overflow", "hidden");
    $(".mediaSelector a.nav").click(function() {

        if (!g_mediaSelectorInProgress) {
            var viewport = $(this).parents(".mediaSelector").find(".viewport");

            if ($(this).hasClass("navLeft")) {
                scrollViewportNavigation(viewport, "+=");
            }
            else if ($(this).hasClass("navRight")) {
                scrollViewportNavigation(viewport, "-=");
            }
        }

        return false
    });

    $("#courseOutline .mediaSelector .item a").click(showMedia);
    $("#courseOutline .mediaPlayer a.close").click(closeMedia);

    // set the show/hide links of the infom panels
    $("#courseOutline .infoPanel h4 a").click(function() {

        var infoPanel = $(this).parents(".infoPanel");

        if ($(this).hasClass("open")) {
            infoPanel.find(".infoContent").slideUp();
            $(this).removeClass("open");
            $(this).addClass("closed");
        }
        else if ($(this).hasClass("closed")) {
            infoPanel.find(".infoContent").slideDown();
            $(this).removeClass("closed");
            $(this).addClass("open");
        }

        return false;
    });

    $("#courseOutline .infoPanel h4 a.closed").parent().siblings(".infoContent").hide();

    // open the appropriate tab
    loc = document.location.toString();
    if (loc.indexOf("loc=uk") > 0)
        displayStudentTab("uk");
    else if (loc.indexOf("loc=notuk") > 0)
        displayStudentTab("nonuk");
    else if (loc.indexOf("loc=fe") > 0)
        displayStudentTab("fe");

    /* hides the Questions about applying area */
    $("#courseContacts .container").hide();
    $("#courseContacts .findOutMore a").toggle(
        function() {
            $(this).parents("#courseContacts").find(".container").slideDown();
        },
        function() {
            $(this).parents("#courseContacts").find(".container").slideUp();
        });
}

/**
* Displays the specified student tab (and hides the others)
**/
function displayStudentTab(id) {
    $(".studentType").hide();
    $("#" + id).show();
    $("#studentTabs .tabs li").removeClass("current");
    $("#studentTabs .tabs li a[href=#" + id + "]").parent().addClass("current");
}

var g_mediaSelectorInProgress = false;

/**
* scrolls the media selector view port
*/
function scrollViewportNavigation(viewport, direction) {

    g_mediaSelectorInProgress = true;

    var multiplier = 3;
    var amount = parseInt(viewport.find(".item").css("width").replace("px", ""), 10);
    var holder = viewport.find(".holder");
    var marginPosition = parseInt(holder.css("margin-left").replace("px", ""), 10);
    var itemCount = holder.find(".item").length;
    var limit = (amount * multiplier) - (itemCount * amount);

    if (direction == "-=") {
        if (marginPosition <= 0 && marginPosition > limit)
            holder.animate({ marginLeft: direction + (amount * multiplier) + "px" }, 1000, function() { g_mediaSelectorInProgress = false; });
        else
            g_mediaSelectorInProgress = false;
    }
    else if (direction == "+=") {
        if (marginPosition < 0)
            holder.animate({ marginLeft: direction + (amount * multiplier) + "px" }, 1000, function() { g_mediaSelectorInProgress = false; });
        else
            g_mediaSelectorInProgress = false;
    }
    else
        g_mediaSelectorInProgress = false;
}

/**
* Shows the selected media
**/
function showMedia() {

    var mediaPlayer;
    var href;
    var stuType;

    mediaPlayer = $(this).parents(".tabInfoPanel").find(".mediaPlayer");
    href = $(this).attr("href");
    stuType = $(this).parents(".studentType").attr("id");

    if (mediaPlayer.css("display") != "block") {

        if (endsWidth(href, ".flv")) {
            mediaPlayer.find("object").hide();
            mediaPlayer.find("embed").hide();
            mediaPlayer.slideDown(function() {
                mediaPlayer.find("object").show();
                mediaPlayer.find("embed").show();

                // load the video
                mediaPlayer.find(".player").html("<div id='" + stuType + "_videoPlayer'>VIDEO HERE</div>");
                var videoID = href.substring(href.lastIndexOf("/") + 1);
                var flashvars = { vid: videoID };
                var params = {};
                var attributes = {};
                swfobject.embedSWF("/media/gcalwebv2/gcal-site/fla/courseVideoPlayer.swf", stuType + "_videoPlayer", "440", "280", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
            });
        }
        else {
            mediaPlayer.find(".player img").attr("src", href);
            mediaPlayer.slideDown();
        }

    }
    else {
        if (endsWidth(href, ".flv")) {

            // load the video
            mediaPlayer.find(".player").html("<div id='" + stuType + "_videoPlayer'>VIDEO HERE</div>");
            var videoID = href.substring(href.lastIndexOf("/") + 1);
            var flashvars = { vid: videoID };
            var params = {};
            var attributes = {};
            swfobject.embedSWF("/media/gcalwebv2/gcal-site/fla/courseVideoPlayer.swf", stuType + "_videoPlayer", "440", "280", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
        }
        else {
            mediaPlayer.find(".player img").attr("src", href);
        }

    }

    return false;
}

function endsWidth(string, value) {
    return (string.match(value + "$") == value);
}

/**
* Closes the course media player
**/
function closeMedia() {

    var mediaPlayer;
    var stuType;

    stuType = $(this).parents(".studentType").attr("id");

    mediaPlayer = $(this).parents(".mediaPlayer");
    mediaPlayer.find("object").hide();
    mediaPlayer.find("embed").hide();
    mediaPlayer.slideUp(function() {
        if (mediaPlayer.parents(".videos").length > 0)
            mediaPlayer.find(".player").html("<div id='" + stuType + "_videoPlayer'>VIDEO HERE</div>");
    });

    return false;
}

var bgTimer;
var currentId = 1;

function openMarketingSection() {
    $(this).parent(".mpItem").each(moveMarginTopUp);
    $(this).addClass("selected");
    $(this).parent(".mpItem").siblings(".mpItem").children(".mpLink").removeClass("selected");
    $(this).parent(".mpItem").prevAll(".mpItem").each(moveMarginTopUp);
    $(this).parent(".mpItem").nextAll(".mpItem").each(moveMarginTopDown);

    var currID = $(this).parent(".mpItem").attr("id");
    $("#marketingPanel").removeClass();
    $("#marketingPanel").addClass(currID);

    //swap the background of the panel after n milliseconds
    var newId = Number($(this).parent(".mpItem").attr("id").slice(-1)); // get the id of this element
    bgTimer = setTimeout(function() { swapBackground(newId) }, 350);
}

function moveMarginTopUp() {
    switch ($(this).attr("id")) {
        case "mp2":
            $(this).animate({ marginTop: "-12.8em" }, 100);
            break;
        case "mp3":
            $(this).animate({ marginTop: "-8.4em" }, 100);
            break;
        case "mp4":
            $(this).animate({ marginTop: "-4em" }, 100);
            break;
        case "mp5":
            $(this).animate({ marginTop: "0.4em" }, 100);
            break;
        default:
            //Do nothing
            break;
    }
}

function moveMarginTopDown() {
    switch ($(this).attr("id")) {
        case "mp2":
            $(this).animate({ marginTop: "0em" }, 100);
            break;
        case "mp3":
            $(this).animate({ marginTop: "4.3em" }, 100);
            break;
        case "mp4":
            $(this).animate({ marginTop: "8.6em" }, 100);
            break;
        case "mp5":
            $(this).animate({ marginTop: "12.9em" }, 100);
            break;
        default:
            //Do nothing
    }
}

function swapBackground(newId) {
    if (newId != currentId) {//only swap if the requested background is different from current one
        if (newId < currentId) {
            //new image is above old image
            //fade in new div
            $("#mpBg" + newId).fadeIn(200,
            //hide old div
				function() {
				    $("#mpBg" + currentId).hide();
				    currentId = newId;
				}
			);
        }

        if (newId > currentId) {
            //new image is beneath old image
            //show new div
            $("#mpBg" + newId).show();
            //fade out old div
            $("#mpBg" + currentId).fadeOut(200,
				function() {
				    currentId = newId;
				}
			);
        }
    }
}

function swapBackground_v1(e) {
    if ($("#mpBackground").attr("class") != e) {
        $("#mpBackground").fadeOut(150,
			function() {
			    $("#mpBackground").attr("class", e);
			    $("#mpBackground").fadeIn(150);
			}
		);
    }
}

function moveBackground(y) {
    $("#marketingPanel").animate({ backgroundPosition: "(0 " + y + "px)" })
}

function switchMPBackground(id) {
    $("#marketingPanel").toggleClass(id);
}

/* Focus event of site search textbox */
function searchFocus() {
    if ($(this).val() == $(".searchLabel").text()) {
        $(this).val("");
    }
}

/* Blur event of site search textbox */
function searchBlur() {
    if ($("#siteSearch").val() == "") {
        var searchLabel = $(".searchLabel").text();
        $("#siteSearch").val(searchLabel);
    }
}

/* Focus event of course keyword search textbox */
function keywordSearchFocus() {
    if ($(this).val() == $("#keywordSearchLabel").text()) {
        $(this).val("");
    }
}

/* Blur event of course keyword search textbox */
function keywordSearchBlur() {
    if ($("#keywordSearchBox").val() == "") {
        var searchLabel = $("#keywordSearchLabel").text();
        $("#keywordSearchBox").val(searchLabel);
    }
}

/* Handles the opening/closing of the course search tool */
function setCourseFormState() {
    if ($(this).parent("li").parent("ul").siblings(".courseSearchForm:visible").length > 0) {
        closeTopTools();
    }
    else {
        closeTopTools();
        openCourseSearch();
    }

    return false;
}

/* Handles the opening/closing of the order a prospectus tool */
function setOrderProspectusState() {
    if ($(this).parent("li").parent("ul").siblings(".orderProspectusForm:visible").length > 0) {
        closeTopTools();
    }
    else {
        closeTopTools();
        openOrderProspectus();
    }

    return false;
}

/* Handles the opening/closing of the RSS feeds tool */
function setRssFeedsState() {
    if ($(this).parent("li").parent("ul").siblings(".rssFeedsForm:visible").length > 0) {
        closeTopTools();
    }
    else {
        closeTopTools();
        openRssFeeds();
    }

    return false;
}

/* Closes all top tools */
function closeTopTools() {
    closeCourseSearch();
    closeOrderProspectus();
    closeRssFeeds();
}

/* Opens the course search tool */
function openCourseSearch() {
    removeSelectedState();
    $("#courseSearchLink").addClass("selected");
    $("#courseSearchLink").attr("title", "Hide course search.");
    $("#courseSearchLink").parent("li").parent("ul").siblings(".courseSearchForm").slideDown("fast");
}

/* Closes the course search tool */
function closeCourseSearch() {
    removeSelectedState();
    $("#courseSearchLink").attr("title", "Show course search.");
    $("#courseSearchLink").parent("li").parent("ul").siblings(".courseSearchForm").slideUp("fast");
}

/* Opens the order a prospectus tool */
function openOrderProspectus() {
    removeSelectedState();
    $("#orderProspectusLink").addClass("selected");
    $("#orderProspectusLink").attr("title", "Hide order prospectus.");
    $("#orderProspectusLink").parent("li").parent("ul").siblings(".orderProspectusForm").slideDown("fast");
}

/* Closes the order a prospectus tool */
function closeOrderProspectus() {
    removeSelectedState();
    $("#orderProspectusLink").attr("title", "Show order prospectus.");
    $("#orderProspectusLink").parent("li").parent("ul").siblings(".orderProspectusForm").slideUp("fast");
}

/* Opens the order a prospectus tool */
function openRssFeeds() {
    removeSelectedState();
    $("#rssFeedsLink").addClass("selected");
    $("#rssFeedsLink").attr("title", "Hide RSS feeds.");
    $("#rssFeedsLink").parent("li").parent("ul").siblings(".rssFeedsForm").slideDown("fast");
}

/* Closes the order a prospectus tool */
function closeRssFeeds() {
    removeSelectedState();
    $("#rssFeedsLink").attr("title", "Show RSS feeds.");
    $("#rssFeedsLink").parent("li").parent("ul").siblings(".rssFeedsForm").slideUp("fast");
}

function removeSelectedState() {
    $("#courseSearchLink").removeClass("selected");
    $("#orderProspectusLink").removeClass("selected");
    $("#rssFeedsLink").removeClass("selected");
}

/* Handles the opening/closing of the various course search options */
function openSearchTypeBox() {
    $(".searchOption").unbind('click', openSearchTypeBox);

    var id = $(this).attr("id");

    if (($("." + id + ":visible").length == 0)) {
        displaySearchTypeBox(id, true);
        $(".error").hide();
    }
    else {
        $(".searchOption").click(openSearchTypeBox);
    }

    return false;
}

/* Handles the open/closing of the various prosoecturs options */
function openProspectusTypeBox() {

    $(".prospectusOption").unbind('click', openProspectusTypeBox);

    var id = $(this).attr("id");

    if (($("." + id + ":visible").length == 0)) {

        //$(".prospectusForm:visible").children(".prospectusType").animate({ width: "0%" }, 300);
        $(".prospectusForm:visible").children(".address").animate({ width: "0%" }, 300, function() { $(this).hide(); });
        $(".prospectusForm:visible").children(".email").animate({ width: "0%" }, 300, function() { $(this).hide(); });
        $(".prospectusForm:visible").children(".prospectusOrderButton").animate({ width: "0%" }, 300, function() { $(this).hide(); });


        $(".prospectusForm:visible").children(".prospectusType").animate({ width: "0%" }, 300, function() {
            $(".prospectusForm:visible").hide();
            $(".prospectusOption").parent("li").removeClass("selected");
            $("#" + id).parent("li").addClass("selected");
            $("." + id).show();

            $("." + id).children(".prospectusType").animate({ width: "19em" }, 300, function() { $(".prospectusOption").click(openProspectusTypeBox); });
            $("." + id).children(".address").animate({ width: "19em" }, 300);
            $("." + id).children(".email").animate({ width: "22em" }, 300);
            $("." + id).children(".prospectusOrderButton").animate({ width: "12.5em" }, 300);
        });


        $(".error").hide();
    }
    else {
        $(".prospectusOption").click(openProspectusTypeBox);
    }

    return false;
}

/* Handles the opening/closing of the various RSS feeds options */
function openRssFeedsTypeBox() {
    $(".rssFeedsOption").unbind('click', openRssFeedsTypeBox);

    var id = $(this).attr("id");

    if (($("." + id + ":visible").length == 0)) {

        $(".feedsForm:visible").children(".feedCategories").animate({ width: "0%" }, 300, function() {
            $(".feedsForm:visible").hide();
            $(".rssFeedsOption").parent("li").removeClass("selected");
            $("#" + id).parent("li").addClass("selected");
            $("." + id).show();

            $("." + id).children("#newsRss").animate({ width: "32em" }, 300, function() { $(".rssFeedsOption").click(openRssFeedsTypeBox); });
            $("." + id).children("#eventsRss").animate({ width: "32em" }, 300, function() { $(".rssFeedsOption").click(openRssFeedsTypeBox); });
        });

        $(".error").hide();
    }
    else {
        $(".rssFeedsOption").click(openRssFeedsTypeBox);
    }

    return false;
}

/* Displays the specified search box */
function displaySearchTypeBox(id, bAnimate) {

    if (bAnimate) {
        $(".courseForm:visible").children(".searchTypeBox").animate({ width: "0%" }, 300, function() {
            $(".courseForm:visible").hide();
            $(".searchOption").parent("li").removeClass("selected");
            $("#" + id).parent("li").addClass("selected");
            $("." + id).show();
            $("." + id).children(".searchTypeBox").animate({ width: "29em" }, 300, function() { $(".searchOption").click(openSearchTypeBox); });
        });
    }
    else {
        $(".courseForm:visible").children(".searchTypeBox").css("width", "0%");
        $(".courseForm:visible").hide();
        $(".searchOption").parent("li").removeClass("selected");
        $("#" + id).parent("li").addClass("selected");
        $("." + id).show();
        $("." + id).children(".searchTypeBox").css("width", "29em");
    }
}

/* Replicates any form changes across the other course search forms */
function replicateFormChange() {
    var radioClass = $(this).attr("class");
    $("." + radioClass).attr("checked", "checked");
}

/* Sets the checked/unchecked state of the A-Z course search */
function setLetterCheckboxState() {
    $(this).toggleClass("selected");

    // ie8 fix
    if ($.browser.msie && $.browser.version == "8.0")
        $("#" + $(this).attr("for")).attr("checked", true);
}

/* Validation of keyword course search form */
function checkKeywordForm() {
    if ($("#keywordSearchBox").val() == $("#keywordSearchLabel").text()) {
        $(this).next(".error").show();
        return false;
    }
    else {
        $(this).next(".error").hide();
    }
}

/* Validation of subject area course search form */
function checkSubjectAreaForm() {
    if ($("input:checkbox[name='a[]']:checked").length == 0) {
        $(this).next(".error").show();
        return false;
    }
    else {
        $(this).next(".error").hide();
    }
}

/* Validation of a-z course search form */
function checkAToZForm() {
    if ($("input:checkbox[name='let[]']:checked").length == 0) {
        $(this).next(".error").show();
        return false;
    }
    else {
        $(this).next(".error").hide();
    }
}

/* Sets the value of the order a prospectus address fields and activates the focus/blur event */
function setAddressFieldContent() {
    var prospectusAddressLabel = $(this).prev("label").text();
    $(this).val(prospectusAddressLabel);
    $(this).focus(prospectusAddressFocus);
    $(this).blur(prospectusAddressBlur);
}

/* Focus event for order a prospectus address fields */
function prospectusAddressFocus() {
    if ($(this).val() == $(this).prev("label").text()) {
        $(this).val("");
    }
}

/* Blur event for order a prospectus address fields */
function prospectusAddressBlur() {
    if ($(this).val() == "") {
        var addressLabel = $(this).prev("label").text();
        $(this).val(addressLabel);
    }
}

/* Focus event for order a prospectus email field */
function emailFocus() {
    if ($(this).val() == $(this).prev("label").text()) {
        $(this).val("");
    }
}

/* Blur event for order a prospectus email field */
function emailBlur() {
    if ($(this).val() == "") {
        var emailLabel = $(this).prev("label").text();
        $(this).val(emailLabel);
    }
}

/* Validation of order a prospectus form */
function checkProspectusForm() {
    var isValid = true;

    if ($("input:checkbox[name='ProspectusType']:checked").length <= 0) {
        isValid = false;
        $("#prospectus_error").text("Error: You must select a prospectus type");
    }

    if ($("#address_name").val() == $("#address_name").prev("label").text()) {
        isValid = false;
        $("#prospectus_error").text("Error: You must provide a valid full name");
    }

    if ($("#address_one").val() == $("#address_one").prev("label").text()) {
        isValid = false;
        $("#prospectus_error").text("Error: You must provide a valid address");
    }

    if ($("#address_city").val() == $("#address_city").prev("label").text()) {
        isValid = false;
        $("#prospectus_error").text("Error: You must provide a valid address");
    }

    if ($("#address_postcode").val() == $("#address_postcode").prev("label").text()) {
        isValid = false;
        $("#prospectus_error").text("Error: You must provide a valid address");
    }

    if ($("#address_country").val() == $("#address_country").prev("label").text()) {
        isValid = false;
        $("#prospectus_error").text("Error: You must provide a country");
    }

    if ($("#prospectus_email").val() == $("#prospectus_email").prev("label").text()) {
        isValid = false;
        $("#prospectus_error").text("Error: You must provide a valid email address");
    }

    if (!isValid) {
        $(this).next(".error").show();
        return false;
    }
    else {
        $(this).next(".error").hide();

        if ($("#address_two").val() == $("#address_two").prev("label").text()) {
            $("#address_two").val() == "";
        }
    }
}

/* Validation of news RSS form */
function checkNewsRssForm() {
    var isValid = true;

    if ($("input:checkbox[name='NewsCategory[]']:checked").length <= 0) {
        isValid = false;
    }

    if (!isValid) {
        $("#rssNewsError").show();
        return false;
    }
    else {
        $("#rssNewsError").hide();
    }
}

/* Validation of news RSS form */
function checkEventsRssForm() {
    var isValid = true;

    if ($("input:checkbox[name='EventsCategory[]']:checked").length <= 0) {
        isValid = false;
    }

    if (!isValid) {
        $("#rssEventsError").show();
        return false;
    }
    else {
        $("#rssEventsError").hide();
    }
}



/** Toggels the content section in teh course outline pages */
function toggleContentSection() {

    var ele;

    ele = $(this).parent().parent();

    if (ele.hasClass("closed")) {
        ele.children(".content").slideDown("fast", function() {
            ele.removeClass("closed");
        });
    }
    else {
        ele.children(".content").slideUp("fast", function() {
            ele.addClass("closed");
        });

    }
}

/**
* initialises the course search results
**/
function initCourseSearchResults() {
    $("table#searchResults tr.info td.summary a").click(function() {
        $("table#searchResults tr.moreInfo." + $(this).attr("href").replace("#", "")).show();
        return false;
    });

    $("table#searchResults tr.moreInfo td.summary a").click(function() {
        $("table#searchResults tr.moreInfo." + $(this).attr("href").replace("#", "")).hide();
        return false;
    });

    $("a.showSummary").toggle(showSummary, hideSummary);
}

function showSummary() {
    var img = $(this).children("img");
    var rowId = $(this).attr("href").replace("#", "");

    img.attr("src", img.attr("src").replace("_closed", "_open"));
    $("#" + rowId).show();
    $("#" + rowId).children("td").show();
}

function hideSummary() {
    var img = $(this).children("img");
    var rowId = $(this).attr("href").replace("#", "");

    img.attr("src", img.attr("src").replace("_open", "_closed"));
    $("#" + rowId).hide();
    $("#" + rowId).children("td").hide();
}

function openRefineBox() {
    $("#refineBox .optionArea").slideDown("fast", function() {
        $("#refineBox .title a").attr("class", "open");
    });

}

function closeRefineBox() {
    $("#refineBox .optionArea").slideUp("fast", function() {
        $("#refineBox .title a").attr("class", "closed");
    });
}

function setUpSlides() {
    $("div.slidesContainer").each(function() {
        var cont = $(this);
        cont.height(cont.find("img").height());
        cont.find("ul.slides").each(function() {
            var ul = $(this);
            ul.find("li:not(:has(a img))").remove();
            unwrap(ul.find("li a span img"));
            unwrap(ul.find("li a[@href=''] img"));
        }).innerfade({ speed: 1000, timeout: 5000, type: 'sequence' });
    });
}

function unwrap(jqobj) {
    if (jqobj.length == 1) {
        var tbr = jqobj.parent();
        tbr.parent().append(jqobj);
        tbr.remove();
    }
}

// displays the post count next to the job family 
function jobPostCount(id) {

    var count = $("#" + id + " tbody tr").size();
    var outputString;

    if (count > 1)
        outputString = "(" + count + " posts)";
    else
        outputString = "(" + count + " post)";

    $("#" + id + "Count").html(outputString);
}
