// T4: Filter Names removing text before 'School Office'
function filterNames(text){
	var words = text.split(", ");
	var newWords = Array();
	var findregex='(.*?)(School)( )(Office)';
	
	for (var i = 0; i < words.length; i++) {
		var p = new RegExp(findregex,["i"]);
		var m = p.exec(words[i]);
		if (m != null) { newWords.push("School Office");} 
		else { newWords.push(words[i]);}
	}
	return newWords.join(", ");;
}


// file encoding must be UTF-8!
function getTextExtractor()
{
  return (function() {
    var patternLetters = /[öäüÖÄÜáàâéèêíúùûóòôÁÀÂÍÉÈÊÚÙÛÓÒÔß]/g;
    var patternDateDmy = /^(?:\D+)?(\d{1,2})\.(\d{1,2})\.(\d{2,4})$/;
    var lookupLetters = {
      "ä": "a", "ö": "o", "ü": "u",
      "Ä": "A", "Ö": "O", "Ü": "U",
      "Í": "I", "í": "i", 
      "á": "a", "à": "a", "â": "a",
      "é": "e", "è": "e", "ê": "e",
      "ú": "u", "ù": "u", "û": "u",
      "ó": "o", "ò": "o", "ô": "o",
      "Á": "A", "À": "A", "Â": "A",
      "É": "E", "È": "E", "Ê": "E",
      "Ú": "U", "Ù": "U", "Û": "U",
      "Ó": "O", "Ò": "O", "Ô": "O",
      "ß": "s"
    };
    var letterTranslator = function(match) { 
      return lookupLetters[match] || match;
    }

    return function(node) {
      var text = $.trim($(node).text());
      var date = text.match(patternDateDmy);
      if (date)
        return [date[3], date[2], date[1]].join("-");
      else
        return text.replace(patternLetters, letterTranslator);
    }
  })();
}


$(document).ready(function(){
	
	// Run though all areas that require to be filtered and run it
	$(".filterSubjArea").each(function() {
		$thistext = filterNames($(this).text());
		$(this).text($thistext);
	});
	
	
	/*
	==============================================
		Quick Finder
	==============================================
	*/

   $("#quick-finder-link").click(function(){
         if ($("#quick-finder").is(':hidden')) 
         	{ $("#quick-finder").slideDown();}
         	else {
			  	$("#quick-finder").fadeOut();
		 }
		 return false;
	});
	$("#quick-finder-close").click(function () { 
      $("#quick-finder").slideUp(); 
    });	
	$('#quick-finder').click(function(e) {
	 	e.stopPropagation();
	});
	$(document).click(function() {
	 	$('#quick-finder').fadeOut();
	});

 	/*
    =========================================================
     ON CMS.NUIGALWAY.IE ONLY 
     change all links to www.nuigalway.ie to cms.nuigalway.ie    
    =========================================================
    */
     if (document.location.href.indexOf('cms.nuigalway.ie') > -1) {
       var allLinks = document.getElementsByTagName('a');
       for (i=0; i < allLinks.length; i++) {
         var linkTarget = allLinks[i].href;
         allLinks[i].href = linkTarget.replace(/www.nuigalway.ie/, "cms.nuigalway.ie");
       }
     }
 
    /*

	=================================================
	    Enable local onLoad() functions in pages
	=================================================
	*/
        //If a function called onLoad() exists in the current page, run it automatically
	try {
	//if (window.onLoad())
		onLoad();
	} catch (exception) {
	  //do nothing
	} 	

   /*	
	=================================================
		Courses breadcrumb fixer
	=================================================
	*/


$("#colbreadcrumb li").each(function(n) {

var me = $(this).text();

if(me=="PhD & Masters"){
  $("#colbreadcrumb li:eq("+n+")").hide();
}
else
if(me=="Structured PhD"){
  $("#colbreadcrumb li:eq("+n+")").hide();
}
else
if(me=="College of Arts Social Sciences and Celtic Stud"){
  $("#colbreadcrumb li:eq("+n+")").hide();
}
else
if(me=="College of Arts, Social Sciences,An tAcadamh"){
  $("#colbreadcrumb li:eq("+n+")").hide();
}
else
if(me=="College of Business, Public Policy, and Law"){
  $("#colbreadcrumb li:eq("+n+")").hide();
}
else
if(me=="College of Medicine, Nursing, and Health Sciences"){
  $("#colbreadcrumb li:eq("+n+")").hide();
}
else
if(me=="College of Engineering and Informatics"){
  $("#colbreadcrumb li:eq("+n+")").hide();
}
else
if(me=="College of Science"){
  $("#colbreadcrumb li:eq("+n+")").hide();
}


});


   /*	
	=================================================
		Courses grid system
	=================================================
	*/
	function equalHeight(group) {
		var tallest = 0;
		group.each(function() {
			var thisHeight = $(this).height();
			if(thisHeight > tallest) {
				tallest = thisHeight;
			}
		});
		group.height(tallest);
	}
	equalHeight($(".tallestcell"));
	equalHeight($(".footercol"));

	//hide empty grid sections
	$('div.split2:empty').hide();

   /*	
	=================================================
		News and events introduction text
	=================================================
	*/


     // $(".Intro-text").css("color","white");

     // $(".Intro-text p:first").css("color","black");

     // $(".Intro-text p:first").next().css("color","black");

     // $(".Intro-text br").nextAll().remove();  // this affects brs in the first paragraph too

   /*	
	=================================================
		Home Page Ticker
	=================================================
	*/	
	if ($("#marquee").length) {
	
    	$('#marquee').cycle (
				{
					fx: 'fade'
				} 
				);

	 	};
		
	if ($("#home-page-feature-pager").length) {
	   	$('#home-page-feature-pager div:first').css("display","block");
			$('#home-page-feature-pager').cycle (
				{
					fx: 'fade',
					timeout: 8000,
					pause: 20,
					pager: '#pager-nav',slideExpr: 'img',
					pauseOnPagerHover: true
				});
	 	};

   /*	
	=================================================
		Hover style on inner pages
	=================================================
	*/	
	 $('a.nav-landing-page').hover(
	  	function() { $("a.home-icon").css("background-color","#377E8B"); }, 
	  	function() { $("a.home-icon").css("background-color","#630560"); }
     );	     

	/*
	
	=================================================
		Breadcrumb  fixer
	=================================================
	*/	
	$(function() {
	  $(".nav-landing-page").each(function() {
	
	    $(this).parent().addClass($(this).text().length > 12 ? "long-link" : "");
	
	  });
	});
	
	/*
	=================================================
		Fees admin page edit in new window
	=================================================
	*/

	$(".editmodify a").attr('target','_blank');



  

	/*
	===============================================================================
		Tooltips
		See: http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
		for demos and documentation
	===============================================================================
		This option will give a fully expandable tooltip with no image background
	===============================================================================
	*/
	if ($("span.plain-tooltip").length) {
		$('span.plain-tooltip').tooltip(
			{
			showBody: " - "
			});
	}
	/*
	===========================================================================
		This option will give a fancier tooltip with an image bubble
	===========================================================================
	*/
	if ($("span.tooltip").length) {
		$("span.tooltip").tooltip({
			track: true,
			delay: 0,
			showURL: false,
			fixPNG: true,
			showBody: " - ",
			extraClass: "pretty fancy",
			top: -15,
			left: 5
		});
	}

	/*
	=================================================
		Image Carousel
	=================================================
	*/	

	if ($("#mycarousel").length) {
	
    		$('#mycarousel').jcarousel({
        		scroll: 7
    		});
	 	};
	
    /*
    =================================================
            Email Click
    =================================================
    */
    if ($("a#email-icon").length) {
            // Construct the anchor link on the email button to include the
            // current URL and the h1 tag.
            var NewUrl="/email-a-friend.php?curpage=" + (jQuery.url.attr("source"));
            var NewUrl= NewUrl + "&title=" + document.title;
            var NewUrl= NewUrl + "&header=" + $("h1").html();

            $('a#email-icon').attr("href", NewUrl);

            };

	/*
	=================================================
		Table Row striping!
	=================================================
	*/

  	$('table.stripe tr:odd td').addClass('odd');
  	$('table.stripe tr:even td').addClass('even');

  
	/*
	=================================================
		Light box gallery
		See details & options at http://fancybox.net/
	=================================================
	*/
	
	if ($("a.gallery").length) {
		$("a.gallery").fancybox({ 
				transitionIn: "elastic", 
				transitionOut: "elastic"
    });
	};

	$(".fancyYoutube").click(function() {
		$.fancybox({
			'transitionIn'	: "elastic",
			'transitionOut'	: "elastic",
			'width'		: 560,
			'height'		: 340,
			'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			'type'			: 'swf',
			'swf'			: {
			  'wmode'		: 'transparent',
				'allowfullscreen'	: 'true'
			}
		});
		return false;
	});
	
	/*
	==============================================
		Search button hover
	==============================================
	*/
	 $('#search-button').hover(
	  	function() { $(this).attr("src","/media/nuigalwayie/styleassets/images/search-button-rollover.png"); }, 
		function() { $(this).attr("src","/media/nuigalwayie/styleassets/images/search-button.png");
     });

	 $('#quick-finder-buttons a.students').hover(
	  	function() { $(this).attr("src","/media/nuigalwayie/styleassets/images/students-rollover.png"); }, 
		function() { $(this).attr("src","/media/nuigalwayie/styleassets/images/students.png");
     });


		if ($('.rollover').length) {
			setupRollovers();
		}
		
		function setupRollovers() {
			// preload any rollover images
			
			$.each ($('input.rollover, img.rollover'), function(i, n) {
				i_src = $(n).attr('src');
				r_src = i_src.substring(0,(i_src.length -4)) + '-rollover' + i_src.substring((i_src.length -4));
				preload_img = new Image();
				preload_img.src = r_src;
			});
	
			// observe the images/inputs
			$('input.rollover, img.rollover').bind('mouseover', function(){
				i_src = $(this).attr('src');
				i_src = i_src.replace(/-rollover/, '');

				r_src = i_src.substring(0,(i_src.length -4)) + '-rollover' + i_src.substring((i_src.length -4));
				$(this).attr({src: r_src});
			});
	
			$('input.rollover, img.rollover').bind('mouseout', function(){
				i_src = $(this).attr('src');
				r_src = i_src.replace(/-rollover/, '');
				$(this).attr({src: r_src});
			});
		}

	/*
	==============================================
		hide footer heading
	==============================================
	*/

	$('#footer-schools li:first').hide();


	/*
	==============================================
		format footer last link
	==============================================
	*/
	$('#footerlist li:last').addClass('last');

	/*
	==============================================
		format Big footer links in schools
	==============================================
	*/
	$("#Big-footer-links:not(li) > ul > li").addClass("schools-lev-one");
	$("#footer div:nth-child(5) #Big-footer-links").css("background","none");
	$("#footer div:nth-child(10) #Big-footer-links").css("background","none");

	/*
	==============================================
		eform date submission
	==============================================
	*/
	var now = new Date();
	
	$("#DateFormCompleted").attr("value",now);

	/*
	==============================================
		Search box text replacement
	==============================================
	*/


	function textReplacement(input){
		  var originalvalue = input.val(); 
		  input.focus( function(){ 
			  if( $.trim(input.val()) == originalvalue ){ input.val(''); } 
		  });
	   
		  input.blur( function(){
			  if( $.trim(input.val()) == '' ){ input.val(originalvalue); }
		  });
		  }
 
	textReplacement($('#keywords'));	

	/*
	==============================================
		Tabbed pages
	==============================================
	*/


	if ($('div.panes div.tab-content').length) {
          try {
		$("ul.tabbed-content").tabs("div.panes > div",
		{	
		
			onClick: function(number) { 
        	this.getCurrentTab().parent().removeClass("selected");
        	$("ul.tabbed-content li:eq("+number+")").addClass("selected");
        
    	} 
		}
	
		);
          } catch (exception) {
            //do nothing - it is a tab effect using multiple pages
          }
	}





	/*

	==============================================
		Tool bar
	==============================================
	*/	
	$("li#increaseFont").click(function(){
 
  		if($.browser.name == 'msie'){
     		var currentFontSize = $('body').css('font-size');
     		/* allow for jQuery MSIE bug on font size */
     		if (currentFontSize == '6px') { var currentFontSize = '10px'}
    		var currentFontSizeNum = parseFloat(currentFontSize, 10);
    		var newFontSize = currentFontSizeNum*1.2; 
    		$('body').css('font-size', newFontSize);
    		return false;
  		}else{
    		var currentFontSize = $('body').css('font-size');
    		var currentFontSizeNum = parseFloat(currentFontSize, 10);
    		var newFontSize = currentFontSizeNum*1.2;
    		$('body').css('font-size', newFontSize);
    		return false;
  		}

    return false;
  });
  
  // Decrease Font Size
  $("li#decreaseFont").click(function(){
    var currentFontSize = $('body').css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum*0.9;
    $('body').css('font-size', newFontSize);
    return false;
  });

		/*
		================================================
			Caption Sliding (Partially Hidden to Visible)
		================================================
		*/	
		if ($(".long-caption-link .cover").length) {
			$('.boxgrid.caption').hover(function(){
				$(".cover", this).stop().animate({top:'110px'},{queue:false,duration:160});
			}, function() {
				$(".cover", this).stop().animate({top:'125px'},{queue:false,duration:160});
			});
		}
		else
		{
			$('.boxgrid.caption').hover(function(){
				$(".cover", this).stop().animate({top:'115px'},{queue:false,duration:160});
			}, function() {
				$(".cover", this).stop().animate({top:'145px'},{queue:false,duration:160});
			});		
		}


	  
	/*
	====================================
	  Style switcher
	====================================
	*/
	$('link[title=Large font]').attr("diabled","");
	 $('.styleswitch').click(function()
		{
		relattrib = this.getAttribute("rel");
		switchStylestyle(this.getAttribute("rel"));
		return false;
		});
		
		var style = readCookie('style');
		if(style) {
		switchStylestyle(style);
		}
		function switchStylestyle(styleName)
		{
	
			$('link[@rel=*style][title]').each(function(i) 
			{
				this.disabled = true;
				if(this.getAttribute('title') == styleName) 
					this.disabled = false;
			});
			largeStyle = styleName;
			if (largeStyle == "Large font" || largeStyle == "High contrast")
				{
					topHeight = '90px';
					if ($(".long-caption-link .cover").length) {bottomHeight = '125px';} else {bottomHeight = '145px';}
				}
				else 
				{	
					topHeight = '115px'; 
					bottomHeight = '145px';
					if ($(".long-caption-link .cover").length) {bottomHeight = '125px';}
				}; 
				$('.boxgrid.caption').hover(function(){
					$(".cover", this).stop().animate({top:topHeight},{queue:false,duration:160});
				}, function() {
					$(".cover", this).stop().animate({top:bottomHeight},{queue:false,duration:160});
				});		
			
			
			
			createCookie('style',styleName,365);
		}
	
		function createCookie(name,value,days)
		{
			if(days)
			{
				var date = new Date();
				date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
				var expires = "; expires=" + date.toGMTString();
			}
			else 
				var expires = "";
			document.cookie = name + "=" + value + expires + "; path=/";
		}
	
		function readCookie(name)
		{
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var index = 0; index < ca.length; index++)
			{
				var c = ca[index];
				while(c.charAt(0 )== ' ') 
					c = c.substring(1,c.length);
				if(c.indexOf(nameEQ) == 0) 
					return c.substring(nameEQ.length,c.length);
			}
			return null;
		}
	
		function eraseCookie(name)
		{
			createCookie(name,"",-1);
		}



		



		
});
