if (!window.console) {
	window.console = {};
	window.console.log = function(){};
}

var DAYS_OF_THE_WEEK = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var MON_OF_THE_YEAR = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var MIME_LOOKUP = {
	'video/x-m4v' : 'M4V',
	'video/mp4' : 'MP4',
	'audio/mpeg3' : 'MP3'
}
var PrettyDuration = function(duration){
	var result = '';
	if (duration > 3600) {
		result = Math.floor(duration/3600) + ':';
		duration = duration - (Math.floor(duration/3600) * 3600);
	}
	result  = result + Math.floor(duration/60) + ':';
	duration = duration - (Math.floor(duration/60) * 60);
	return result + duration;
}
var PrettyFilesize = function(size){
	if (size > 1024*1024) 
		return Math.round(size / (1024*1024)) + ' MB';
	else if (size > 1024)
		return Math.round(size / 1024) + ' KB';
	else
		return size + ' B';
};


var ExternalHomePage = function(){
	Shadowbox.init({ 
		handleOversize: 'none', 
		skipSetup: true, 
		displayCounter: false, 
		displayNav: false, 
		initialHeight: 480, 
		initialWidth: 640,
		viewportPadding: 0,
		onOpen: function() {
				jQuery('#slideshowContainer').mouseenter();
				if (jQuery('#sb-wrapper').find('.close-button').length == 0) {
					jQuery('#sb-wrapper').append(jQuery('<img/>').attr({
						src: '/static_war/render/images/mediaplayers/closebox.png',
						'class': 'close-button'
					}).click(function(){
						Shadowbox.close();
					}));
				}
		},
		onClose: function(){ jQuery('#slideshowContainer').mouseleave(); }
	});
	this.searchHasFocus = false;
	this.setupNavigation();
	this.setupSearch();
	this.setupSlideshow();
	this.setupLowerContent();
	this.setupQuickLinks();
	// SBTWO-5026
	var oldSkinInit = Shadowbox.skin.init;
	var _this = this;
	Shadowbox.skin.init = function(){
		oldSkinInit();
		_this.setupSidebar();
	}; 
	this.setupMediaSearch();
	this.setupTwitter();
	jQuery('label').show();

  var setSidebarHeight = function(evt, isSmallscreen) {
    if (isSmallscreen) {
      jQuery('#sidebar').height('auto');
    } else {
      jQuery('#sidebar').height(jQuery('#centre').height());
    }
  };
  jQuery(document.body).bind('smallscreen', setSidebarHeight);
  setSidebarHeight(null, jQuery(document.body).hasClass('is-smallscreen'));
};

ExternalHomePage.prototype.setupSearch = function(){
	var _this = this;

	jQuery('#searchContainer').mouseover(function(){
		jQuery('#searchContainer .search-button').addClass('hover');

    	if (!jQuery(document.body).hasClass('is-smallscreen')) {
  			clearTimeout(_this.searchTimeout);
  			_this.searchTimeout = setTimeout(function(){
  				jQuery('#searchContainer ul').stop().fadeIn('fast');
  			}, 250);
    	}
	}).mouseout(function(){
		if (!_this.searchHasFocus) {
			jQuery('#searchContainer .search-button').removeClass('hover');

      		if (!jQuery(document.body).hasClass('is-smallscreen')) {
  				clearTimeout(_this.searchTimeout);
	  			_this.searchTimeout = setTimeout(function(){
	  				jQuery('#searchContainer ul').stop().fadeOut('fast');
	  			}, 250);
			}
		}
	});
	jQuery('#searchBox').focus(function(event){
		jQuery('#searchContainer label').hide();
		_this.searchHasFocus = true;
	}).blur(function(event){
		_this.searchHasFocus = false;
		jQuery('#searchContainer').mouseout();
		if (jQuery('#searchBox').val().length == 0)
			jQuery('#searchContainer label').show();
	});
	if (jQuery('#searchBox').val().length > 0)
		jQuery('#searchContainer label').hide();
				
	new NavigableList({
		inputElement: jQuery('#searchBox'),
		queryURL: '/sitebuilder2/api/go/redirects.htm?maxResults=6&prefix=',
		containerElement: jQuery('#search-suggestions'),
		selectFunction: function(li) {
			window.location = '/go/' + jQuery(li).find('.redirectpath').html()
				+ '?goSearchReferer=' + encodeURIComponent(window.location) 
				+ '&goSearchQuery=' + jQuery('#searchBox').val();
			jQuery('#searchContainer').submit(function(e){ e.preventDefault(); return false; });
			return false;
		}
	});
	jQuery('#searchContainer li').click(function(event){
		if (jQuery(this).attr('rel')){
			jQuery('#searchContainer li').removeClass('active');
			jQuery(this).addClass('active');
			jQuery('#searchBox').parent('form').attr('action','http://search.warwick.ac.uk/' + jQuery(this).attr('rel'))
		}
	});
	jQuery('#searchContainer li a').click(function(event){
		event.preventDefault();
		window.location = 'http://search.warwick.ac.uk/website' + '?q=' + jQuery('#searchBox').val();
	});

  var $searchContainer = jQuery('#searchContainer');
  var moveSearchBox = function(evt, isSmallscreen) {
    if (isSmallscreen) {
      if (jQuery('#alternate-search').length == 0) {
        jQuery('#centre').prepend(
          jQuery('<div id="alternate-search" />')
        );
      }

      jQuery('#alternate-search').append($searchContainer);
      jQuery('#searchContainer ul').show();
    } else {
      jQuery('#utility-container').append($searchContainer);
    }
  };

  jQuery(document.body).bind('smallscreen', moveSearchBox);
  if (jQuery(document.body).hasClass('is-smallscreen')) {
    moveSearchBox(null, true);
  }
};

ExternalHomePage.prototype.setupNavigation = function(){
  var handleSmallscreen = function(evt, isSmallscreen) {
    if (isSmallscreen) {
      jQuery('#main').css({ top: '50px' });

      jQuery('#navigation').unbind('mouseenter').unbind('mouseleave').unbind('click');
      jQuery('#navigation li a').unbind('focus');
    } else {
    	jQuery('#main').css({ top: '25px' });

      if (jQuery('#navigation li ul').length == 0) return;

    	jQuery('#navigation').mouseenter(jQuery.proxy(function(event){
    		clearTimeout(this.navigationTimeout);
    		this.navigationTimeout = setTimeout(function(){
    			jQuery('#main').stop().animate({ top: '150px' });
    		}, 250);		
    	}, this)).mouseleave(jQuery.proxy(function(event){
    		clearTimeout(this.navigationTimeout);
  
    		this.navigationTimeout = setTimeout(function(){
    			jQuery('#main').stop().animate({ top: '25px' });
    		}, 250);
    	}, this)).click(function(){
    		// for mouse-less devices
    		jQuery(this).mouseenter();
    	});
    	jQuery('#navigation li a').focus(function(){jQuery('#navigation').mouseenter();});
    }
  }

  jQuery(document.body).bind('smallscreen', handleSmallscreen);
  handleSmallscreen(null, jQuery(document.body).hasClass('is-smallscreen'));
};

ExternalHomePage.prototype.slideshowForward = function(){
	if (this.enableSlideshowAdvance) {
		var next = jQuery('#slideshowNavigation a.link.active').next('a.link');
		if (next.length == 0) {
			next = jQuery('#slideshowNavigation a.link:first');
		}
		next.click();
	}
};

ExternalHomePage.prototype.slideshowBack = function(){
	if (this.enableSlideshowAdvance) {
		var prev = jQuery('#slideshowNavigation a.link.active').prev('a.link');
		if (prev.length == 0) {
			prev = jQuery('#slideshowNavigation a.link:last');
		}
		prev.click();
	}
};

ExternalHomePage.prototype.setupSlideshowTimeout = function(){
	if (!this.slideshowAdvanceTimeout) {
		this.slideshowAdvanceTimeout = setTimeout(jQuery.proxy(function(){ 
			this.slideshowForward();  
			this.clearSlideshowTimeout();
			this.setupSlideshowTimeout();
		}, this), 10000);
	}
};

ExternalHomePage.prototype.clearSlideshowTimeout = function(){
	clearTimeout(this.slideshowAdvanceTimeout);
	this.slideshowAdvanceTimeout = null;
};

ExternalHomePage.prototype.setupSlideshow = function(){
	if (jQuery('#slideshowInner div.slide').length > 1){
		this.enableSlideshowAdvance = true;
		var _this = this;
		jQuery('#slideshowInner div.slide').each(function(index){
			jQuery(this).fadeTo(0,0).hide();
			jQuery('#slideshowNavigation a.right').before(
				jQuery('<a/>')
				.attr({
					'href':'#',
					'title':jQuery(this).find('h2 a').html(),
					'rel':jQuery(this).attr('id'),
					'class':'link'
				})
				.html('<img src="/static_war/images/shim.gif" alt="Story '+index+'" />')
				.click(function(event){
					event.preventDefault();
					if (!jQuery(this).hasClass('active')) {
						_this.enableSlideshowAdvance = false;
						var prev = jQuery('#' + jQuery('#slideshowNavigation a.link.active').attr('rel'));
						jQuery('#slideshowNavigation a.link.active').removeClass('active');
						jQuery(this).addClass('active');
						prev.animate({opacity: 0},'slow',function(){ jQuery(this).css('display','none'); });
						jQuery('#' + jQuery(this).attr('rel')).css('display','block').animate({opacity: 1},'slow',function(){
							_this.enableSlideshowAdvance = true;
						});
					}
				})
			)
		});
		jQuery('#slideshowNavigation a.right').click(jQuery.proxy(function(event){
			event.preventDefault();
			this.slideshowForward();
		}, this));
		jQuery('#slideshowNavigation a.left').click(jQuery.proxy(function(event){
			event.preventDefault();
			this.slideshowBack();
		}, this));
		jQuery('#slideshowContainer').mouseenter(jQuery.proxy(function(event){
			this.clearSlideshowTimeout();
			clearTimeout(this.slideshowTimeout);
			this.slideshowTimeout = setTimeout(function(){
				jQuery('#slideshowNavigation').stop().fadeIn('fast');
			}, 250);
		}, this)).mouseleave(jQuery.proxy(function(event){
			this.setupSlideshowTimeout();
			clearTimeout(this.slideshowTimeout);
			this.slideshowTimeout = setTimeout(function(){
				jQuery('#slideshowNavigation').stop().fadeOut('fast');
			}, 250);
		}, this));
	
		jQuery('#slideshowNavigation a.link:first').addClass('active');
		jQuery('#slideshowInner div.slide:first').fadeTo(0,1);
		this.setupSlideshowTimeout();
	}
};

ExternalHomePage.prototype.setupLowerContent = function(){
	var _this = this;
	jQuery('#lowerContent .container .image').mouseenter(function(){
		clearTimeout(_this.lowerContentTimeout);
		_this.lowerContentTimeout = setTimeout(jQuery.proxy(function(){
			jQuery(this).animate({opacity: 1 },250).animate({width: '462px'},'fast');
		}, this), 250);
	});
	jQuery('#lowerContent .container').mouseleave(function(){
		clearTimeout(_this.lowerContentTimeout);
		jQuery(this).children('div.image').stop().animate({width: '224px'},'fast').animate({opacity: 0.8},'fast');
	});

  var mobileLowerContent = function(evt, isSmallscreen) {
    if (isSmallscreen) {
      if (jQuery('#lowerContent .alternate-container').length == 0) {
        jQuery('#lowerContent .container').each(function(i, el) {
          var alt = jQuery('<div class="alternate-container" />');

          var $el = jQuery(el);

          if ($el.hasClass('left')) { alt.addClass('left'); }
          if ($el.hasClass('middle')) { alt.addClass('middle'); }
          if ($el.hasClass('right')) { alt.addClass('right'); }

          alt.append(jQuery('<div class="image" />').append($el.find('a.block').clone()));
          alt.append($el.find('.image > h3').clone());
          alt.append(jQuery('<p />').html($el.find('.image > .content').html()));

          alt.insertAfter($el);
        });
      }
    } 
  };

  jQuery(document.body).bind('smallscreen', mobileLowerContent);
  if (jQuery(document.body).hasClass('is-smallscreen')) {
    mobileLowerContent(null, true);
  }
};

ExternalHomePage.prototype.setupQuickLinks = function(){
	if (jQuery('#quickLinks').length == 0) return; 

	jQuery('#quickLinks .container > ul').append('<li><ul id="qlResults"></ul></li>');

	var links = jQuery('#quickLinks li li a');
	var searchFunction = function(){
		if (jQuery('#qlSearchBox').val().length > 0) {
			jQuery('#quickLinks .container > ul li').removeClass('active');
			jQuery('#qlResults').empty().parent().addClass('active');
			
			links.filter(function(){ 
				return jQuery(this).text().toLowerCase().indexOf(jQuery('#qlSearchBox').val().toLowerCase()) != -1 
			}).each(function(){
				var outerThis = this;
				if (jQuery('#qlResults li a').filter(function(){
					return jQuery(this).text().toLowerCase().indexOf(jQuery(outerThis).text().toLowerCase()) != -1;
				}).length == 0) {
					jQuery('#qlResults').append(
						jQuery('<li/>').append(
							jQuery('<a/>')
							.attr('href',jQuery(this).attr('href'))
							.html(jQuery(this).text().replace(new RegExp('(' + jQuery('#qlSearchBox').val() + ')','gi'), '<strong>$1</strong>'))
						)
					);
				}
			});
		} else {
			jQuery('#qlResults').empty();
		}
	}
	
	jQuery('#qlSearchBox').focus(function(event){
		jQuery('#quickLinks label').hide();
		if (jQuery('#qlSearchBox').val().length > 0) {
			searchFunction();
		}
	}).blur(function(){
		if (jQuery('#qlSearchBox').val().length == 0) {
			jQuery('#quickLinks label').show();
		}
	}).delayedObserver(searchFunction, 0.1);
	jQuery('#quickLinks .container > ul > li > a').click(function(event){
		event.preventDefault();
		jQuery('#quickLinks .container > ul li').removeClass('active');
		jQuery(this).parent().addClass('active');
		new WCookie('exthomepage-savedQuickLinkSection',jQuery(this).attr('rel'),72);
	});
	if (jQuery('#qlSearchBox').val().length > 0) {
		jQuery('#quickLinks label').hide();
		searchFunction();
	}
	var savedQuickLinkSection = new WCookie('exthomepage-savedQuickLinkSection').value;
	if (savedQuickLinkSection)
		jQuery(jQuery.grep(jQuery('#quickLinks div.container > ul > li > a'), function(link){ return jQuery(link).attr('rel') == savedQuickLinkSection; })[0]).click();
};

ExternalHomePage.prototype.setupSidebar = function(){
	jQuery.ajax('/sitebuilder2/api/dataentry/entries.json?page=/&sort=title&num=-1',{
		success: jQuery.proxy(function(data){
			this.renderVideos(data);
			this.renderAudio(data);
		},this),
		error: function(obj, status, error){ console.log(status); }
	});
};

ExternalHomePage.prototype.renderVideos = function(data){
	jQuery.each(jQuery.grep(data.items, function(item){ return item.title.indexOf('D Video') != -1; }), function(index, item){
		item.metadata = jQuery.parseJSON(item.metadata);
		jQuery('#warwickVideoContainer div.allVideos').append(
			jQuery('<div/>').attr({'class':'video indexed', id:'warwick-video'+index}).css({backgroundImage: 'url('+item.url.href+'?preview&maxWidth=165)'}).append(
				jQuery('<a/>').attr('href',item.url.href).data('index', index)
			)
		);
		jQuery('#warwickVideoContainer div.allText').append(
			jQuery('<div/>').attr({'class':'text indexed',id:'warwick-video-text'+index}).append(
				jQuery('<h6/>').append(
					jQuery('<a/>').attr('href',item.url.href).html(item.metadata.title).data('index', index)
				)
			).append(
				jQuery('<p/>').html(item.content)
			)
		);
	});
	var itemCount = jQuery('#warwickVideoContainer .video').length;
	if (itemCount <= 1) {
		jQuery('#warwickVideoContainer .control').addClass('none');
	} else {
		jQuery('#warwickVideoContainer .text').fadeTo(0,0,function(){ jQuery(this).hide(); });
		jQuery('#warwickVideoContainer .left').click(jQuery.proxy(function(event){
			event.preventDefault();
			this.videoBack();
		}, this));
		jQuery('#warwickVideoContainer .right').click(jQuery.proxy(function(event){
			event.preventDefault();
			this.videoForward();
		}, this));

		jQuery('#warwickVideoContainer .left').addClass('none');
		jQuery('#warwickVideoContainer .allVideos').width(itemCount * 160);
	}
	jQuery('#warwickVideoContainer .indexed a').click(jQuery.proxy(function(event){
		event.preventDefault();
		Shadowbox.open({
			warwick_videoID: 'warwick-video-shadowbox' + jQuery(event.target).data('index'),
			warwick_videoURL: jQuery(event.target).attr('href'),
			content: this.getShadowboxVideoContent(
				jQuery(event.target).data('index'), 
				jQuery('#warwick-video-text'+jQuery(event.target).data('index')).find('a').html(), 
				jQuery(event.target).attr('href')
			),
			height: 600,
			width: 800,
			player: "html",
			options: {onFinish: jQuery.proxy(this.getShadowboxVideoContentMetadata, this) }
		});
	}, this));
	jQuery('#warwickVideoContainer .video:first').addClass('active');
	jQuery('#warwickVideoContainer .text:first').show().fadeTo(0,1,function(){
		// IE is full of suck
		if (this.style.removeAttribute)
				this.style.removeAttribute("filter");
	});
};

ExternalHomePage.prototype.videoBack = function(){
	var activeVideoID = jQuery('#warwickVideoContainer .active').attr('id');
	if(jQuery('#warwickVideoContainer .video:first').attr('id') != activeVideoID){
		jQuery('#warwickVideoContainer .active').removeClass('active').prev('div.video').addClass('active');
		jQuery('#warwickVideoContainer .allVideos').animate({left: '+=160'},'fast');
		jQuery('#warwick-video-text'+activeVideoID.replace('warwick-video','')).animate({opacity: 0},'fast',function(){ jQuery(this).hide(); })
		.prev('div.text').show().animate({opacity: 1},'fast',function(){
			// IE is full of suck
			if (this.style.removeAttribute)
				this.style.removeAttribute("filter");
		});
		jQuery('#warwickVideoContainer .right').removeClass('none');
		if(jQuery('#warwickVideoContainer .video:first').attr('id') == jQuery('#warwickVideoContainer .active').attr('id')){
			jQuery('#warwickVideoContainer .left').addClass('none');
		}
	}
};

ExternalHomePage.prototype.videoForward = function(){
	var activeVideoID = jQuery('#warwickVideoContainer .active').attr('id');
	if(jQuery('#warwickVideoContainer .video:last').attr('id') != activeVideoID){
		jQuery('#warwickVideoContainer .active').removeClass('active').next('div.video').addClass('active');
		jQuery('#warwickVideoContainer .allVideos').animate({left: '-=160'},'fast');
		jQuery('#warwick-video-text'+activeVideoID.replace('warwick-video','')).animate({opacity: 0},'fast',function(){ jQuery(this).hide(); })
		.next('div.text').show().animate({opacity: 1},'fast',function(){
			// IE is full of suck
			if (this.style.removeAttribute)
				this.style.removeAttribute("filter");
		});
		jQuery('#warwickVideoContainer .left').removeClass('none');
		if(jQuery('#warwickVideoContainer .video:last').attr('id') == jQuery('#warwickVideoContainer .active').attr('id')){
			jQuery('#warwickVideoContainer .right').addClass('none');
		}
	}
};

ExternalHomePage.prototype.getShadowboxVideoContent = function(index, title, href){
	var container = jQuery('<div/>');
	container.append(
		jQuery('<div/>').attr({'id':'warwick-video-shadowbox' + index, 'class': 'shadowbox video'}).append(
			jQuery('<h5/>').html(title)
		).append(
			jQuery('<p/>').attr('class','created').html('&nbsp;')
		).append(
			jQuery('<div/>').attr('class','video')
		).append(
			jQuery('<p/>').attr('class','description').html('&nbsp;')
		).append(
			jQuery('<iframe/>').attr({
				scrolling: 'no',
				frameborder: '0',
				allowtransparency: 'true',
				style: 'border: none; overflow: hidden; width: 450px; height: 30px;',
				src: 'http://www.facebook.com/plugins/like.php?href='
					+ encodeURIComponent(href) 
					+ '&layout=standard&show_faces=false&width=450&action=like&font=nobile&colorscheme=light&height=25'
			})
		).append(
			jQuery('<p/>').append(
				jQuery('<a/>').attr('href', href + '?forceOpenSave=true').html('Download')
			).append(
				jQuery('<span/>').attr('class','meta')
			)
		)
	);
	return container.html();
};

ExternalHomePage.prototype.getVideoContent = function(data){
	var insertFlash = function(){
		var object = new FlashObject("/static_war/render/flvplayer-4.2.swf", "obj972704", data.metadata.width, data.metadata.height + 20);
		object.addVariable("file", data.url);
		object.addVariable("stretching", "uniform");
		object.addVariable("width", data.metadata.width);
		object.addVariable("height", data.metadata.height);
		object.addParam("allowfullscreen", "true");
		object.addVariable("showdownload", "false");
		object.addVariable('autostart','true');
		object.align = "left";
		return object.getHTML();
	};

	var videoString = "<video width='"
		+ data.metadata.width
		+ "' height='"
		+ data.metadata.height
		+ "' controls='controls' autoplay>";

	var vidEl = document.createElement('video');
	var supportsVideo = !!vidEl.canPlayType;
	if (supportsVideo) {
		if (!data.metadata.alternateRenditions)
			data.metadata.alternateRenditions = [];

		var supportsAnyType = jQuery.grep([vidEl.canPlayType(data.mimeType)].concat(jQuery.map(data.metadata.alternateRenditions, function(ren){ 
			return vidEl.canPlayType(ren.mimeType); 
		})), function(canPlay){ return canPlay == "probably" || canPlay == "maybe"; }).length > 0;

		if (supportsAnyType) {

			videoString += "<source src='" + data.url + "' type='" + data.mimeType + "' >";

			if (data.metadata.alternateRenditions && data.metadata.alternateRenditions.length > 0) {
				jQuery.each(data.metadata.alternateRenditions, function(index, ren) {
					videoString += "<source src='" + ren.url + "' type='" + ren.mimeType + "' >";
				});
			}
			videoString += "</video>";
			return videoString;
		} else {
			return insertFlash();
		}
	} else {
		return insertFlash();
	}
};

ExternalHomePage.prototype.getShadowboxVideoContentMetadata = function(obj){
	var container = jQuery('#' + obj.warwick_videoID);
	var videoURL = obj.warwick_videoURL;
	if(videoURL.indexOf('http://www2.warwick.ac.uk')==0)
		videoURL = videoURL.replace('http://www2.warwick.ac.uk','');

	var processFunction = function(data){
		var _this = this;
		return function() {
			var uploadedDate = new Date(data.contentUpdated.date);
			container.find('p.created').html(
				uploadedDate.getHours() + ":" + uploadedDate.getMinutes() + " "
				+ DAYS_OF_THE_WEEK[uploadedDate.getDay()] + " " + uploadedDate.getDate() + " "
				+ MON_OF_THE_YEAR[uploadedDate.getMonth()] + " " + uploadedDate.getFullYear()
			);
			container.find('div.video').html(_this.getVideoContent(data));
			container.find('p.description').html((data.description)?data.description:'&nbsp;');
			container.find('span.meta').html(
				' (' + MIME_LOOKUP[data.mimeType] +' format, ' 
				+ PrettyDuration(data.metadata.duration) + ', ' 
				+ PrettyFilesize(data.fileSize) + ')');
		}(data);
	};

	jQuery.getJSON('/sitebuilder2/api/page.json?page=' + encodeURIComponent(videoURL), jQuery.proxy(processFunction, this));
};

ExternalHomePage.prototype.renderAudio = function(data){
	jQuery.each(jQuery.grep(data.items, function(item){ return item.title.indexOf('E Audio') != -1; }), function(index, item){
		item.metadata = jQuery.parseJSON(item.metadata);
		jQuery('#warwickAudioContainer').append(
			jQuery('<p/>').append(
				jQuery('<a/>').attr('href',item.url.href).html(item.content).data('index', index)
			)
		);
	});
	jQuery('#warwickAudioContainer p a').click(jQuery.proxy(function(event){
		event.preventDefault();
		Shadowbox.open({
			warwick_audioID: 'warwick-audio-shadowbox' + jQuery(event.target).data('index'),
			warwick_audioURL: jQuery(event.target).attr('href'),
			content: this.getShadowboxAudioContent(jQuery(event.target).data('index'), jQuery(event.target).html(), jQuery(event.target).attr('href')),
			player: "html",
			height: 300,
			width: 800,
			options: {onFinish: this.getShadowboxAudioContentMetadata }
		});
	}, this));

};

ExternalHomePage.prototype.getShadowboxAudioContent = function(index, title, href){
	var container = jQuery('<div/>');
	container.append(
		jQuery('<div/>').attr({'id':'warwick-audio-shadowbox' + index, 'class': 'shadowbox audio'}).append(
			jQuery('<h5/>').html(title)
		).append(
			jQuery('<p/>').attr('class','created').html('&nbsp;')
		).append(
			this.getAudioContent(href)
		).append(
			jQuery('<iframe/>').attr({
				scrolling: 'no',
				frameborder: '0',
				allowtransparency: 'true',
				style: 'border: none; overflow: hidden; width: 450px; height: 40px;',
				src: 'http://www.facebook.com/plugins/like.php?href='
					+ encodeURIComponent(href) 
					+ '&layout=standard&show_faces=false&width=450&action=like&font=nobile&colorscheme=light&height=35'
			})
		).append(
			jQuery('<p/>').append(
				jQuery('<a/>').attr('href', href + '?forceOpenSave=true').html('Download')
			).append(
				jQuery('<span/>').attr('class','meta')
			)
		)
	);
	return container.html();
};

ExternalHomePage.prototype.getAudioContent = function(url){
	var insertFlash = function(){
		var object = new FlashObject("/static_war/render/audio-player.swf", "obj972704", "290", "24");
		object.addParam("wmode","transparent");
		object.addParam("menu","false");
		object.addParam("play","true");
		object.addParam("FlashVars","playerID=1&amp;bg=0xf8f8f8&amp;leftbg=0xeeeeee&amp;lefticon=0x666666"
			+ "&amp;rightbg=0xcccccc&amp;rightbghover=0x999999&amp;righticon=666666"
			+ "&amp;righticonhover=0xFFFFFF&amp;text=0x666666&amp;slider=0x666666"
			+ "&amp;track=0xFFFFFF&amp;border=0x666666&amp;loader=0x9FFFB8&amp;autostart=yes" 
			+ "&amp;soundFile=" + url);
		object.align = "left";

		return object.getHTML();
	};

//	var audEl = document.createElement('audio');
//	audEl.setAttribute('controls', 'controls');
//	audEl.setAttribute('autoplay', 'autoplay');
//	audEl.setAttribute('src', url);
//
//	var supportsAudio = !!audEl.canPlayType;
//	if (supportsAudio && audEl.canPlayType('audio/mpeg;')) {
//		return audEl;
//	} else {
//		return insertFlash();
//	}

	return insertFlash(); // can't get native audio to work in Chrome

};

ExternalHomePage.prototype.getShadowboxAudioContentMetadata = function(obj){
	var container = jQuery('#' + obj.warwick_audioID);
	var audioURL = obj.warwick_audioURL;
	if(audioURL.indexOf('http://www2.warwick.ac.uk')==0)
		audioURL = audioURL.replace('http://www2.warwick.ac.uk','');

	jQuery.getJSON('/sitebuilder2/api/page.json?page=' + encodeURIComponent(audioURL), function(data){
		return function() {
			var uploadedDate = new Date(data.contentUpdated.date);
			container.find('p.created').html(
				uploadedDate.getHours() + ":" + uploadedDate.getMinutes() + " "
				+ DAYS_OF_THE_WEEK[uploadedDate.getDay()] + " " + uploadedDate.getDate() + " "
				+ MON_OF_THE_YEAR[uploadedDate.getMonth()] + " " + uploadedDate.getFullYear()
			);
			container.find('span.meta').html(
				' (' + MIME_LOOKUP[data.mimeType] +' format, ' 
				+ PrettyDuration(data.metadata.duration) + ', ' 
				+ PrettyFilesize(data.fileSize) + ')');
		}(data);
	});
};

ExternalHomePage.prototype.setupMediaSearch = function(){
	if (jQuery('#mediaSearchContainer').length == 0) return;

	jQuery('#mediaSearchContainer form').submit(function(event){
		event.preventDefault();
	});

	var searchFunction = function(_this){
		if (jQuery('#mediaSearchBox').val().length > 0) {
			jQuery('#mediaSearchResults').css({display: 'block'}).html('<img src="/static_war/images/tab-spinner.gif" alt="Loading" />');
			jQuery.getJSON(
				'/ajax/lvsch/query.json',
				'indexSection=sitebuilder&fileFormat=video&fileFormat=audio&q=' + jQuery('#mediaSearchBox').val() + '*', 
				function(data){
					if (data.results.length == 0) {
						jQuery('#mediaSearchResults').html('No results');
					} else {
						jQuery('#mediaSearchResults').empty();
						for (var i=0, total=Math.min(4,data.results.length); i<total; i++){
							var itemDate = new Date(data.results[i].lastModified);
							var isVideo = data.results[i].link.indexOf('.mp3')==-1;
							var link = jQuery('<a/>').attr('href',data.results[i].link).html(data.results[i].title)
							var container = jQuery('<div/>').attr('class','searchResult').append(
								jQuery('<p/>').append(link)
							);
							if (isVideo){
								link.mousedown({i:i}, function(event){
									var i = event.data.i;
									event.preventDefault();
									Shadowbox.open({
										warwick_videoID: 'warwick-video-shadowbox' + i,
										warwick_videoURL: data.results[i].link,
										content: _this.getShadowboxVideoContent(i, data.results[i].title, data.results[i].link),
										player: "html",
										height: 600,
										width: 800,
										options: {onFinish: jQuery.proxy(_this.getShadowboxVideoContentMetadata, _this) }
									});
								});
								container.append(
									jQuery('<p/>').attr('class','meta').html(
										"Video - "
										+ itemDate.getDate() + " " 
										+ MON_OF_THE_YEAR[itemDate.getMonth()] + " " 
										+ itemDate.getFullYear()
									)
								);
							} else {
								link.mousedown({i:i}, function(event){
									var i = event.data.i;
									event.preventDefault();
									Shadowbox.open({
										warwick_audioID: 'warwick-audio-shadowbox' + i,
										warwick_audioURL: data.results[i].link,
										content: _this.getShadowboxAudioContent(i, data.results[i].title, data.results[i].link),
										player: "html",
										height: 300,
										width: 800,
										options: {onFinish: jQuery.proxy(_this.getShadowboxAudioContentMetadata, _this) }
									});
								});
								container.append(
									jQuery('<p/>').attr('class','meta').html(
										"Audio - "
										+ itemDate.getDate() + " " 
										+ MON_OF_THE_YEAR[itemDate.getMonth()] + " " 
										+ itemDate.getFullYear()
									)
								);
							}
							jQuery('#mediaSearchResults').append(container);
						}
						jQuery('#mediaSearchResults').append(
							jQuery('<p/>').append(
								jQuery('<a/>')
									.attr('href','http://search.warwick.ac.uk/website?indexSection=sitebuilder&fileFormat=video&fileFormat=audio&q=' + jQuery('#mediaSearchBox').val() + '*')
									.html('More results')
							)
						);
					}
				}
			);
		} else {
			jQuery('#mediaSearchResults').css({display: 'none'});
		}
	}

	jQuery('#mediaSearchBox').focus(jQuery.proxy(function(event){
		jQuery('#mediaSearchContainer label').hide();
		if (jQuery('#mediaSearchBox').val().length > 0) {
			searchFunction(this);
		}
	}, this)).blur(function(){
		if (jQuery('#mediaSearchBox').val().length == 0) {
			jQuery('#mediaSearchContainer label').show();
		}
		setTimeout(function(){ jQuery('#mediaSearchResults').css({display: 'none'}); }, 100);
	}).delayedObserver(jQuery.proxy(function(){ searchFunction(this); }, this));
	if (jQuery('#mediaSearchBox').val().length > 0) {
		jQuery('#mediaSearchContainer label').hide();
		searchFunction();
	}

};

ExternalHomePage.prototype.setupTwitter = function(){
	if (jQuery('#warwickTwitterContainer').length == 0) return;

	jQuery.getJSON('http://api.twitter.com/1/statuses/user_timeline/warwickuni.json?count=20&include_entities=true&include_rts=0&callback=?', function(data){
		var count = 0;
		jQuery.each(data, function(index, item){
			if (count <= 2){
				var htmlString = item.text;
				if(htmlString.charAt(0) != '@') {
					if(item.entities) {
						if(item.entities.hashtags && item.entities.hashtags.length > 0){
							jQuery.each(item.entities.hashtags, function(i, obj){
								htmlString = htmlString.replace(
									new RegExp("#" + obj.text,"g"),
									"<a target='_blank' href='http://www.twitter.com/search?q=" + obj.text + "'>#" + obj.text + "</a>")
							});
						}
						if(item.entities.urls && item.entities.urls.length > 0){
							jQuery.each(item.entities.urls, function(i, obj){
								htmlString = htmlString.replace(
									new RegExp(obj.url,"g"),
									"<a target='_blank' href='" + obj.url + "'>" + obj.url + "</a>")
							});
						}
						if(item.entities.user_mentions && item.entities.user_mentions.length > 0){
							jQuery.each(item.entities.user_mentions, function(i, obj){
								htmlString = htmlString.replace(
									new RegExp("@" + obj.screen_name,"g"),
									"<a target='_blank' href='http://www.twitter.com/" + obj.screen_name + "'>@" + obj.screen_name + "</a>")
							});
						}
					}
					jQuery('#warwickTwitterContainer').append(
						jQuery('<p/>').html(htmlString)
					)
					count = count + 1;
				}
			}
		});
	})
};



jQuery(document).ready(function(){ new ExternalHomePage(); });

