// 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();
	// $("#menu>li a").focus(website.menu_focus);
	// $("#menu>li").blur(website.menu_blur);
	
	
	// 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();
	
	$("ul.news_panel a").hover(website.news_panel_over, website.news_panel_out);
	
	// Embedded video links
    website.embed_videos($("#body a.flv, #body a.mp4"), false);
    $("#video_player").click(function(){
        website.embed_videos($("#video_player"), true);
        return false;
    });
    
	
  	// Hosted video player
    // if (($videos = $("a.flv")) && $videos.length > 0) website.videos($videos);
    // if ($("#video_player").length > 0) website.video($("#video_player"));
	
	
	// Gmaps embed code
  	// website.google_maps();
	
	// Inline form validation
	if ($("form.inline_validation").length > 0) {
	  $("form.inline_validation").each( website.form_validation.setup($(this)) );
	}
	if ($("form.tabbed_form fieldset.tabbed").length > 0) $("form.tabbed_form").tabbed_form();
	if ($("#forgotten_password_form").length > 0) website.forgotten_password();
	
	// Disable links for preview window
	website.disable_preview();
	
	// Course search overlay
	if ($("#course_directory").length > 0) {
		$("#department_popup").overlay({expose:'#BBBBBB', fadeInSpeed:'fast', preload:false});
	}
	
	// Event tooltips
	$(".mini table.calendar a.num").tooltip({
		position: ['bottom', 'center'],
		offset: [10, 0],
		opacity: 1,
		delay: 60,
		effect: 'fade',
		tip: 'span',
		onBeforeShow: function() {
			$(".mini span.event_details").hide();
		}
	});
	
	// Equal ops questionnaire form
	$("input.clear_radios").click(website.clear_radio_buttons);
	$("ul.other_radios input:radio").click(website.other_radio_options);
	
	// Banner rotations
	if($("#banner_tabs").length > 0){
		$("#banner_tabs").tabs(".banner_slideshow > div", { effect: 'fade', fadeInSpeed:2000, fadeOutSpeed:2000, rotate: true, initialIndex:0 }).slideshow( {interval:6000, autoplay:true} );
	}
});

/* jQuery additions */
jQuery.fn.first = function() { return this.eq(0) };
jQuery.fn.last = function() { return this.eq(this.size() - 1) };
jQuery.fn.exists = function() { return (this.length > 0); };
jQuery.fn.ifExists = function() { if(this.length > 0) return this; };

// Tweak to jQuery so that rails will respond_to format.js from a jQuery ajax call
$.ajaxSetup({
	beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");}
});

// Is an item really visible? http://remysharp.com/2008/10/17/jquery-really-visible/
jQuery.extend(
  jQuery.expr[ ":" ], 
  { reallyvisible : function (a) { return !(jQuery(a).is(':hidden') || jQuery(a).parents(':hidden').length); }}
);

// Used by the multi-model form JS
replace_ids = function(s){
  var new_id = new Date().getTime();
  return s.replace(/NEW_RECORD/g, new_id);
}


jQuery.extend({
/**
* Returns get parameters.
*
* If the desired param does not exist, null will be returned
*
* @example value = $.getURLParam("paramName");
*/ 
getURLParam: function(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  var bFound=false;
  
  var cmpstring = strParamName + "=";
  var cmplen = cmpstring.length;

  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?")+1);
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (aQueryString[iParam].substr(0,cmplen)==cmpstring){
        var aParamAndAnchor = aQueryString[iParam].split("=");
        var aParam = aParamAndAnchor[1].split("#");
        strReturn = aParam[0];
        bFound=true;
        break;
      }
      
    }
  }
  if (bFound==false) return null;
  return strReturn;
}
});

website = {
	// News panel links
	news_panel_over: function() {
		var li = $(this).parents("li");
		$("ul.news_panel li").removeClass("active");
		li.addClass("active");
	},
	
	news_panel_out: function() {
		$("ul.news_panel li").removeClass("active");
		$("ul.news_panel li:first").addClass("active");
	},
	
	
	// Forgotten password link
	forgotten_password: function() {
		if ($("#forgotten_password_form fieldset div").length > 0) {
			$("#forgotten_password_form a").hide();
			if ($("#forgotten_password_form #notice").length > 0) {
				$("#forgotten_password_form label, #forgotten_password_form input").hide();
			}
		} else {
			$("#forgotten_password_form fieldset").hide();
			$("#forgotten_password_form a").click(function(){
				$("#forgotten_password_form fieldset").toggle();
				return false;
			});
		}
	},
	
    disable_preview: function() {
    if (location.href.match(/cms_preview/)) {
    		$("a").click(function(){
    			alert("Links are disabled as this is a preview window."); 
    			return false; 
    		});
    	}
    }, 

    // Hide labels, set text to targets value
    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
    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 = '';
    	}
    },
  
	// Clear radio buttons
	clear_radio_buttons: function() {
		var ul = $(this).parents("ul");
		$("input:radio", ul).attr('checked', false);
	},
	
	other_radio_options: function() {
		var input = $("input:radio", $(this).parents("li"));
		var ul = $(this).parents("ul");
		
		if (input.length > 0) {
			$("input:text", ul).val($(input).val());
		}
	},

    // Jump to URL
    jump_to_url: function(url) {
    	if (url == "") return false;
    	location.href = "/" + url;
    },

    // Popup link
    popup: function() {
        this.target = "_blank";
        this.title =  this.title ? this.title += ". " : "";
        this.title += "Link opens in a new window.";
    }, 

    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");
    }, 
  
    embed_videos: function(elms, autoplay) {
		// Hosted video player
        elms.each(function(){
         var container = $('<div/>');
         var flashvars = {
             video: this.href,
             autoplay: autoplay,                 // use to autoplay video
             //buffer: 3,                        // set buffer length (default is 3)
        
             navAutoHideIdleTime: 2,             // set mouse idle time for navigation to hide
             navAutoHide: true,                  // disable navigation auto hide
             //hideNav: true,                    // turn off navigation
        
             //debug: true,                      // debug mode
             scaleMode: "crop",              // use "crop" to change, default mode is "fit"
        
             // THEMES //////////////////////////////////////////////////
        
             // theming is based on setting hue, saturation, brightness and constrast values
             // to 0xff0000 (red) colour
        
             customTheme: false          // enables custom colours
         };
         
          $(container).flashembed({src:'/flash/flvplayer.swf', width: 460, height: 258, quality:'best', allowfullscreen:'true', version:[9,115]}, flashvars);
          $(this).after(container).remove();
        });
		
		
		$('#body a[href*="vimeo.com"]').not($('#replies a')).each(function(){
			var container = $('<div/>');
			var src = "http://vimeo.com/moogaloop.swf?clip_id=" + this.href.match(/(\d+)/)[1] + "&amp;server=vimeo.com&amp;fullscreen=1&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=6BA222";
			$(container).flashembed({src:src, width: 460, height: 300, wmode: 'transparent', quality:'best', allowfullscreen:'true', scale:'showAll', version:[9,115]});
			$(this).after(container).remove();
		});
		
        $('#body a[href*="youtube.com"]').not($('#replies a')).each(function(){
         var container = $('<div/>');
         var src = "http://www.youtube.com/v/" + this.href.match(/v=(.+)/)[1];
         
         $(container).flashembed({src:src, width: 460, height: 300, wmode: 'transparent', quality:'best', allowfullscreen:'true', scale:'showAll', version:[9,115]});
		 $(this).after(container).remove();
        });
	},

    google_maps: function() {
		if (($google_map = $("#google_map")) && $google_map.length > 0) {
	    $google_map.googleMap(
				map.lat, 
				map.lng, 
				map.zoom, 
	      { 
	        controls: ["GSmallMapControl"], 
	        markers: [{lat: map.lat, lng: map.lng, txt: map.txt}]
	      }
	    );
	  }
	}, 
    
	menu_focus: function() {
		$("#menu>li").removeClass("hover");
		$(this).addClass("hover");
	},
	
	menu_blur: function() {
		$(this).removeClass("hover");
	},

	iehacks: function() {
		$("#menu>li").hover(website.menu_focus, website.menu_blur);
	}
};


website.form_validation = {
  
  valid: true, 
  
  // Expects a jQuery object
  setup: function(form) {

    var $form = form;
    
    var required = [];
    
    $("label.required", $form).each( function(i) {
      required[i] = $("#"+$(this).attr("for"));
    });
    
    $form.submit( function() {
      website.form_validation.validate(required, $form);
      return website.form_validation.valid;
    });    
  }, 
  
  validate: function(required, form) {
    var $form = form;

    var error_count = 0;
    
    $("#errorExplanation").remove();
    
    var $errorbox = $("<div id=\"errorExplanation\" class=\"errorExplanation\"><p>Please correct the following errors</p><ul></ul></div>");    
    
    $(required).each( function() {
      var $this = $(this);
      if ($this.val() == "" || $("option:selected", $this).val() == "") {
        error_count++;

        var field_name = $("label[for=" + $this.attr("id") + "]", $form).text().replace(/:/, "");
        $this.wrap("<em class=\"field_error\"></em>");
        $("ul", $errorbox).append("<li>" + field_name + " can't be blank</li>");
      } else {
        if ($this.parents("em").length > 0) {
          $error_surround = $this.parents("em");
          $("label[for=" + $this.attr("id") + "]", $form).after($this);
          $error_surround.remove();
        }        
      }
    });
    
    if (error_count > 0) {
      website.form_validation.valid = false;
      $form.before($errorbox);     
    } else {
      $errorbox.remove();
      website.form_validation.valid = true;
    }    
  }
};