//set up the login and comment boxes
$(document).ready(function(){
$('#logOpts').hide();
  $('#login a').toggle(function() {
    $(this)
      .addClass('active')
	$('#logOpts')
      .animate({'height':'show'}, {
        duration:'slow',
        easing: 'linear'
      });
	$('#login').css('background','#DFE9F3');
	$('#login').css('background-image','none');
  }, function() {
    $(this)
      .removeClass('active')
	$('#logOpts').slideUp();
	$('#login').css('background-color','#005188'); 
	$('#login').css('background-image','url(../graphics/toptail.gif');
	$('#login').css('background-repeat','no-repeat');
	$('#login').css('background-position','right bottom');
  });
  
$('#commentBox').hide();
  $('#commentHeaderText a').toggle(function() {
    $(this)
      .addClass('active')
	$('#commentBox')
      .animate({'height':'show'}, {
        duration:'slow',
        easing: 'linear'
      });
  }, function() {
    $(this)
      .removeClass('active')
	$('#commentBox').slideUp();
  });
  
  $('a.tips').cluetip({
      splitTitle: '|',               
    showTitle: false,
		clickThrough: true,
		width: 120
  });
  
  $('area.tips').cluetip({
      splitTitle: '|',               
    showTitle: false,
		clickThrough: true,
		width: 120
  });
});

$(function() {
	$("#tabs").tabs({ fx: { opacity: 'toggle' } });
});

// 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() < 5000 ? 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="next">&gt;</a><a href="#" class="previous">&lt;</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","");
		});
	}
}

// Setup the rotating feature
function rotatingFeature2() {
	narrow = $("#pageContent .rotatingFeature2").width() < 5000 ? true : false;
	/*$("#pageContent .rotatingFeature2 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 .rotatingFeature2 ul li h3").append('<div class="arrow"></div>');
	if (!narrow) {$("#pageContent .rotatingFeature2 ul li h3 a").append('<div class="corner"></div>');}
	$("#pageContent .rotatingFeature2").append('<div class="features"></div>');
	$("#pageContent .rotatingFeature2 ul li .feature").appendTo("#pageContent .rotatingFeature2 .features");
	$("#pageContent .rotatingFeature2 .feature").hide();
	$("#pageContent .rotatingFeature2 .feature:eq(0)").addClass("active").show();
	if (narrow) {
		$("#pageContent .rotatingFeature2 ul li h3 a").append('<div class="cornerLeft"></div><div class="cornerRight"></div>');
		$("#pageContent .rotatingFeature2 ul li").hide();
		$("#pageContent .rotatingFeature2 ul li:eq(0)").show();
		$("#pageContent .rotatingFeature2").append('<div class="nav"><a href="#" class="previous">&lt;</a> <a href="#" class="next">&gt;</a></div>');
		$("#pageContent .rotatingFeature2 .nav a").click(function() {
		
			if(isactive==true)
				isactive = false;
			var $active = $("#pageContent .rotatingFeature2 ul li.active");
			if($(this).hasClass("previous")) {
				var $next = $active.prev().length ? $active.prev() : $("#pageContent .rotatingFeature2 ul li:last");
			} else {
				var $next = $active.next().length ? $active.next() : $("#pageContent .rotatingFeature2 ul li:first");
			}
			rotatingFeature2Switch($next,narrow);
			return false;
		});
		$("#pageContent .rotatingFeature2 .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( 'rotatingFeature2Switch(null,narrow)', 10000 );
		  }
		);		
	}
	$("#pageContent .rotatingFeature2 ul li:eq(0)").addClass("active");

	// set cycle interval
	var playSlideshow =  setInterval( 'rotatingFeature2Switch(null,narrow)', 10000 );
	$("#pageContent .rotatingFeature2 ul li h3 a").hover(
		function() {
			if(!narrow) {
				rotatingFeature2Switch($(this).parents("li"));
				clearInterval(playSlideshow);
			}
		},
		function() {
			if(!narrow) {playSlideshow =  setInterval( 'rotatingFeature2Switch(null,narrow)', 10000 );}
		}
	);
	$("#pageContent .rotatingFeature2 .feature").hover(
		function() {
			$(this).addClass("hover");
			clearInterval(playSlideshow);
		},
		function() {
			if(isactive==false) {
			$(this).removeClass("hover");
			playSlideshow =  setInterval( 'rotatingFeature2Switch(null,narrow)', 10000 );
			}
		}
	);
	
	var isactive = false;
	
	$("#pageContent .rotatingFeature2 .feature").click(function() {
		if(isactive==true) {
			isactive = false;
		}
		else {
			clearInterval(playSlideshow);
			isactive = true;
			
			//play the relevant video clip			
			var pid = $(this).find('p').attr('id');
			
		var s1 = new SWFObject("http://www.gla.ac.uk/t4/generic/flvplayer/player.swf","ply","640","392","9","#FFFFFF");
		
		var vidclip = '';
		
		if(pid=='gaw1')
			vidclip = 'cairncross640.mp4'
		else if(pid=='gaw2')
			vidclip = 'dictol640.mp4'
		else if(pid=='gaw3')
			vidclip = 'donald640.mp4'
		else if(pid=='gaw4')
			vidclip = 'morgan640.mp4'
		else
			vidclip = 'robertson640.mp4'
 
		s1.addParam("allowfullscreen","true");
		s1.addParam("allowscriptaccess","always");
		s1.addParam("swliveconnect","true");
		s1.addParam("flashvars","file=http://itunesu.gla.ac.uk/podcasts/featuredcontent/glasgowfirsts/"+vidclip+"&autostart=true&fullscreen=true&skin=http://www.gla.ac.uk/t4/generic/flvplayer/kleur.swf");
		s1.write(pid);
			
		}
	});
	
	
}

function rotatingFeature2Switch(obj, narrow) {
	
	//reset all videos to their images
	$('#gaw1').html('<img src="/graphics/top-5-video-l-robertson-d.jpg" alt="" title="" align="center" />');
	$('#gaw2').html('<img src="/graphics/top-5-video-l-dictol.jpg" alt="" title="" align="center" />');
	$('#gaw3').html('<img src="/graphics/top-5-video-l-donald.jpg" alt="" title="" align="center" />');
	$('#gaw4').html('<img src="/graphics/top-5-video-l-morgan.jpg" alt="" title="" align="center" />');
	$('#gaw5').html('<img src="/graphics/top-5-video-l-robertson-m.jpg" alt="" title="" align="center" />');
	
	// jump to end of animation if another is initiated
	if ($('#pageContent .rotatingFeature2 .feature').is(':animated')) {
		$('#pageContent .rotatingFeature2 .feature.last-active, #pageContent .rotatingFeature2 ul li.last-active').removeClass('last-active').css("position","").css({opacity: null}).stop().hide();
		$('#pageContent .rotatingFeature2 .feature.active, #pageContent .rotatingFeature2 ul li.active').css({opacity: null}).stop().show();
	}
	
	var $active = $('#pageContent .rotatingFeature2 ul li.active');

	// set next section in cycle, at end of list reset to first item
	var $next = $active.next().length ? $active.next()
		: $('#pageContent .rotatingFeature2 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 .rotatingFeature2 .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 .rotatingFeature2 .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)").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>");
		};
	});
}
*/

// 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"))) {
			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;
			});
		}
	});
}

// Clear value on focus
function clearOnEnter() {
	// Store the default value for each box
	$('.clearOnEnter, #siteSearch form #ssKeywords').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 wrap = video.replace("/media/", "");
	var wrapped = wrap.replace(".mp4", "");
	$(this).replaceWith('<div style="margin: 0pt 0pt 20px 20px; float: right; position: relative;"><embed flashvars="file='+video+'&autostart=false&skin=http://www.gla.ac.uk/t4/generic/flvplayer/kleur.swf" allowfullscreen="true" allowscripaccess="always" id="'+wrapped+'" name="'+wrapped+'" src="http://www.gla.ac.uk/t4/generic/flvplayer/player.swf" width="280" height="185" /></div>');
	});
}

function videolarge(){
    $(".largeplayer").each(function(){
	var video = $(".largeplayer").attr("href");
	var wrap = video.replace("/media/", "");
	var wrapped = wrap.replace(".mp4", "");
	$(this).replaceWith('<embed flashvars="file='+video+'&autostart=false&skin=http://www.gla.ac.uk/t4/generic/flvplayer/kleur.swf" allowfullscreen="true" allowscripaccess="always" id="'+wrapped+'" name="'+wrapped+'" src="http://www.gla.ac.uk/t4/generic/flvplayer/player.swf" width="500" height="300" />');
	});
}

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
    });
	$("#jquerylist2").listnav({
        includeNums: false
    });
    $(".jquerylist2").listnav({
        includeNums: false
    });
    
    if ($("#coursenav").children('li').length == 1) {
        $("#coursenav").hide();
    }
	tabsSetup();
	courseFinderHover();
	researchFinderHover();
	jumpLinkHover();
	rotatingFeature();
	rotatingFeature2();
	blockquotes();
	alternateRows();
	downloadIcons();
	externalLinks();
	clearOnEnter();
	slideListShowNone();
    schoolsSlideListShowNone();
	imageGallery();
	videosmall();
	videolarge();
	$("a[rel^='prettyPhoto']").prettyPhoto();
    $("#accordion").accordion({
        collapsible: true
    });
	
	$(".testclick").click(function() {
		alert("clicked!");
	});
	
	$("#ply").click(function() {
		alert("player clicked!");
	});
});
