// Namespace function
function namespace(ns) {
    ns = ns.split('.');
    var cur = window, i;
    while ( i = ns.shift() ) {
        if ( !cur[i] ) cur[i] = {};
        cur = cur[i];
    }
}

namespace("website");

$(document).ready(function(){
  // Hacks for IE, mostly for fake hover classes
  if ($.browser.msie) website.iehacks();
  
  // Load the flash banner
  website.banners.setup("#home #banner");
  
  // Apply the sifr replacements
  website.sifr();
  
  // Setup and tabbed content that might be needed
  if ($("#body_tabs").length > 0) website.tabs.setup("#body_tabs");
  if ($(".panel.tabs .tab_container").length > 0) website.tabs.setup(".panel.tabs .tab_container");
  if ($("#content_tabs").length > 0) website.tabs.setup("#content_tabs");
  
  // Hide Labels from particular fieldsets
	$("form.hide_labels").each(website.hide_labels);	  
		
	// Popup links
	$("#body a.popup").each(website.popup);
	
	// Document links
	website.document_links();
	
  // form effects
  website.form_effects();
  
  var $news_intro = $("#body.hentry .intro");
  $(".quote:first", $news_intro).height($(".image:first", $news_intro).height()-40);
  
  website.main_nav_focus();
    
});

website = {
  // ratios to contol the look of the sifr fonts
  serifa_ratios: [7, 1.47, 10, 1.43, 15, 1.36, 16, 1.34, 23, 1.32, 27, 1.31, 28, 1.3, 31, 1.29, 34, 1.3, 39, 1.28, 40, 1.29, 52, 1.28, 55, 1.27, 56, 1.28, 84, 1.27, 85, 1.26, 88, 1.27, 91, 1.26, 92, 1.27, 95, 1.26, 96, 1.27, 1.26], 
  
  main_nav_focus: function() {
    $("#main_nav ul.top_level > li > a").focus(function() {
      $("#main_nav li").removeClass("hover");
      $(this).parent("li").addClass("hover");
    }).blur(function() {
      $("#main_nav li").removeClass("hover");
    });
    $("#main_nav .sub_surround a").focus(function() {
      $("#main_nav li").removeClass("hover");
      $(this).parents("li.main_section").addClass("hover");
    });
  }, 
  
  // control the hiding and showing of the advanced search form fields
  form_effects: function() {
    $("form fieldset.advanced_search_fields").hide();
    $("fieldset a.advanced_switch").click( function() {
      $(this).parents("form").find("fieldset.advanced_search_fields").slideToggle("fast");
      return false;
    });
  }, 
  
  // perform all of the various sifr font replacements throughout the site
  // see http://wiki.novemberborn.net/sifr/ for in depth information on sIFR
  sifr: function() {
    var ratios = website.serifa_ratios;
    
    sIFR.replace(serifa, {
      selector: '#body h1',
      css: '.sIFR-root { background-color: #ffffff; color: #ed1c24; leading: -11; letter-spacing: -1; }', 
			tuneHeight: '-18', 
			offsetTop: '-12', 
      ratios: ratios, 
      wmode: 'opaque'
      });
/*      
    sIFR.replace(serifa, {
      selector: '#body h2',
      css: '.sIFR-root { background-color: #ffffff; color: #ed1c24; leading: -11; letter-spacing: -1; }', 
			tuneHeight: '-8', 
			offsetTop: '-6	',
      ratios: ratios, 
      wmode: 'opaque'
      });
*/
    sIFR.replace(serifa, {
      selector: '#body h2',
      css: '.sIFR-root { background-color: #ffffff; color: #000000; leading: -11; letter-spacing: -1; }', 
			tuneHeight: '-8', 
			offsetTop: '-6	',
      ratios: ratios, 
      wmode: 'opaque'
      });
      
      sIFR.replace(serifa, {
                        selector: '#wrap #section_title',
                        css: '.sIFR-root { background-color: #ffffff; color: #ed1c24; leading: -11; letter-spacing: -1; }', 
                  			tuneHeight: '-15', 
                  			offsetTop: '-9',
                        ratios: ratios, 
                        wmode: 'transparent'
      });
    
		sIFR.replace(serifa, {
			selector: '#body h3',
			css: ['.sIFR-root { background-color: #ffffff; color: #000000; leading: -11; letter-spacing: -1; }', 
						'a { color: #000000; text-decoration: none; }', 
						'a:hover { color: #ed1c24; text-decoration: underline; }'], 
      tuneHeight: '-13', 
			offsetTop: '-8',
			ratios: ratios, 
			wmode: 'transparent'
			});
    
    sIFR.replace(serifa, {
      selector: '.panel h3',
      css: '.sIFR-root { background-color: #ffffff; color: #333333; leading: -11; letter-spacing: -1; }', 
			tuneHeight: '-14', 
			offsetTop: '-8', 
      ratios: ratios, 
      wmode: 'transparent'
      });
      
      sIFR.replace(serifa, {
                      selector: '.panel .related',
                      css: '.sIFR-root { background-color: #ffffff; color: #333333; leading: -11; letter-spacing: -1; }', 
                			tuneHeight: '-10', 
                			offsetTop: '-5', 
                      ratios: ratios, 
                      wmode: 'transparent'
            });

    sIFR.replace(serifa, {
      selector: '.signpost h4',
      css: '.sIFR-root { color: #333333; leading: -11; letter-spacing: -1; }', 
			tuneHeight: '-10', 
			offsetTop: '-5',
      ratios: ratios, 
      wmode: 'transparent'
      });
/*
    sIFR.replace(serifa, {
      selector: 'h2#section_title',
      css: '.sIFR-root { color: #ed1c24; leading: -11; letter-spacing: -1; }', 
			tuneHeight: '-15', 
			offsetTop: '-8',
      ratios: ratios, 
      wmode: 'opaque'
      });
*/
    sIFR.replace(serifa, {
      selector: 'h2#section_title',
      css: '.sIFR-root { color: #000000; leading: -11; letter-spacing: -1; }', 
			tuneHeight: '-15', 
			offsetTop: '-8',
      ratios: ratios, 
      wmode: 'opaque'
      });

    sIFR.replace(serifa, {
      selector: '#footer .contact .details .sifr-replace',
      css: ['.sIFR-root { background-color: #333333; color: #ffffff; letter-spacing: -1; }', 
            'a { color: #ed1c24; text-decoration: none; display: block; }', 
            'a:hover { color: #ed1c24; text-decoration: underline; }'], 
			tuneHeight: '-13', 
			offsetTop: '-7',
      ratios: ratios, 
      wmode: 'opaque'
      });
  }, 
  
  // Hide form labels, set the associated form elements value to the label text
  hide_labels: function() {
  	$(this).find("label").each(function() {
  		$('#' + this.htmlFor).val(this.innerHTML);
  		$(this).hide();
  		$('#' + this.htmlFor).click(website.clearbox);
  	})
  },

  // Clear default text in an input box when it is selected
  clearbox: function() {
		if (!this.default_value) this.default_value = this.value;

		if (this.value == '') {
			this.value = this.default_value;
			this.select();
		} else if (this.value == this.default_value) {
			this.value = '';
		}
  },
    
  // Popup link, sets the target of a link to _blank to force it to open in a new window
  popup: function() {
    this.target = "_blank";
    this.title =  this.title ? this.title += ". " : "";
    this.title += "Link opens in a new window.";
  }, 
  
  // Add classes to document links depending on their extensions to highlight what kind of document
  // is being linked to
  document_links: function() {
    $("#body a[href$='.doc']").addClass("doc");
  	$("#body a[href$='.xls']").addClass("xls");
  	$("#body a[href$='.ppt']").addClass("ppt");

  	$("#body a.pdf:has(img)").removeClass("pdf");
  	$("#body a.doc:has(img)").removeClass("doc");
  	$("#body a.xls:has(img)").removeClass("xls");
  	$("#body a.ppt:has(img)").removeClass("ppt");
  }, 
    
  // Internet explorere specific code to work around any browsers bugs or deficiencies
  iehacks: function() {
    if (parseInt($.browser.version) == 7) {
      // IE7 hacks      
       
    } else if (parseInt($.browser.version) < 7) {
      // IE6 and below hacks
      
      // Menu popdown
      $("#main_nav > ul").superfish({
        hoverClass: 'hover', 
        autoArrows: false, 
        dropShadows: false, 
        disableHI: true, 
        delay: 0
        }).find("div.sub_surround").bgIframe();
     
    } else {
      // All IE versions
      $("#search").hover(
        function(){ $(this).addClass("hover"); },
        function(){ $(this).removeClass("hover"); }
      );
    }
  }
};

website.tabs = {
  active: "#tab-0", 
  
  sifr_active_css: ['.sIFR-root { background-color: #ffffff; color: #cccccc; leading: -11; letter-spacing: -1; }', 'a { color: #000000; text-decoration: none; leading: -11; }', 'a:hover { color: #000000; }'],
  sifr_inactive_css: ['.sIFR-root { background-color: #ffffff; color: #cccccc; leading: -11; letter-spacing: -1; }', 'a { color: #cccccc; text-decoration: none; leading: -11; }', 'a:hover { color: #000000; }'],
  
  // Setup the content area tabs (such as on the homepage)
  // Accepts a jquery selector for the containing element. The inner elements to be tabbed should 
  // have a class of 'tabbed' applied to them
  setup: function(container) {
    // if the location bar currently contains a hash then sleect that tab to be active if it matches
    if (window.location.hash.indexOf("#tab-") == 0) {
      website.tabs.active = window.location.hash;
    }
    
    // if a container elent is not passed to the function then use #tab_container as a default
    var elem = container == undefined ? "#tab_container" : container;
    var $container = $(elem);
    
    // create an empty ul to place the tab links into
    var $tabs = $("<ul id=\"tablinks\" class=\"clearfix\"></ul>");
    
    var $panels = $(".tabbed", $container);
    
    // loop through all of the panels with a class .tabbed inside the container element and 
    // add nav elements to the empty ul defined above
    $panels.each( function(idx) {
      var $this = $(this);
      $this.attr("id", "tab-"+idx);
      $tabs.append("<li><a rel=\"#" + $this.attr("id") + "\" href=\"#" + $this.attr("id") + "\">" + $("h3", $this).text() + "</a></li>");
      if ($container.is(".flashed") && idx < ($panels.length-1)) {
        $tabs.append("<li>/</li>");
      }
      $("h3", $this).remove();
    });
    $("li",$tabs).last().addClass("last");
    // hide all of the panels by default
    $panels.hide();

    // attach clikc eent handlers to all of the tab navigation elements
    $("a", $tabs).click( function(event) {
      event.preventDefault();
      website.tabs.change_tab("#"+$(this).attr("rel").split("#")[1], $container);
			return false;
    });
    
    // add the tab navigation to the DOM before the container element
    $container.before($tabs);    
        
    // set the active tab on first load
    website.tabs.change_tab(website.tabs.active, $container);    
    
    // replace the tab links with sifr
    // the href attribute needs to be changed to javascript:void(0) in order to get around flash 
    // interaction issues in many browsers.
    // Normally this is very very bad but as the elements are being replaced with javascript it is 
    // already a given that the browser has javascript support and it is active
    if ($container.is(".flashed")) {
      $("a", $tabs).attr("href", "javascript:void(0);");
      website.tabs.sifr();
    }
  }, 
  
  // control the hiding and showing of the various panels
  change_tab: function(tab_id, container, flash_id) {
    $(website.tabs.active).hide();
    var $container = container;
    $(tab_id).show();

    // Remove all of the active classes and set the new active one
    var $tablinks = $("#tablinks")
    $("a", $tablinks).removeClass("active");

    $("a[rel$=" + tab_id + "]", $tablinks).addClass("active");
  
    // change the state of the active sifr tab
    // there needs to be special logic for the flash replaced elements because of issues in 
    // many browsers
    if ($container.is(".flashed") && $(".sIFR-flash", $tablinks).length > 0) {
      website.tabs.update_sifr($tablinks, flash_id);
    } 
    
    // set the active tab reference
    website.tabs.active = tab_id;
  }, 
  
  // in order to have the sifr replaced tabs change color on hover and have them display and active 
  // state we need to have some fancy replacements just for them which is why they are defined in 
  // this function instead of the main website.sifr() function
  sifr: function() {
    var ratios = website.serifa_ratios;
    sIFR.replace(serifa, {
      selector: '#tablinks li',
      css: ['.sIFR-root { background-color: #ffffff; color: #cccccc; leading: -11; letter-spacing: -1; }',
            '.active { color: #000000; }', 
            'a:hover { color: #000000; }', 
            'a { color: #cccccc; text-decoration: none; }'            
            ], 
      ratios: ratios, 
      wmode: 'opaque', 
			tuneHeight: '-15', 
			offsetTop: '-8', 
      forceSingleLine: true, 
      onRelease: function(fi) {
        var flash_id = $(fi).attr("id");
        var $link = $("#"+flash_id+"_alternate a:first");
        var $container = $("#body_tabs");
        website.tabs.change_tab("#"+$link.attr("rel").split("#")[1], $container, flash_id);
      }
    });
  }, 
  
  // reset the styles of the sifr replaced tabs to highlight when they are clicked on or active
  update_sifr: function(tablinks, flash_id) {
    $tablinks = tablinks;

    if (sIFR != "undefined" && sIFR.replace && typeof sIFR.replace == "function") {      
      var $tab_replacements = $(".sIFR-flash", $tablinks);

      // if there is a reference to a flash replaced tab passed into the function change the css 
      // rules of all of the replaced elements to the inactive style and the passed in reference to 
      // the active one if a reference to a replaced tab is not passed in then we assume that this 
      // is an initial load of the page and that the active tab should be the first one in the list.
      if (flash_id != undefined) {
        $tab_replacements.each( function() {
          var $this = $(this);
          if ($this.attr("id") == flash_id) {
            sIFR.replacements[$this.attr("id")].changeCSS(website.tabs.sifr_active_css);
          } else {
            sIFR.replacements[$this.attr("id")].changeCSS(website.tabs.sifr_inactive_css);
          }        
        });
      } else {
        var active_id = $("li:first .sIFR-flash", $tablinks).attr("id");
        if (active_id != undefined) {
          sIFR.replacements[active_id].changeCSS(sifr_active_css);
        }
      }      
    }
		return false;
  }
};

website.banners = {
  // the banner setup accepts a jquery selector, if one is not supplied the selector defaults to 
  // #banner
  setup: function(selector) {    
    var elem = selector == undefined ? "#banner" : selector;
    
    var $banner = $(elem);    
    var height = "300px";
    var width = "100%";
    
    // use the jquery flash plugin to embed the banner if the element exists
    if ($banner.length > 0) {
      $banner.flash(
        { 
          src: '/media/media,105,en.swf',
          width: width,
          height: height,
          wmode: "opaque",
          flashvars: {    
            xmlpath: "/media/config.xml"
          }
        }, 
        { update: false, version: 9 }, 
        function(htmlOptions) {
          // assuming that the right version of flash is available, empty out the container element 
          // and append the swf to it
          $(this).empty().removeClass("container").css({width: "100%", margin: 0}).append($.fn.flash.transform(htmlOptions));
          var $masthead = $("#masthead");
          $masthead.removeClass("container").find(".header").addClass("container");
        }
      );
			
			if ($.cookie("_abertay_show_banner") == "false") {
				$banner.hide();
			}
			
      // Create the 'hide banner' link
      website.banners.create_hide_link("#masthead .header");
    }    
  },
  
  // the show/hide link is created entirely with javascript as it only applies to showing or hiding 
  // the flash banner which is embedded using javascript
  create_hide_link: function(selector) {
    var elem = selector == undefined ? "#masthead" : selector;
    
    var link = "<a href=\"#hide_banner\" id=\"hide_banner\">Hide banner</a>";    
    var $link = $(link);
    var $banner = $("#banner");
    
    $link.text(update_text($banner));
    $link.click( function() {
      $banner.slideToggle("fast", function callback() {
        $link.text(update_text($banner));
				update_cookie($banner);				
      });
      return false;
    });
    var $elem = $(elem);    
    $elem.append($link);
    
    // checks to see if the banner is visible or not and alters the link text accordingly
    function update_text(banner) {
      var $banner = banner;
      var text = ""
      if ($banner.is(":visible")) {
        text = "Hide banner";
      } else {
        text = "Show banner";
      }
      return text;
    }
		
		// sets a cookie to save whether or not the flash banner on the homepage should be displayed
		function update_cookie(banner) {
			$.cookie('testcookiesenabled', null, {path: "/"});
  	  $.cookie('testcookiesenabled', 'enabled', {path: "/"});

			if ($.cookie('testcookiesenabled')) {				
				var $banner = banner;

	      if ($banner.is(":visible")) {
	        $.cookie("_abertay_show_banner", "true", {path: "/", expires: 7})
	      } else {
	        $.cookie("_abertay_show_banner", "false", {path: "/", expires: 7})
	      }
			}
		}
  }  
};
