﻿$(document).ready(function(){
	
	/*
	==============================================
		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");
       }
     }
 
    /*
    =====================================================
	Show 4th level nav containing this page
    =====================================================
    */
    function showUL(parentEl) {
      var uls = parentEl.getElementsByTagName('ul');
      if (uls) {
        for (j=0; j < uls.length; j++) {
          uls[j].style.display = "block"; 
        }
      }
    }

    var lastSlashPos = document.location.href.lastIndexOf('/');
    var thisDir = document.location.href.substr(0,lastSlashPos+1);
    var guessCnt = 0;
    var foundLink = false;
    //var sideBar = $("#primary-nav");
    var sideBar = document.getElementById('primary-nav');
    if (sideBar) {
      var sideBarLinks = sideBar.getElementsByTagName('a');
      var barePageName = document.location.href.replace(/\?.*$/, "");
      barePageName = barePageName.replace(/:8./, "");
      var greatGrandParent = null;
      for (i=0; i < sideBarLinks.length; i++) {
        var linkTarget = sideBarLinks[i].href;
        if (linkTarget.indexOf(thisDir) > -1) {
          //if you find a link to a page in this directory, mark the parent LI in the nav so it can be selected if an exact match is not found
          if (sideBarLinks[i].parentNode.parentNode.id && sideBarLinks[i].parentNode.parentNode.id == 'primary-nav') {
            //do nothing
            if (sideBarLinks[i].parentNode.className.indexOf('guessedNavSection') < 0 && sideBarLinks[i].parentNode.className.indexOf('selected') < 0) {
              sideBarLinks[i].parentNode.className = 'guessedNavSection' + guessCnt++; 
            }
          } else {
            greatGrandParent = sideBarLinks[i].parentNode.parentNode.parentNode;
            if (greatGrandParent.className.indexOf('guessedNavSection') < 0 && greatGrandParent.className.indexOf('selected') < 0) {
              greatGrandParent.className = 'guessedNavSection' + guessCnt++; 
            }
          }
        }
        if (linkTarget == barePageName || linkTarget == thisDir) {
          //an exact match
          foundLink = true;
          sideBarLinks[i].parentNode.className = 'selected'; //highlight the LI containing this link
          showUL(sideBarLinks[i].parentNode); //make any sub-lists visible (in case a gategory was matched)
          var makeVisible = true;
          if (sideBarLinks[i].parentNode.parentNode.id && sideBarLinks[i].parentNode.parentNode.id == 'primary-nav') {
            sideBarLinks[i].parentNode.parentNode.className = 'selected'; //highlight the LI containing the top-level link to this page.
          } else { 
            sideBarLinks[i].parentNode.parentNode.parentNode.className = 'selected'; //highlight the LI containing the UL that contains the link to this page.
            sideBarLinks[i].parentNode.parentNode.style.display = "block"; //make the UL containing this link visible
          }
        }
      }
      if (!foundLink) {
        //no match was found, so highlight the first nav section that contained a page in the same physical directory
        if (document.getElementsByClassname) {
          var gns = document.getElementsByClassName('guessedNavSection0');
          if (gns) {
            showUL(gns[0]);
          }
          $('#primary-nav').find('.guessedNavSection0').removeClass('guessedNavSection0').addClass('selected');
        }
      }
    }
		
		/*	
	=================================================
	    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
	} 	

   /*	
	=================================================
		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',
					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"); }
     );	     

	/*
	===============================================================================
		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","/images/search-button-rollover.png"); }, 
		function() { $(this).attr("src","/images/search-button.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});
			});
		}

	/*
	==============================================
		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
====================================
*/
 $('.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);
	}


		
});
