
// Set the hover state for the course finder
function courseFinderHover() {
	$(".courseFinder ul li a").hover(
		function() {
			$(this).parent().siblings().removeClass("active");
			$(this).parent().addClass("active");
		}
	);
}

// Set the hover state for the research finder
function researchFinderHover() {
	$(".researchFinder ul li a").hover(
		function() {
			$(this).parent().siblings().removeClass("active");
			$(this).parent().addClass("active");
		}
	);
}


// Set the hover state for the jump links
function jumpLinkHover() {
	$("#pageContent .jumpLink").hover(
		function() {
			$(this).addClass("hover");
		},
		function() {
			$(this).removeClass("hover");
		}
	);
	$("#pageContent .jumpLink").click(function() {
		window.location = ($(this).find("a").attr("href"));
	});
}

// Setup the rotating feature
function rotatingFeature() {
	narrow = $("#pageContent .rotatingFeature").width() == 500 ? true : false;
	$("#pageContent .rotatingFeature ul li").each(function() {
		$(this).find("h3").clone().insertAfter($(this).find(".feature img"));
		$(this).find(".feature h3 a").parent().append($(this).find(".feature h3 a").remove().html());
	});
	$("#pageContent .rotatingFeature ul li h3").append('<div class="arrow"></div>');
	if (!narrow) {$("#pageContent .rotatingFeature ul li h3 a").append('<div class="corner"></div>');}
	$("#pageContent .rotatingFeature").append('<div class="features"></div>');
	$("#pageContent .rotatingFeature ul li .feature").appendTo("#pageContent .rotatingFeature .features");
	$("#pageContent .rotatingFeature .feature").hide();
	$("#pageContent .rotatingFeature .feature:eq(0)").addClass("active").show();
	if (narrow) {
		$("#pageContent .rotatingFeature ul li h3 a").append('<div class="cornerLeft"></div><div class="cornerRight"></div>');
		$("#pageContent .rotatingFeature ul li").hide();
		$("#pageContent .rotatingFeature ul li:eq(0)").show();
		$("#pageContent .rotatingFeature").append('<div class="nav"><a href="#" class="previous">&lt;</a> <a href="#" class="next">&gt;</a></div>');
		$("#pageContent .rotatingFeature .nav a").click(function() {
			var $active = $("#pageContent .rotatingFeature ul li.active");
			if($(this).hasClass("previous")) {
				var $next = $active.prev().length ? $active.prev() : $("#pageContent .rotatingFeature ul li:last");
			} else {
				var $next = $active.next().length ? $active.next() : $("#pageContent .rotatingFeature ul li:first");
			}
			rotatingFeatureSwitch($next,narrow);
			return false;
		});
		$("#pageContent .rotatingFeature .nav a").hover(
		  function () {
			$(this).css("background-image",$(this).css("background-image").replace(/.png/g, '_active.png'));// mouse over image
			clearInterval(playSlideshow);
		}, 
		  function () {
			$(this).css("background-image",$(this).css("background-image").replace(/_active.png/g, '.png'));// mouse out image
			playSlideshow =  setInterval( 'rotatingFeatureSwitch(null,narrow)', 10000 );
		  }
		);		
	}
	$("#pageContent .rotatingFeature ul li:eq(0)").addClass("active");

	// set cycle interval
	var playSlideshow =  setInterval( 'rotatingFeatureSwitch(null,narrow)', 10000 );
	$("#pageContent .rotatingFeature ul li h3 a").hover(
		function() {
			if(!narrow) {
				rotatingFeatureSwitch($(this).parents("li"));
				clearInterval(playSlideshow);
			}
		},
		function() {
			if(!narrow) {playSlideshow =  setInterval( 'rotatingFeatureSwitch(null,narrow)', 10000 );}
		}
	);
	$("#pageContent .rotatingFeature .feature").hover(
		function() {
			$(this).addClass("hover");
			clearInterval(playSlideshow);
		},
		function() {
			$(this).removeClass("hover");
			playSlideshow =  setInterval( 'rotatingFeatureSwitch(null,narrow)', 10000 );
		}
	);
	$("#pageContent .rotatingFeature .feature").click(function() {
		window.location = ($("#pageContent .rotatingFeature ul li:eq(" + ($(this).index()) + ") a").attr("href"));
	});
}

function rotatingFeatureSwitch(obj, narrow) {
	
	// jump to end of animation if another is initiated
	if ($('#pageContent .rotatingFeature .feature').is(':animated')) {
		$('#pageContent .rotatingFeature .feature.last-active, #pageContent .rotatingFeature ul li.last-active').removeClass('last-active').css("position","").css({opacity: null}).stop().hide();
		$('#pageContent .rotatingFeature .feature.active, #pageContent .rotatingFeature ul li.active').css({opacity: null}).stop().show();
	}
	
	var $active = $('#pageContent .rotatingFeature ul li.active');

	// set next section in cycle, at end of list reset to first item
	var $next = $active.next().length ? $active.next()
		: $('#pageContent .rotatingFeature ul li:first');
	
	// check if a specific section has been requested
	if(obj) $next = obj;

	// only animate if next section is different to current section
	if($active.index() != $next.index()) {
		$active.removeClass("active");
		$next.addClass("active");
		if (narrow) {
			$next.fadeIn(2000);
			$active.addClass("last-active").css("position","absolute").fadeOut(2000,function() {
				$(this).removeClass("last-active").css("position","");
			});
		}
		$("#pageContent .rotatingFeature .feature:eq(" + $next.index() + ")").addClass("active").fadeIn(2000,function() {
			// removed for now as the redraw is causing a leak in IE and rendering issues with nav hover states
			// if(isdefined("curvyCorners")){curvyCorners.redraw();}
		});
		$("#pageContent .rotatingFeature .feature:eq(" + $active.index() + ")").removeClass("active").addClass("last-active").css("position","absolute").fadeOut(2000,function() {
			$(this).removeClass("last-active").css("position","");
		});
	}
}


// Add quotes to blockquotes
function blockquotes() {
	$("p.pullquote").prepend('<span class="quoteopen">&ldquo;</span>').append('<span class="quoteclosed">&rdquo;</span>');
	$("p.pullquote, p.textsplash").wrapInner('<span class="container"></span>');
}

// Add class to alternate rows
function alternateRows() {
	$("#pageContent #mainpage .maincontent table.StripedTable tr:even, #pageContent #mainpage .maincontent .newsstory:even").addClass("alt");
}

// Add icons to downloads
function downloadIcons() {
	var arrFileTypes = ["doc","docx","xls","xlsx","ppt","pptx","pdf","zip","gif","png","jpg","jpeg"];
	for (i in arrFileTypes) {
		$("#pageContent .links ul li a[href$='." + arrFileTypes[i] + "']").parent().addClass(arrFileTypes[i]);
		$("#pageContent .links ul li a[href$='." + arrFileTypes[i] + "']").after('<div class="meta"><span class="filetype">' + arrFileTypes[i] + '</span></div>');
		$("#pageContent .links ul li a[href$='." + arrFileTypes[i] + "']").parent().each(function() {
			$(this).find(".filesize").prepend(", ").appendTo($(this).find(".meta"));
		});
	}
}

// Setup image captions
function imageCaptions(){
	$("#pageContent #mainpage .maincontent img:not(.inlineimg):not(#gallery img):not(#tabs img):not(#slideshow-area img):not(#accordion img):not(table img)").each(function () {
		divWrapper = $('<div/>').addClass('img'+$(this).attr("class")).css({width:$(this).outerWidth(true)});
		if ($(this).parent().get(0).tagName == "A") {
			$(this).parent().wrap(divWrapper);
		} else {
			$(this).wrap(divWrapper);
		};
		$(this).removeAttr("class");
		if ($(this).attr("title") != "") {
			$(this).after('<p class="caption">' + $(this).attr("title") + "</p>");
		} else if ($(this).parent("a").attr("title") != "" && $(this).parent("a").attr("title") != undefined) {
			$(this).after('<p class="caption">' + $(this).parent("a").attr("title") + "</p>");
		};
	});
}


function imageCaptionsLinks(){
	$("#pageContent #mainpage #mainpage_forbottom .links img:not(.inlineimg):not(#gallery img):not(#tabs img):not(#slideshow-area img):not(table img)").each(function () {
		divWrapper = $('<div/>').addClass('img'+$(this).attr("class")).css({width:$(this).outerWidth(true)});
		if ($(this).parent().get(0).tagName == "A") {
			$(this).parent().wrap(divWrapper);
		} else {
			$(this).wrap(divWrapper);
		};
		$(this).removeAttr("class");
		if ($(this).attr("title") != "") {
			$(this).after('<p class="captionLinks">' + $(this).attr("title") + "</p>");
		} else if ($(this).parent("a").attr("title") != "" && $(this).parent("a").attr("title") != undefined) {
			$(this).after('<p class="captionLinks">' + $(this).parent("a").attr("title") + "</p>");
		};
	});
}

// Set external links to open in a new window
function externalLinks() {
	$('a[href^=http://]:not([href*="gla.ac.uk"]):not([href*="glasgow.ac.uk"]),a[href^=https://]:not([href*="gla.ac.uk"]):not([href*="glasgow.ac.uk"])').each(function() {
		// Fix for IE6 and 7 inexplicably applying the above selector for the A-Z list nav
		if (!($(this).parent().hasClass("ln-letters"))) {
            // Removed by DG 14/04/2011 (it was breaking images)
			/*var titleStr = $(this).attr("title");
			if (titleStr!="" && titleStr!=undefined) {
				titleStr += " (new window)";
			} else {
				titleStr = "(new window)";
			}*/
			$(this).addClass("externalLink");
			//$(this).attr("title", titleStr);
			$(this).click(function() {
				window.open(this.href);
				return false;
			});
		}
	});
}

function externalLinksImg() {

}

// Clear value on focus
function clearOnEnter() {
	// Store the default value for each box
	$('.clearOnEnter, #siteSearch form #ssKeywords, #individualSearch form #isKeywords').each(function() {
		$(this).data('swap', $(this).attr('value'));
	}).bind('focus', function() {
		if ($(this).val() == $(this).data('swap')) {
			$(this).val('');
		}
	}).bind('blur', function() {
		if ($(this).val() == '') {
			$(this).val($(this).data('swap'));
		}
	});
}

function slideList() {
	$('ul.slide').each(function() {
		if ($(this).children('li').length > 3) {
			$(this).children('li:gt(2)').hide();
			$(this).append('<li class="more"><a href="#"><span>Show all...</span></a></li>');
			$(this).children('li.more').click(function() {
				var speed = $.browser.msie ? 0 : 200;
				if ($.browser.msie) {
					$(this).addClass("loading").find("a span").text("Loading...");
				}
				$parentthis = $(this);
				$(this).siblings("li:gt(2):not(this)").delay(0).toggle(speed,function() {
					// IE7 ClearType fix
					if($.browser.msie) {$(this).get(0).style.removeAttribute('filter');}
					if ($(this).index() == $parentthis.siblings("li").length-1) {
						// intentionally duplicated, not sure why the redraw doesn't work without
						if(isdefined("curvyCorners")){
							curvyCorners.redraw();
							curvyCorners.redraw();
						}
						if ($parentthis.hasClass("open")) {
							$parentthis.removeClass("open").find("a span").text("Show all...");
						} else {
							$parentthis.addClass("open").find("a span").text("Show fewer...");
						}
					}
				});
				return false;
			});
		}
	});
}

function slideListShowNone() {
	$('ul.slide').each(function() {
		if ($(this).children('li').length > 3) {
			$(this).children('li').hide();
			$(this).append('<li class="more"><a href="#"><span>Show...</span></a></li>');
			$(this).children('li.more').click(function() {
				var speed = $.browser.msie ? 0 : 200;
				if ($.browser.msie) {
					$(this).addClass("loading").find("a span").text("Loading...");
				}
				$parentthis = $(this);
				$(this).siblings("li:not(this)").delay(0).toggle(speed,function() {
					// IE7 ClearType fix
					if($.browser.msie) {$(this).get(0).style.removeAttribute('filter');}
					if ($(this).index() == $parentthis.siblings("li").length-1) {
						// intentionally duplicated, not sure why the redraw doesn't work without
						if(isdefined("curvyCorners")){
							curvyCorners.redraw();
							curvyCorners.redraw();
						}
						if ($parentthis.hasClass("open")) {
							$parentthis.removeClass("open").find("a span").text("Show...");
						} else {
							$parentthis.addClass("open").find("a span").text("Hide...");
						}
					}
				});
				return false;
			});
		}
	});
}

function schoolsSlideListShowNone() {
	$('ul.schoolsslide').each(function() {
		if ($(this).children('li').length > 3) {
			$(this).children('li').hide();
			$(this).append('<li class="more"><a href="#"><span>Show Schools and Research Institutes...</span></a></li>');
			$(this).children('li.more').click(function() {
				var speed = $.browser.msie ? 0 : 200;
				if ($.browser.msie) {
					$(this).addClass("loading").find("a span").text("Loading...");
				}
				$parentthis = $(this);
				$(this).siblings("li:not(this)").delay(0).toggle(speed,function() {
					// IE7 ClearType fix
					if($.browser.msie) {$(this).get(0).style.removeAttribute('filter');}
					if ($(this).index() == $parentthis.siblings("li").length-1) {
						// intentionally duplicated, not sure why the redraw doesn't work without
						if(isdefined("curvyCorners")){
							curvyCorners.redraw();
							curvyCorners.redraw();
						}
						if ($parentthis.hasClass("open")) {
							$parentthis.removeClass("open").find("a span").text("Show Schools and Research Institutes...");
						} else {
							$parentthis.addClass("open").find("a span").text("Hide...");
						}
					}
				});
				return false;
			});
		}
	});
}

function tabsSetup() {
	$("#tabs").tabs().bind('tabsshow', function(event, ui) {
		if(isdefined("curvyCorners")){
			curvyCorners.redraw();
			if(isdefined("flashfile")){swfobject.embedSWF(flashfile, flashid, flashwidth, flashheight, flashversion, flashinstall, flashvars, params);}
		}
	});	
}

function imageGallery() {
	$("#gallery img").each(function() {
	   $(this).cjObjectScaler({
		 method: "fit",
		 fade: 800
	   });
	});
}


// Setup video
function videosmall(){
    $(".smallplayer").each(function(){
	var video = $(".smallplayer").attr("href");
	var wrapped = video.replace(".mp4", "");
	var emb = $('<script type="text/javascript" src="http://www.gla.ac.uk/0t4/generic/video/jwplayer.js"></script><div style="margin: 0pt 0pt 20px 20px; float: right; position: relative;"><div id="'+wrapped+'"><a href="http://get.adobe.com/flashplayer/">Get the latest flash player to view this media.</a><\/div><script type="text/javascript">jwplayer("'+wrapped+'").setup({file: "'+video+'",plugins: "fbit-1,tweetit-1, gapro-2","gapro.accountid":"UA-9258834-1",height: 180,width: 320, image: "http://www.gla.ac.uk/0t4/generic/images/videothumb.gif", skin: "http://www.gla.ac.uk/0t4/generic/video/skin/bekle.zip", "controlbar.idlehide": "true", modes: [{ type: "flash", src: "http://www.gla.ac.uk/0t4/generic/video/player.swf" },{ type: "html5" },{ type: "download" }]});<\/script><\/div>');
	$(this).replaceWith(emb);
	});
}

function videolarge(){
    $(".largeplayer").each(function(){
	var video = $(".largeplayer").attr("href");
	var wrapped = video.replace(".mp4", "");
		var emb = $('<script type="text/javascript" src="http://www.gla.ac.uk/0t4/generic/video/jwplayer.js"></script><div id="'+wrapped+'"><a href="http://get.adobe.com/flashplayer/">Get the latest flash player to view this media.</a><\/div><script type="text/javascript">jwplayer("'+wrapped+'").setup({file: "'+video+'",plugins: "fbit-1,tweetit-1, gapro-2","gapro.accountid":"UA-9258834-1",height: 270,width: 480,"controlbar.idlehide": "true", image: "http://www.gla.ac.uk/0t4/generic/images/videothumb.gif", skin: "http://www.gla.ac.uk/0t4/generic/video/skin/bekle.zip",modes: [{ type: "flash", src: "http://www.gla.ac.uk/0t4/generic/video/player.swf" },{ type: "html5" },{ type: "download" }]});<\/script><br  style="clear:both;" />');
	$(this).replaceWith(emb);
	});
}




function videolightbox(){
    $(".lightbox").each(function(){
	var video = $(".lightbox").attr("href");
	var wrap = video.replace("/media/", "");
	var wrapped = wrap.replace(".mp4", "");
	$(this).replaceWith('<a href="#'+wrapped+'" rel="prettyPhoto" title="videotest">'+wrapped+'</a><div id="'+wrapped+'" class="hide"><p><embed src="http://www.gla.ac.uk/t4/generic/flvplayer/player.swf" width="640" height="480" allowscriptaccess="always" allowfullscreen="true" id="'+wrapped+'" name="'+wrapped+'" flashvars="file='+video+'&fullscreen=true&backcolor=111111&frontcolor=eeeeee&stretching=fill&skin=http://www.gla.ac.uk/t4/generic/flvplayer/kleur.swf" /></p></div>');
	});
}

function mp3(){
    $(".mp3").each(function(){
	var video = $(".mp3").attr("href");
	var wrapped = video.replace(".mp3", "");
	var emb = $('<embed flashvars="file='+video+'&skin=http://www.gla.ac.uk/0t4/generic/video/kleur.swf" allowfullscreen="true" allowscripaccess="always" id="splayer" name="splayer" src="http://www.gla.ac.uk/0t4/generic/video/player.swf" width="300" height="30" image="http://www.gla.ac.uk/0t4/generic/images/videothumb.gif" />');
	$(this).replaceWith(emb);
	});
}

function isdefined(variable){
    return (typeof(window[variable]) == "undefined")?  false: true;
}

$(window).load(function(){
	imageCaptions();
});

$(document).ready(function(){
	$("body").addClass("has_js").addClass($.client.os.toLowerCase());
	$("li:first-child, #pageContent #mainpage .maincontent .newsstory:first, #pageContent .links h1:first").addClass("first");
	$("li:last-child, #pageContent #mainpage .maincontent .newsstory:last").addClass("last");
	$("#jquerylist").listnav({
        includeNums: false
    });
    $(".jquerylist").listnav({
        includeNums: false
    });
    
    if ($("#coursenav").children('li').length == 1) {
        $("#coursenav").hide();
    }
	tabsSetup();
	courseFinderHover();
	researchFinderHover();
	jumpLinkHover();
	rotatingFeature();
	blockquotes();
	alternateRows();
	downloadIcons();
	externalLinks();
	clearOnEnter();
	slideListShowNone();
    schoolsSlideListShowNone();
	imageGallery();
	imageCaptionsLinks();
	videosmall();
	videolarge();
	videolightbox();
	mp3();
	$("a[rel^='prettyPhoto']").prettyPhoto();
    $("#accordion").accordion({
            collapsible: true,
			autoHeight: false,
			navigation: true
    });
    
    $("#refinebysubjectform #refinebysubjectselect").change(function() {
        $("#refinebysubjectform").submit();
    });
    
    $(".refinebysubjectselect").change(function() {
        $(this).parentsUntil("form").parent().submit();
    });
    
    $(".relatedprogrammesselect").change(function() {
        $(this).parentsUntil("form").parent().submit();
    });
    
    /* for shortbread */
    var len =  $('#breadcrumbs ul li').length;
    if(len > 3) {
        var item = $('#breadcrumbs ul li:nth-child(3)');
        if(item.text() == 'Taught degree programmes A-Z') {
            item.hide();
        }
    }
    
    if(len > 4) {
        $('#breadcrumbs ul li').each(function(n){
            if(n >= 3 && n!=len-1){
                if(n==3) {
                    $(this).after('<li id="shortbread"><a href="">...</a></li>')
                }
                $(this).hide();
            }
        });
    }
    
    $("#shortbread").click(function () {
        $('#breadcrumbs ul li').show();
        $(this).hide();
        return false;
    });     
});
