// JavaScript Document
$(document).ready(function(){
	
  //Login status
$('<div id="portal-status"/>').prependTo($(".header"));
checkLogin();

  //Clickable stuff
  $("#logo").addClass('clickable').click(function(){window.location="http://www.stir.ac.uk";});
  $("#homeblocks #news h2").addClass('clickable').click(function(){window.location="http://www.stir.ac.uk/news";});
  $("#homeblocks #whats-on h2").addClass('clickable').click(function(){window.location="http://www.externalrelations.stir.ac.uk/events/";});
  $("#homeblocks #research h2").addClass('clickable').click(function(){window.location="http://www.research.stir.ac.uk/";});
  
  //Make focusable
  $(".course-browser").attr('tabindex',0);
  
  //Parent selector
  $(".course-browser a").focus(function(){$(this).parents("ol,ul").addClass('leftshow');});
  $(".course-browser a").blur(function(){$(this).parents("ol,ul").removeClass('leftshow');});

  //IE's lack of support of :hover psuedo class
  $(".course-browser").hover(function(){$(this).children("ul, ol").css({left:"1px"});},function(){$(this).children("ul, ol").css({left:"-2222px"});});
  $(".course-browser").focus(function(){$(this).children("ul, ol").css({left:"1px"});});
  $(".course-browser").blur(function(){$(this).children("ul, ol").css({left:"-2222px"});});
  
  //Touch interface needs 'click' event
  $(".course-browser").click(function(){
	     if(typeof(stirdebugmode) != "undefined"){ 
     	   var a = $(this).children("ul, ol").css();
		   alert(a);
		 }
  });
  //New window links
  $("a.newwindow").click(function(e){e.preventDefault();window.open(this.href);});
  
  //Tabs
  $(".stir-tabs").tabs();
  $(".dynamic-tabs").tabs();

  //SideTabs
  $(".sidetab ol.tabs li:nth-child(2) a").css("background-position","0px -96px");
  $(".sidetab ol.tabs li:nth-child(3)").addClass("current").find("a").css("background-position","0px -192px");
  $(".sidetab ol.tabs li").hover(function(){activateTab($(this));},function(){});
  $(".sidetab .content a").attr('tabindex','-1');
  $(".sidetab ol.tabs li a").focus(function(){activateTab($(this).parent().parent());});
	
  //Slideshows
  slideshow($(".slideshow"));

  //Acronyms
  var sb = $("<div></div>").appendTo('body'); //speech bubble
  var tt = $('<div></div>').addClass('inner'); //tooltip
  var h = ''; //bubble handedness
  $("acronym, abbr,dfn").click(function(){
	  var w = ($(window).width()); //current window width
	  sb.removeClass('tooltip-left').removeClass('tooltip-right');
	  var p = $(this).position();
	  if(p.left<=(w/2)){sb.addClass('tooltip-left').css({'left':p.left});}else{sb.addClass('tooltip-right');}
	  var h = parseFloat($(this).css('line-height'));
	  tt.html($(this).attr('title'));
	  
	  sb.css({'top':p.top+h}).html(tt).show();
	  $(".tooltip-right").css('left',p.left-(sb.width()-20));
  });
  sb.click(function(){$(this).hide();});
  
  //Tables
  $('table.zebra thead tr td:first-child').addClass("thead-frst-chld");
  $("table.zebra thead tr:nth-child(odd) th").addClass("thead-th-odd");
  $("table.zebra thead tr:nth-child(even) th").addClass("thead-th-even");
  $("table.zebra tbody tr:nth-child(odd) th").addClass("tbody-th-odd");
  $("table.zebra tbody tr:nth-child(even) th").addClass("tbody-th-even");
  $("table.zebra tbody tr:nth-child(even) td").addClass("tbody-td-even");


 //Popup Info
 $(".triggerlb a").each(function(){
	 a = $(this).attr('href');
	 $(a).click(function(){$(this).hide();});
	 }).click(function(e){
	 e.preventDefault();
	 a = $(this).attr('href');
	 $(a).show();
 });

$('.module_timetable a').each(function(i, link){
  $(link).click(function(event) {
    event.preventDefault();
    $('.module_popup').css('display', 'none');
	  $($(link).attr('href')).css("top", ( $(window).height() - $($(link).attr('href')).height() ) / 2+$(window).scrollTop() + "px");
	  $($(link).attr('href')).css("left", ( $(window).width() - $($(link).attr('href')).width() ) / 2+$(window).scrollLeft() + "px");
	$($(link).attr('href')).css('display', 'block');
  });
});

jQuery.expr[':'].icontains = function(a,i,m){
     //return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
	 return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
};

  //GALLERY
	//Variables
	var a = $(".gallery > ul > li").size();
	var b = 0;
	if(a%6 == 0){
	b = a/6;
	}else{b=Math.floor(a/6)+1;}
	var h = (b*110)+10;
	
	//Set up
	$(".gallery").append("<div id=\"lightbox\"></div><div id=\"overlay\"></div>");
	$(".gallery ul li a").click(function(e){e.preventDefault();}).attr('tabindex','-1');
	$(".gallery ul li").css({bottom:h+"px"}).attr('tabindex','0');
	$("#lightbox,#lightbox img,#overlay").click(lbHide);
	
	//Begin Drawing
	$(".gallery ul").animate({height:h+"px"},"fast");
	tetris($(".gallery ul li:last-child"));
	
	jQuery.fn.center = function () {
	  this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
	  this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
	  return this;
	}
  // END Gallery
  
  $(".has_id_links").each(function(){
	  process_matrix_links();
  });

  //$(".call-to-action.application").before($("<div/>").addClass('downtime').html('<strong>Scheduled Maintenance</strong><br>The application and enquiry buttons below are offline between <strong>8am and 12 noon BST on Saturday 9 April</strong>. If you experience any difficulties please try again after this time.'));     


}); //END DOCUMENT READY

//SUPPORT FUNCTIONS FOR GALLERY
var left    = 10;
var bottom  = 10;
function tetris (jq){
	if(left > 575){left = 10;bottom += 110;}
	bg = jq.find("img:first-child").css('display','none').attr('src');
	jq.css({left:left+"px", background:"url("+bg+") top center no-repeat", cursor:"pointer"}).data({bottom:bottom, left:left,bg:bg}).click(function(){$("#lightbox").html('<img src="'+$(this).data('bg')+'"><br><span>'+$(this).attr('title')+'</span><br>&laquo;<a id="next">Next</a> <a id="prev">Prev</a>&raquo; <a id="close">Close</a>').center();lbShow();if(jq.prev().length ){$("#prev").click(function(){$("#lightbox").hide(100, function(){jq.prev().click();});});}if(jq.next().length){$("#next").click(function(){$("#lightbox").hide(100,function(){jq.next().click();});});}$("#close").click(lbHide);});
	jq.animate({bottom:bottom+"px"},50,function(){$(this).hover(function(){grow($(this));},function(){shrink($(this));});tetris(jq.prev());});left += 110;}
function grow(jq){jq.css("z-index","200").animate({bottom:(jq.data("bottom")-10)+"px",left:(jq.data("left")-10)+"px",width:"120px",height:"120px"},50);}
function shrink(jq){jq.css("z-index","auto").animate({width:"100px",height:"100px",bottom:jq.data("bottom")+"px",left:jq.data("left")+"px"},50);}
function lbShow(){$("#overlay").fadeIn(100, function(){$("#lightbox").show(100);});}
function lbHide(){$("#lightbox").hide(100, function(){$("#overlay").fadeOut(100);});}

function slideshow($id){
	$id.each(function(){
		id=$(this).attr('id');
		if(window.ajax && window.ajax[id] && (window.ajax[id].length>0)){
			for(x in ajax[id]){
				$(this).prepend(ajax[id][x]);
			}
		}
		if($(this).children('div.frame').length > 1){
			fadereroo($(this).children('div.frame').last());
		}
	});
}

/***
* Recursive 'slideshow transition' function 
* r.w.morrison@stir.ac.uk | 16/06/2010
* @$el - jQuery object representing an image in the slideshow.
*		  the function will transition to the $el.prev() image.
*/
function fadereroo($el){
	var rst = false;
	if($el.index()== 0){
		$el.css({zIndex:1000});
		$prev=$el.parent().children('div.frame').last();
		$el.parent().children('div.frame').css('display','block');
		rst = true;
	}else{
		$prev=$el.prev('div.frame');
		rst=false;
	}
	//These numbers affect the speed of the slideshow. Figures are delays measured in miliseconds.
	$el.delay(9000).fadeOut(2000, function(){if(rst){slideshowReset($el);}fadereroo($prev);});
	//    hold-^  transition-^
}

function slideshowReset($element){
	$element.css({zIndex:0,display:'block'});
}
/* Used for SIDETABS - r.w.morrison@stir.ac.uk - 06/07/2010 */
function activateTab($tab){$(".content").css('z-index',0);$(".current").removeClass("current");$tab.addClass('current').children(".content").css('z-index','1000');}  

function checkLogin(){ logged = getCookie('psessv0'); if (logged!=null && logged!=""){ b=logged.split("|"); $("#portal-status").html('<a href="https://portal.stir.ac.uk/my-portal.jsp" class="portal00">My Portal</a> Welcome back <strong> '+b[2].split("_").join(" ") + '</strong>. You last logged on '+b[3].split("_").join(" ") + ' <a href=\"https://portal.stir.ac.uk/security/logout.jsp" class="portal01">Log out</a>'); } else { $("#portal-status").html(''); } } 

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

function process_matrix_links(){
  //we'll use an array to track our <a> objects
  var links = new Array();

  //itterate each link in the content area
  $("#right-column a").each(function(){
    
    //this is the link prefix we're looking for:
    a = './?a=';
    src = $(this).attr('href');

    //if the prefix is found:
    if((typeof(src) != "undefined") && (src.indexOf(a) === 0)){
      //we only want the ID from the link
      b=src.split(a);
      id = parseInt(b[1]);
      links[id] = new Array();
      links[id][0] = $(this); //jQuery element
      if(b[1].indexOf('#') != -1){
        ref = b[1].split('#');
        links[id][1] = '#'+ref[1];
      } else {
        links[id][1] = '';    //link string
      }
      

      //Call the JavaScript API to get the correct Webpath
      $.ajax({
        url: '/web-services/javascript-api.js?key=6867877307&type=getGeneral&id=' +  id,
        success: function(data) {
replace_matrix_link(data,links);
        }
      });
    }
  });

  function replace_matrix_link(data,links){
    if (data.error != undefined) {
    } else {
      links[data.id][0].attr('href',data.web_path+links[data.id][1]);
    }
  }
}
