$(document).ready(function(){
	$('body').addClass('has_js').addClass($.client.os.toLowerCase()).addClass($.client.browser.toLowerCase());
	chooseEssex();
	carousel();
	ctaNav();
	//siteSearch();
	socialMedia();
	tabsSetup();
	alternateRows();
	//vtip();
	imageCaptions();
	ctaA();
	faqs();
	downloadIcons();
	prettyPhotos();
	checkWinWidth();
	includesIntent();
	$(window).smartResize(function(){
		checkWinWidth();
	});
});


// Gallery Functions -----------------------------------------------------------------------------------------


function prettyPhotos(){
				$("area[rel^='prettyPhoto']").prettyPhoto();
				
				$("#gallery:first a[rel^='prettyPhoto']").prettyPhoto({animation_speed:'normal',theme:'light_square',slideshow:3000, autoplay_slideshow: false});
				$("#gallery:gt(0) a[rel^='prettyPhoto']").prettyPhoto({animation_speed:'fast',slideshow:10000, hideflash: true});
}



// Carousel Functions -----------------------------------------------------------------------------------------

function chooseEssex() {
	$('#pageContent .feature#chooseEssex:nth-child(1)').addClass('nth-child1');
	$('#pageContent .feature#chooseEssex:nth-child(2)').addClass('nth-child2');
	$('#pageContent .feature#chooseEssex:nth-child(3)').addClass('nth-child3');
	$('#pageContent .feature#chooseEssex ol li').each(function() {
		$(this).prepend('<span class="num">' + ($(this).index()+1) + '</span>');
	});
}

function carousel() {
	
	var navSel;
	var slideCur;
	var slideMax = $('#pageContent #carousel ul li').length;
	
	$('#pageContent #carousel .nav ul a').click(function() {
		if ($('#pageContent #carousel > ul:animated').length == 0) {
			navSel = $(this).parent().index() + 1;
			slideCur = $('#pageContent #carousel > ul > li:eq(0)').data('id');
			if (navSel < slideCur) {
				itt = slideCur - navSel;
				carouselSlide('stop');
				carouselSlideSwitch(itt, 'rwd', 100);
			} else {
				itt = navSel - slideCur;
				carouselSlide('stop');
				carouselSlideSwitch(itt, 'fwd', 100);
			}
		}
		return false;
	});	
	
	// setup slides
	$('#pageContent #carousel ul').clone().prependTo('#pageContent #carousel');
	$('#pageContent #carousel > ul > li').each(function() {
		$(this).data('id',($(this).index()+1));
	});
	
	$('#pageContent #carousel .nav ul li:eq(0)').addClass('active');
	
	// intro animation
	$('#pageContent #carousel > ul > li:eq(0) .caption').fadeIn(1500);
	
	// start cycle if more than one slide
	if (slideMax > 1) {
		carouselSlide('play');
		
		$('#pageContent #carousel').prepend('<div id="pause"></div>');
		
		// pause cycle on hover
		$('#pageContent #carousel #pause').click(function() {
			if ($(this).hasClass('paused')) {
				carouselSlide('play');
				$(this).removeClass('paused');
			} else {
				carouselSlide('stop');
				$(this).addClass('paused');
			}
		});
	}
}

function carouselSlide(action) {
	if (action == 'play') {
		play =  setInterval( 'carouselSlideSwitch(1, "fwd", 1000)', 10000 );
	} else if (action == 'stop') {
		clearInterval(play);
	}
}

function carouselSlideSwitch(itt, dir, speed) {
	$('#pageContent #carousel > ul > li:eq(0) .caption').fadeOut('fast');
	var easing = (speed < 400) ? 'linear' : 'swing';
	if (dir == 'rwd') {
		$('#pageContent #carousel > ul > li').last().prependTo($('#pageContent #carousel > ul'));
		$('#pageContent #carousel > ul').css('left',-$('#pageContent #carousel > ul > li:eq(0)').width());
		$('#pageContent #carousel > ul').animate({left: 0}, speed, easing, function() {
			navactive = $('#pageContent #carousel .nav ul li.active');
			navactive.removeClass('active');
			if(navactive.prev().length == 0) {
				navactive.siblings().last().addClass('active');
			} else {
				navactive.prev().addClass('active');
			}
			if (itt > 1) {
				itt = itt - 1;
				carouselSlideSwitch(itt, dir, speed);
			} else {
				if (speed < 1000) {carouselSlide('play');}
				$(this).find('li:eq(0) .caption').fadeIn(1500);
			}
		});
	} else  {
		$('#pageContent #carousel > ul').animate({left: -$('#pageContent #carousel > ul > li:eq(0)').width()}, speed, easing, function() {
			$(this).children('li').first().appendTo($(this));
			$(this).css('left',0);
			
			navactive = $('#pageContent #carousel .nav ul li.active');
			navactive.removeClass('active');
			if(navactive.next().length == 0) {
				navactive.siblings().first().addClass('active');
			} else {
				navactive.next().addClass('active');
			}
			if (itt > 1) {
				itt = itt - 1;
				carouselSlideSwitch(itt, dir, speed);
			} else {
				if (speed < 1000) {carouselSlide('play');}
				$(this).find('li:eq(0) .caption').fadeIn(1500);
			}
		});
	}
}

// Call To Action Functions -----------------------------------------------------------------------------------------


//note - important change to click function as menus are pulled in dynamically - .live('click')

function ctaNav() {
	$('#ctaNav.js-uninclude > ul > li > a').live('click',function() {
		
		
		if ($(this).parent().hasClass('active') || !$('#ctaNav ul li').hasClass('active')) {
         	$(this).parent().toggleClass('active').find('.toolbox').slideToggle('fast');
		} else {
			$('#ctaNav ul li.active').removeClass('active').find('.toolbox').hide();
						
			$(this).parent().toggleClass('active').find('.toolbox').show();
		}
		return false;
	});
}


// Search box expansion Functions -----------------------------------------------------------------------------------------


function siteSearch() {
	$('.siteSearch input').focusin(function() {
		$(this).animate({'width': '+=100px'});
	});
	$('.siteSearch input').focusout(function() {
		$(this).animate({'width': '-=100px'});
	});
}

// Social media animation functions -----------------------------------------------------------------------------------------


function socialMedia() {
	$('#pageFooter .container .col#socialMedia ul li').hover(function() {
		$(this).toggleClass('hover');	
	});
	$('#pageFooter .container .col#socialMedia ul li').click(function() {
		window.location = $(this).find('a').attr('href');	
	});
}

// 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 .article table").each(function() {
		$(this).find("tr: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) {
		$(".download ul.rsList li h4 a[href$='." + arrFileTypes[i] + "']").parent().addClass(arrFileTypes[i]);
		}
}

// Setup image captions -----------------------------------------------------------------------------

function imageCaptions(){
	$("#pageContent #mainpage .maincontent img:not(#gallery img, .rotatingFeature 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"]),a[href^=https://]:not([href*="gla.ac.uk"])').each(function() {
		// Fix for IE6 and 7 inexplicably applying the above selector for the A-Z list nav and narrow rotating feature nav
		if (!($(this).parent().hasClass("ln-letters")) && !($(this).parent().hasClass("nav"))) {
			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'));
		}
	});
}

// Tabs ------------------------------------------------------------------------------------------------------

function tabsSetup() {
	
		var currentTab = 0; // Set to a different number to start on a different tab.
		
		function openTab(clickedTab) {
		   var thisTab = $(".tabbed-box .tabs a").index(clickedTab);
		   $(".tabbed-box .tabs li a").removeClass("active");
		   $(".tabbed-box .tabs li a:eq("+thisTab+")").addClass("active");
		   $(".tabbed-box .tabbed-content").hide();
		   $(".tabbed-box .tabbed-content:eq("+thisTab+")").show();
		   currentTab = thisTab;
		}
		
		$(document).ready(function() {
		   $(".tabbed-box .tabs li a").click(function() { 
			  openTab($(this)); return false; 
		   });
		   
		   $(".tabbed-box .tabs li a:eq("+currentTab+")").click()
		});
}

//  Image Gallery --------------------------------------------------------------------------------------------


function imageGallery() {
	$("#gallery img").each(function() {
	   $(this).cjObjectScaler({
		 method: "fit",
		 fade: 800
	   });
	});
}

function isdefined(variable){
    return (typeof(window[variable]) == "undefined")?  false: true;
}

//  Mouse over tip function (subnav) --------------------------------------------------------------------------------------------

function vtip() {    
    this.xOffset = 0; // x distance from mouse
    this.yOffset = 19; // y distance from mouse       
    
    $(".vtip").unbind().hover(    
        function(e) {
            this.t = this.title;
            this.title = ''; 
            this.top = (e.pageY + yOffset); this.left = (e.pageX + xOffset);
            
            $('#sNav h3').append( '<p id="vtip"><img id="vtipArrow" />' + this.t + '</p>' );
                        
            $('p#vtip #vtipArrow').attr("src", 'scripts/images/vtip_arrow.png');
            $('p#vtip').css("top", this.top+"px").css("left", this.left+"px").fadeIn("slow");
            
        },
        function() {
            this.title = this.t;
            $("p#vtip").fadeOut("slow").remove();
        }
    ).mousemove(
        function(e) {
            this.top = (e.pageY + yOffset);
            this.left = (e.pageX + xOffset);
                         
            $("p#vtip").css("top", this.top+"px").css("left", this.left+"px");
        }
    );            
    
};


// Browser width detection and menu loader ------------------------------------------------------------------------------------
// This function is used to determine the browser width and starts the include function which brings in the Main menu and CTA menu

(function($,sr){
 
  // debouncing function from John Hann
  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  
  var debounce = function (func, threshold, execAsap) {
      var timeout;
 
      return function debounced () {
          var obj = this, args = arguments;
          function delayed () {
              if (!execAsap)
                  func.apply(obj, args);
              timeout = null; 
          };
 
          if (timeout)
              clearTimeout(timeout);
          else if (execAsap)
              func.apply(obj, args);
 
          timeout = setTimeout(delayed, threshold || 250); 
      };
  }
	// smartResize 
	jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
 
})(jQuery,'smartResize');


function checkWinWidth() {

	var winWidth = $(window).width();
	//console.log(winWidth);
	
	if (winWidth >= 960) {
		includes();
	}
	
	else {
		unIncludes();
	}
}


// Include files function ------------------------------------------------------------------------------------

function includes() {

	$(".js-include").each(function(){
		var inc=$(this);
		$.get(inc.attr("data-includes"), function(data){
			inc.replaceWith(data);
			includesIntent();
		});
	});

};

function unIncludes() {

	$(".js-uninclude").each(function(){
		var inc=$(this);
		$.get(inc.attr("data-unincludes"), function(data){
			inc.replaceWith(data);
		});
	});

};

// Include files display with hoverIntent --------------------------------------------------------------------


function includesIntent() {
	
	//console.log('Triggered');
	
	var config = {
		over: addHoverClass,
		timeout: 250,
		out: removeHoverClass
	};

	function addHoverClass() {
		$(this).addClass('hover');
		//console.log('Added Class');
	}
	
	function removeHoverClass() {
		$(this).removeClass('hover');
		//console.log('Removed Class');
	}
	
	$('#wrapper_menu .menu > li').hoverIntent(config);
		
}



// FAQs  -----------------------------------------------------------------------------------------------------

function faqs() {
	
	$(".answer.opening").hide();
	
    $('.question ').hover(function(){$(this).addClass('hover')},function(){$(this).removeClass('hover')}).click(function(){
     $(this).next().slideToggle('normal');	
	});

};




// Panel switching functions -------------------------------------------------------------------------------

// **NOTE** - THIS COULD DESPERTELY DO WITH REFINING !
// ^ Yes, yes it could.



function ctaA() {

	   $(".button.fac_undergrad").live('click',function () {
				//toggle student type
				$(".button.fac_undergrad").addClass("current");    
				$(".button.fac_postgrad").removeClass("current");    
				$(".button.fac_posttaught").removeClass("current");
                $(".fac_undergrad > input").attr("checked", "checked");
				//reset the second panel
				$(".fac .col_2, .fac .col_3").hide("fast");
				//reset the third panel
				$(".fac .col_2.option_1").show("fast");
				if ($(".fac .col_2.option_1 .keywords > input").is(":checked")) {
					$(".fac .col_3.option_1").show("fast");
				} else if ($(".fac .col_2.option_1 .subject > input").is(":checked")) {
					$(".fac .col_3.option_2").show("fast");
				} else {
					$(".fac .col_3.option_3").show("fast");	
				}
	   });
	    
	   
	   $(".button.fac_posttaught").live('click',function () {
				//toggle student type
				$(".button.fac_undergrad").removeClass("current");   
				$(".button.fac_postgrad").removeClass("current");   
				$(".button.fac_posttaught").addClass("current");
                $(".fac_posttaught > input").attr("checked", "checked");
				//reset the second panel
				$(".fac .col_2, .fac .col_3").hide("fast");
				//reset the third panel
				//$(".fac .col_2.option_3").show("fast");
				/*if ($(".fac .col_2.option_3 #details").is(":checked")) {
					$(".fac .col_3.option_4").show("fast");
				} else if ($(".fac .col_2.option_3 #department").is(":checked")) {
					$(".fac .col_3.option_5").show("fast");
				} else {
					$(".fac .col_3.option_2").show("fast");	
				}*/
	   });
	   	   
	      
	   $(".button.fac_postgrad").live('click',function () {
				//toggle student type
				$(".button.fac_undergrad").removeClass("current");  
				$(".button.fac_postgrad").addClass("current");   
				$(".button.fac_posttaught").removeClass("current");
                $(".fac_postgrad > input").attr("checked", "checked");
				//reset the second panel
				$(".fac .col_2, .fac .col_3").hide("fast");
				//reset the third panel
				$(".fac .col_2.option_2").show("fast");
				if ($(".fac .col_2.option_2 .keywords > input").is(":checked")) {
					$(".fac .col_3.option_1").show("fast");
				} else if ($(".fac .col_2.option_2 .subject > input").is(":checked")) {
					$(".fac .col_3.option_2").show("fast");
				} else {
					$(".fac .col_3.option_3").show("fast");	
				}
	   });

	   
     <!--*******************-->	     
	    
		$(".fac .col_2.option_1 .keywords > input").live('click',function () {
 			$(".fac .col_3").hide("fast");     $(".fac .col_3.option_1").show("fast");   $(".fac .col_4").show("fast");   });
		$(".fac .col_2.option_1 .subject > input").live('click',function () {
			$(".fac .col_3").hide("fast");     $(".fac .col_3.option_2").show("fast");   $(".fac .col_4").show("fast");   });
		$(".fac .col_2.option_1 .atoz > input").live('click',function () {
			$(".fac .col_3").hide("fast");     $(".fac .col_3.option_3").show("fast");    $(".fac .col_4").show("fast");   });
		
	<!--*******************-->		
		
		$(".fac .col_2.option_2 .keywords > input").live('click',function () {
			 $(".fac .col_3").hide("fast");     $(".fac .col_3.option_1").show("fast");   $(".fac .col_4").show("fast");   });
		$(".fac .col_2.option_2 .subject > input").live('click',function () {
		     $(".fac .col_3").hide("fast");     $(".fac .col_3.option_2").show("fast");   $(".fac .col_4").show("fast");   });
		$(".fac .col_2.option_2 .atoz > input").live('click',function () {
			$(".fac .col_3").hide("fast");      $(".fac .col_3.option_3").show("fast");  $(".fac .col_4").show("fast");   });
			
	<!--*******************-->	    
	   
	   $(".fac .col_2.option_3 #details").live('click',function () {
		   $(".fac .col_3").hide("fast");     $(".fac .col_3.option_4").show("fast");   $(".fac .col_4").show("fast");   }); 
	   $(".fac .col_2.option_3 #department").live('click',function () {
		   $(".fac .col_3").hide("fast");     $(".fac .col_3.option_5").show("fast");   $(".fac .col_4").show("fast");   });
	   $(".fac .col_2.option_3 #subject").live('click',function () {
		   $(".fac .col_3").hide("fast");     $(".fac .col_3.option_2").show("fast");   $(".fac .col_4").show("fast");   });

	
	<!--*******************-->	    	
		
		$(".odays .col_2.option_1 .opendaylocationunderCol > input").live('click',function () {
			 $(".odays .col_2 .option_southend").hide("fast");
			 $(".odays .col_2 .option_colchester").show("fast");
		});
		$(".odays .col_2.option_1 .opendaylocationunderSouth > input").live('click',function () {
		     $(".odays .col_2 .option_colchester").hide("fast");
			 $(".odays .col_2 .option_southend").show("fast");
		});
		/*$(".odays .col_4 button").live('click',function () {
		     $(".odays .col_1, .odays .col_2, .odays .col_3, .odays .col_4").hide("fast");
			 $(".odays .col_5, .odays .col_6, .odays .col_7, .odays .col_8").show("fast");
			 return false;
		});
		$(".odays .col_5 button").live('click',function () {
			 $(".odays .col_5, .odays .col_6, .odays .col_7, .odays .col_8").hide("fast");
		     $(".odays .col_1, .odays .col_3, .odays .col_4").show("fast");
			 if($(".odays .col_1 .button.odays_undergrad").hasClass("current")) {
			 	$(".odays .col_2.option_1").show("fast");
			 } else {
			 	$(".odays .col_2.option_2").show("fast");
			 }
			 return false;
		});*/
	
	
	<!--********************************************************************************************************************-->	   
	
	
	
	
	   $(".button.prsp_online").live('click',function () {
				//toggle student type
				$(".button.prsp_online").addClass("current");    
				$(".button.prsp_download").removeClass("current");    
				$(".button.prsp_postal").removeClass("current");
				//reset the second panel
				$(".psp .col_2, .psp .col_3, .psp .col_4").hide("fast");
				$(".psp .col_2.option_1").show("fast");
	   });
	   
	      
	   $(".button.prsp_download").live('click',function () {
				//toggle student type
				$(".button.prsp_online").removeClass("current");  
				$(".button.prsp_download").addClass("current");   
				$(".button.prsp_postal").removeClass("current");
				//reset the second panel
				$(".psp .col_2, .psp .col_3, .psp .col_4").hide("fast");
				$(".psp .col_2.option_2").show("fast");
	   });
	    
	   
	   $(".button.prsp_postal").live('click',function () {
				//toggle student type
				$(".button.prsp_online").removeClass("current");   
				$(".button.prsp_download").removeClass("current");   
				$(".button.prsp_postal").addClass("current");
				//reset the second panel
				$(".psp .col_2").hide("fast");
				$(".psp .col_2.option_3, .psp .col_3.option_3, .psp .col_4").show("fast");
	   });
	   
     <!--*******************-->	    
	   
	      
	   $(".button.odays_undergrad").live('click',function () {
				//toggle student type
				$(".button.odays_undergrad").addClass("current");   
				$(".button.odays_postgrad").removeClass("current");  
				//reset the second panel
				$(".odays .col_2").hide("fast");
				$(".odays .col_2.option_1").show("fast");
	   });
	    
	   
	   $(".button.odays_postgrad").live('click',function () {
				//toggle student type
				$(".button.odays_undergrad").removeClass("current");   
				$(".button.odays_postgrad").addClass("current");   
				//reset the second panel
				$(".odays .col_2").hide("fast");
				$(".odays .col_2.option_2").show("fast");
	   });


}

