// Easing equation, borrowed from jQuery easing plugin
// http://gsgd.co.uk/sandbox/jquery/easing/
jQuery.easing.easeOutQuart = function (x, t, b, c, d) {
	return -c * ((t=t/d-1)*t*t*t - 1) + b;
};

/*
$(window).resize(function() {
    
});
*/



$(function() {
   //top nav menu hovers
   topNav();

   //ini where have i been cookies
   whereHaveIBeen();

   //initiate script for the where have I been scroller
   iniFooterScroller();

   //remove border on last a tag in the left hand menu
   subMenuBorder();

   //apply table row classes
   tableRowClasses();

   //apply dl row classes
   $(window).load(function() {
       if ($('.dl-table-narrow').length || $('.dl-table-wide').length) {
           dlRowClasses();
           dlHeightFix();
       }
   });

   // YouTube video links for iDevices
   $(window).load(function() {
       var ua = navigator.userAgent;
       if (ua.indexOf('iPod') > -1 || ua.indexOf('iPhone') > -1 || ua.indexOf('iPad') > -1) {
           $('a.youtube').each(function(){
		       $(this).unbind('click.fb');
               var link = $(this).attr('href');
               var ytid = link.substring(link.indexOf('yt=') + 3);
               var ytlink = 'http://www.youtube.com/watch?v=' + ytid;
               $(this).attr('href', ytlink);
           });
       }
   });

//check if right col has objects in it
   checkRightCol();

   // fix two-col height issues if required
   $(window).load(function() {
       if ($('.height-fix').length) {
           fixHeight();
       }
   });

   // fix other column height issues if required
   $(window).load(function() {
       if ($('.global-height-fix').length) {
           globalFixHeight();
       }
   });

   // add table of contents
   if ($('#toc').length) {
       toc();
   }

   // add table of contents for international entry requirements
   if ($('#int-entry-reqs-toc').length) {
       intEntryReqsToc();
   }

   // initiate our tabs functionality if it is found on the page

   if($('.content-tabs').length > 0){
     iniTabs();
   }

   // add fancybox to appropriately linked images
   $('a.fancy').fancybox();

   // add info popups
   $(window).load(function() {
       if($('.note').length > 0){
           infoPopups();
       }
   });

   // key dates tabs
   if($('.key-dates').length > 0){
       //keyDates();
   }

   // red star formatting
   formatRequiredFormLabels();
});

function trace(s) {
  try { console.log(s) } catch (e) {}
}

function topNav() {
    var fullpath = window.location.href;
    var homePageCheck = $('h1:eq(0)').text();
    var homeLinkCheck = $('li.menu:eq(0) a.menu-link span').text();

    if ((homePageCheck == "Home") && (homeLinkCheck == "Home")) {
        $('li.menu:eq(0) a.menu-link').addClass('current');
    } else {
    $('li.menu').each(function() {
        var href = $(this).children('a.menu-link').attr('href');
        var homeLinkText = $(this).children('a.menu-link').children('span').text();

        if ((fullpath.indexOf(href) == 0) && (homeLinkText != "Home")) {
            $(this).children('a.menu-link').addClass('current');
            $(this).prev().children('a.menu-link').addClass('current-adjacent');
        } 
    });
    }   

    $('li.menu').mouseover(function() {
        $(this).prev().each(function() {
            $(this).children('a.menu-link').addClass('adjacent');
        });
        $(this).children('a.menu-link').addClass('adjacent');
    });

    $('li.menu').mouseout(function() {
        $(this).prev().each(function() {
            $(this).children('a.menu-link').removeClass('adjacent');
        });
        $(this).children('a.menu-link').removeClass('adjacent');
    });
}

//Enable note popup bubbles
function infoPopups(){
$('.note').each(function(){
  if($(this).attr('title') != ''){
    var theTitle = $(this).attr('title');
    $(this).attr('title','');
    $(this).append('<span class="note-popup"><em>' + theTitle + '</em></span>');
  }
});
}

function contentOverflowVisible() {
   $('#content').css('overflow', 'visible');
}

function toc(){
        $('#toc').append('<p>On this page</p>');
        $('#toc').append('<ul id="toc-links"></ul>');
	$('#middle-col h2').each(function(i) {
	    var current = $(this);
            if (current.children('a').attr('name')) {
	        $("#toc-links").append('<li><a href="#' + current.children('a').attr('name') + '">' + current.text() + '</a></li>');
            } else {
	        current.attr('id', 'h2-' + i);
	        $("#toc-links").append('<li><a href="#h2-' + i + '">' + current.text() + '</a></li>');
            }
	});
    }

function intEntryReqsToc(){
        $('#int-entry-reqs-toc').append('<p>On this page</p>');
        $('#int-entry-reqs-toc').append('<ul id="toc-links"></ul>');
	$('#entry-int h3.int-toc').each(function(i) {
	    var current = $(this);
            if (current.children('a').attr('name')) {
	        $("#toc-links").append('<li><a href="#' + current.children('a').attr('name') + '">' + current.text() + '</a></li>');
            } else {
	        current.attr('id', 'h2-' + i);
	        $("#toc-links").append('<li><a href="#h2-' + i + '">' + current.text() + '</a></li>');
            }
	});
    }

function globalFixHeight() {
    var greatestHeight = 0;
    $(".global-height-fix").children().each(function() { // get all children for the height fix
        var testHeight = $(this).height();
        if (testHeight > greatestHeight) {
            greatestHeight = testHeight; //if larger than previous largest, sets the new largest
        }
    });
    $(".global-height-fix").children().each(function() { // sets height according to largest
        $(this).height(greatestHeight);
    });
}

function fixHeight() {
    $('.height-fix').each(function(){
        var fixedHeight = ($(this).height() - 45) + 'px';
        $(this).children('div').css('height', fixedHeight);
    });
}

function dlHeightFix() {
    if ($('.dl-table-narrow').length) {
        $('.dl-table-narrow dt').each(function(){
            var dtHeight = $(this).height();
            var ddHeight = $(this).next('dd').height();
            if (dtHeight > ddHeight) {
                $(this).css('height', (dtHeight + 'px'));
                $(this).next('dd').css('height', (dtHeight + 'px'));
            } else {
                $(this).css('height', (ddHeight + 'px'));
                $(this).next('dd').css('height', (ddHeight + 'px'));
            } 
        });
    }
    if ($('.dl-table-wide').length) {
        $('.dl-table-wide dt').each(function(){
            var dtHeight = $(this).height();
            var ddHeight = $(this).next('dd').height();
            if (dtHeight > ddHeight) {
                $(this).next('dd').css('height', (dtHeight + 'px'));
            } else {
                $(this).css('height', (ddHeight + 'px'));
            } 
        });
    }
}

function keyDates() {
	// Key dates tabs
	$(".key-dates ul.tabs>li:last-child").addClass('second');
	$(".key-dates ul.tabs ul").hide();
	$(".key-dates ul.tabs>li span").after('<strong></strong>');
	$(".key-dates ul.tabs>li span").click(function(){
	  $(".key-dates ul.tabs ul").hide();
	  $(".key-dates ul.tabs>li").removeClass('selected');
	  $(this).parent().addClass('selected');
	  $(this).parent().find('ul').show();
	});
	$(".key-dates ul.tabs li:first").addClass('selected');
	$(".key-dates ul.tabs>li.selected span").trigger('click');
}

function checkRightCol(){
   if($(".inside-right-col").length > 0 && $(".inside-right-col .object").length < 1){
      $(".inside-right-col").hide();
      var middleColWidth = parseInt($("#middle-col").css('width'));
      //middleColWidth = middleColWidth + 276;
      middleColWidth = middleColWidth + 260;
      $("#middle-col").css('width',middleColWidth+'px')
   }
}

function tableRowClasses(){
    $("#middle-col table").each(function(){
        var columns = $(this).find('thead tr:first-child').children().length;

        $(this).find('tbody > tr').filter(function() {
            return $(this).children().length == columns;
        }).filter(':odd').addClass('odd');

        $('tr.odd td[rowspan]').each(function() {
            $(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('odd');
        });
    });
    $("#middle-col table th:last-child").addClass('last');

    // Courses tables
    $("#middle-col table.blue-table").each(function(){
        $(this).find('tr').filter(':odd').addClass('odd');
    });
}

function dlRowClasses(){
   $(".dl-table-narrow dt:even").addClass('even');
   $(".dl-table-narrow dt:even + dd").addClass('even');
}

function showHide(selector) {
   $(selector).toggle();
}

function subMenuBorder(){
   $("#sub-menu>li:last-child a").addClass('no-border');
}

function iniFooterScroller(){
	$('#page-list li:last-child').addClass('last'); 
	$('#page-list li.last').prev().addClass('second-last');
	$('#page-list li.second-last').prev().addClass('third-last');
	$('body #page-list').serialScroll({
		items:'span',
		prev:        '#where-have-i-been a.prev',
		next:        '#where-have-i-been a.next',
		offset:      -879, //when scrolling to an item, stop 879 before reaching it (from the left)
		start:       $('#page-list li').size()-1, //start at the last item
		duration:    500,
		force:       true,
		stop:        true,
		lock:        true,
		cycle:       false, //don't pull back once you reach the end
		easing:      'easeOutQuart', //use this easing equation for a funny effect
		jump:        false, //click on the images to scroll to them
		exclude:     0,
		onAfter:     function(elem){
			var itemClass = $(elem).parent().attr('class');
			var positionFirst = $('#where-have-i-been ul').position();
			if(positionFirst.left > 19){
				$('#where-have-i-been a.prev').fadeOut('fast');
			}else{
				$('#where-have-i-been a.prev').fadeIn('fast');
			}
			if(itemClass.indexOf('page last')){
				$('#where-have-i-been a.next').fadeIn('fast');
			}else{
				$('#where-have-i-been a.next').fadeOut('fast');
			}
		}
	});
	var totalWidth = 0;
	$('#page-list ul li').each(function(){
		totalWidth = totalWidth + $(this).width();
	});
	if(totalWidth < 890){
		$('#where-have-i-been a.prev').hide();
		$('#where-have-i-been a.next').hide();
	}
}

//Barts crazy true lineage js cookie function
function whereHaveIBeen(){
   //First check if we have cookies, if we don't we simply just create two
   if($.cookie('lineageNames') != null){
      //Get the current cookie values, one for the page name and one for the url of the page
      var cookieUrl = $.cookie('lineageUrls');
      var cookieName = $.cookie('lineageNames');
      //Split those babies into arrays
      var currentUrls = cookieUrl.split('$');
      var currentNames = cookieName.split('$');
      //Check if we are on the current page as previously
      if(currentNames[currentNames.length-1] == $("h1").text()){
         //Don't add as we are on the same page
      }else{
         //Add the new page to the arrays
         cookieUrl = cookieUrl + '$' + window.location.href;
         cookieName = cookieName + '$' + $("h1").text();
         //Add the new page into the arrays
         currentUrls[currentUrls.length] = window.location.href;
         currentNames[currentNames.length] = $("h1").text();
         if(currentNames.length > 10){
            currentUrls.splice(0,1);
            currentNames.splice(0,1);
         }
      }
      //Reset as we now need to print our pages
      cookieUrl = '';
      cookieName = '';
      $("#page-list ul").html('');
      //Run a loop, for every page found in the array, print it out and update the new string
      for(var i = 0; i < currentNames.length; i++){
         $("#page-list ul").append('<li class="page"><a href="' + currentUrls[i] + '">' + currentNames[i] + '</a><span></span></li>');
         cookieUrl = cookieUrl + currentUrls[i] + '$';
         cookieName = cookieName + currentNames[i] + '$';
      }
      //Remove the last $ sign from both arrays
      cookieUrl = cookieUrl.slice(0, -1);
      cookieName  = cookieName .slice(0, -1);
      //Update our cookies with our new cookie strings
      $.cookie('lineageUrls',cookieUrl,{path: '/'});
      $.cookie('lineageNames',cookieName,{path: '/'});
   }else{
      //No current cookies found for this, so go ahead and create a new two
      $.cookie('lineageUrls',window.location.href,{path: '/'});
      $.cookie('lineageNames',$("h1").text(),{path: '/'});
      $("#page-list ul").html('<li class="page"><a href="' + window.location.href + '">' + $("h1").text() + '</a><span></span></li>');
   }
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


//Wherever there are tabs being used on the site, this function is used for initialising them and hiding/showing the necessary tabs, it also uses cookies to save the tab that you last had open on each individual page that has tabs
function iniTabs(){
  var tabCookie = $("#middle-col").attr('class') + 'tab';
  var cookieVal = '';
  //$('.content-tabs').show();

  //Find the content tab A tags and add ids and hide their relative divs that they are targeted for
  $('.content-tabs a').each(function(i){
    $(this).attr('id',('tab-' + (i + 1)));
    var rel = $(this).attr('href');
    if($(this).is('.selected')) {
      $(rel).show();
    }else{
      $(rel).hide();
    }
  });

  //Add onclicks to each A tag in the LI tags
  $('.content-tabs a').click(function(){
    $('.content-tabs a').removeClass('selected');
    $('.content-tabs li').removeClass('selected');
    $(this).addClass('selected');
    $(this).parent().addClass('selected');
    $.cookie(tabCookie, '#' + this.id);
    $('.content-tabs a').each(function(){
      var rel = $(this).attr('href');
      if($(this).is('.selected')) {
        $(rel).show();
      }else{
        $(rel).hide();
      }
    });
    return false;
  });

  // Special version for research project action link
//  $('.project-panel-section a.action-link').click(function(){
    $('.project-panel-section a.tab-link').click(function(){
    $('.content-tabs a').removeClass('selected');
    $('.content-tabs li').removeClass('selected');
    $('#tab-2').addClass('selected');
    $('#tab-2').parent().addClass('selected');
    $.cookie(tabCookie, '#tab-2');
    $('.content-tabs a').each(function(){
      var rel = $(this).attr('href');
      if($(this).is('.selected')) {
        $(rel).show();
      }else{
        $(rel).hide();
      }
    });
    return false;
  });

  // Special version for research areas
  $('#publications a[href=#Staff]').click(function(){
    $('.content-tabs a').removeClass('selected');
    $('.content-tabs li').removeClass('selected');
    $('.content-tabs a[href=#people]').addClass('selected');
    $('.content-tabs a[href=#people]').parent().addClass('selected');
    $.cookie(tabCookie, '#people');
    $('.content-tabs a').each(function(){
      var rel = $(this).attr('href');
      if($(this).is('.selected')) {
        $(rel).show();
      }else{
        $(rel).hide();
      }
    });
    window.location = '#Staff';
    return false;
  });

  // Special version for courses units tab link
  $('#course a[href=#units]').click(function(){
    $('.content-tabs a').removeClass('selected');
    $('.content-tabs li').removeClass('selected');
    $('.content-tabs a[href=#units]').addClass('selected');
    $('.content-tabs a[href=#units]').parent().addClass('selected');
    $.cookie(tabCookie, '#units');
    $('.content-tabs a').each(function(){
      var rel = $(this).attr('href');
      if($(this).is('.selected')) {
        $(rel).show();
      }else{
        $(rel).hide();
      }
    });
    return false;
  });

  // Generic version
  $('.cut-offs a.tab-link').click(function(){
    $('.content-tabs a').removeClass('selected');
    $('.content-tabs li').removeClass('selected');
    $('#tab-4').addClass('selected');
    $('#tab-4').parent().addClass('selected');
    $.cookie(tabCookie, this.href);
    $('.content-tabs a').each(function(){
      var rel = $(this).attr('href');
      if($(this).is('.selected')) {
        $(rel).show();
      }else{
        $(rel).hide();
      }
    });
    return false;
  });

  //Open the appropiate tab weather it be from the requested URL or from the users cookie
  var anchor = location.hash.substring(1); //e.g. anchor = #info (from URL "http://www.qut.edu.au/test.html#info") 
  if (anchor != '') {
    //If anchor is a tab, open that tab
    $('.content-tabs a').removeClass('selected');
    $('.content-tabs li').removeClass('selected');
    $('.content-tabs a[href=#'+anchor+']').addClass('selected');
    $('.content-tabs a[href=#'+anchor+']').parent().addClass('selected');
    $.cookie(tabCookie, this.href);
    $('.content-tabs a').each(function(){
      var rel = $(this).attr('href');
      if($(this).is('.selected')) {
        $(rel).show();
      }else{
        $(rel).hide();
      }
    });
    $(window).load(function() {
      window.scrollTo(0,0);
    });
  } else {    
    //If a cookie is available, then activate the tab that the cookie value is for
    if($.cookie(tabCookie) != '' || $.cookie(tabCookie) != null){
      cookieVal = $.cookie(tabCookie);
      $(cookieVal).trigger('click');
    } 
    if($.cookie(tabCookie) == '' || $.cookie(tabCookie) == null){
      $('.content-tabs li:eq(0)').addClass('selected');
    }
  }
}

//Replace all *'s on form labels to allow them to be formatted red.
function formatRequiredFormLabels() {
  $("#content form label").each(function() { 
    if ($(this).html().indexOf("*") != -1) {
      $(this).html( $(this).html().replace("*:","<span class=\"red-star\">*</span>:") );
    }
  });
} 

