// JavaScript Document

// requires jquery-latest.min.js

// written by Suzie Blackman 7 March 2008
// Last update 24 June 2007

// USAGE 

/* 
Displaying larger versions of images with credit lines.
*/

// DEPLOYMENT

/*

* example /stives/exhibitions/maeckelberghe/default.shtm

* requires jquery-latest.min.js

* Add the script to the document:
<script src="/javascripts/jquery.tateenlargeimg.js" type="text/javascript"></script>

* Add HTML in the form:
<div class="tate_enlarge_img">
<a href="[URL of large image]">
<img alt="[ALT text here]" height="158" src="/images/cms/xib/13261w_margomaeckelberghecoastalreflections.jpg" width="272" />
<span class="credit">[Full credit line]</span>
<span class="tee_enlarge_link">enlarge</span></a></div>

*/

 
// CUSTOM CSS
// ~~~~~~~~~~

// All the necessary CSS is in master_scalable.css but it can be customised.

// For the 'pop-up'
// .tee_loading - the div that displays the loading graphic
// .tee_enlarged - the div that displays the resized image and credit
// .tee_enlarged .credit - the credit line for the enlarged image
// .tee_enlarged .tee_close div that holds the close link
// .tee_enlarged .tee_close a - link to close the enlarged image

// For the static pgae:
// .tee_enlarge_link - link below the small image
// .tate_enlarge_img - wrapper for enlargable images
// .tate_enlarge_img .credit - credit line for enlargable images


// COMPATIBILITY

/*

* IE5.5 and below, not functional

* Issue calculatuing width of enlarge div

*/

// GLOBAL VARIABLES
// ~~~~~~~~~~~~~~~~

// template width, can be overridden locally
var tate_enlarge_content_width = 749;
// any left-hand padding, can be overridden locally
var tate_enlarge_content_width_offset = 0;
// don't cover the header bar etc, can be overridden locally
var tate_enlarge_content_height_offset = 100;
// holds dimensions of original, small image
var img_h = 0;
var img_w = 0;
// default dimensions for enalarged image (to be corrected in individual cases)
var lg_img_h = 512;
var lg_img_w = 512;
// default dimensions for smaller image (to be corrected in individual cases)
var sm_img_h = 128;
var sm_img_w = 128;
// default dimensions for multimedia (to be corrected in individual cases)
var av_h = 320;
var av_w = 480;
// holds dimensions of overlay box when displaying large image
var img_box_h = 0;
var img_box_w = 0;
// holds dimensions of overlay box when displaying multimedia
var av_box_h = 0;
var av_box_w = 0;
// holds dimensions of caption when displaying large image
var img_cap_h = 0;
var img_cap_w = 0;
// holds dimensions of caption when displaying multimedia
var av_cap_h = 0;
var av_cap_w = 0;
// holds dimensions of 'show multimedia' button
var av_link_h = 0;
var av_link_w = 0;

// file paths for the FLV content
var mp4 = "";
var videodata = {
'1.mp4': ["42608772001", "Marcel Duchamp, 'From or by Marcel Duchamp or Rose Selavy (The Box in a Valise)', c.1943"],
'2.mp4': ["42608817001", "Frank Stella, 'Island No. 10, Palmito Ranch, Sabine Pass, Hampton Roads, New Madrid, and Delaware Crossing', 1962"],
'3.mp4': ["42608816001", "Jim Dine, 'The Studio (Red Devil Color Chart No. 1)', 1963"],
'4.mp4': ["42602388001", "Ellsworth Kelly, 'Colors for a Large Wall', 1951"],
'5.mp4': ["42612347001", "Yves Klein, 'Yves Peintures', 1954"],
'6.mp4': ["42617075001", "Andy Warhol, '[No Title] (From Marilyn, 9 Prints)', 1967"],
'7.mp4': ["42608815001", "Vitrine exhibit: 'The Law of the Simultaneous Contrast of Colours'"],
'8.mp4': ["42608814001", "Gerhard Richter, '1025 Colours', 1974"],
'9.mp4': ["42617073001", "On Kawara, 'Today' Series"],
'10.mp4': ["42608813001", "Alighiero Boetti, 'Oro Longchamp', c.1968; 'Verde Ascot 1 288 6631', c.1968; 'Rosso Palermo', 1967"],
'11.mp4': ["42608812001", "Donald Judd, 'Untitled (DJ-85-51)', 1985"],
'12.mp4': ["42617070001", "Jan Dibbets, 'Colour Studies', 1970s"],
'13.mp4': ["42612344001", "Dan Flavin, 'Untitled (to Don Judd, colorist), 1-5', 1987"],
'14.mp4': ["42612343001", "John Baldessari, 'Six Colorful Inside Jobs', 1977"],
'15.mp4': ["42617067001", "Vitrine exhibit: 'The British Colour Council Dictionary of Colour Standards', 1951[1934]"],
'16.mp4': ["42608807001", "David Batchelor, 'I Love King's Cross and King's Cross Loves Me, 08', 2002-07"],
'17.mp4': ["42612341001", "Sherrie Levine, 'Salubra #2', 2007"],
'18.mp4': ["42602383001", "Byron Kim, 'Synecdoche', 1991"],
'19.mp4': ["42617064001", "Jim Lambie, 'Zobop!', 2006"],
'20.mp4': ["42602382001", "Carrie Mae Weems, 'Blue Black Boy 1988 (from) Colored People series', 1987-1988"],
'21.mp4': ["42617062001", "Cory Arcangel, 'Colors', 2005"],
'22.mp4': ["42602381001", "Vitrine exhibit: Joseph Albers, 'Interaction of Color', Yale, 1963"],
'23.mp4': ["42612339001", "Angela Bulloch, 'Ideation and Reflection', 2003"],
'about.mp4': ["42602380001", "About the exhibition"],
'installing.mp4': ["/liverpool/exhibitions/colourchart/xml/lambie-installing.xml", "Installing Jim Lambie's 'Zobop!' at Tate Liverpool"]
};

// apply action to 'close' button
function close_button(){
	$(".tee_enlarged .tee_close a, #shadebox").click(function () { 
		$('.tip, #objview').remove();
		$('#shadebox, .tee_enlarged').fadeTo(400,0,function(){
			$('#shadebox').css('display','none');
	      	$(".tee_enlarged").remove();
			// Show problematic elements
			$('embed, object, select').css({ 'visibility' : 'visible' });
		});											
		return false;
    });	
} // close_button ends


// show AV content (to switch from large image view)
function av_button(){
	$(".tee_enlarged .tee_av_link").css({'top':(lg_img_h+40)+'px'});
	// enable the rollover effect on the AV button
	$(".tee_enlarged .tee_av_link").append('<span class="topdisc"></span>');
	$(".tee_enlarged .tee_av_link").hover(function(e) { // display a 'tool tip' on mouseover
		$('body').append('<div class="tip tip3">Watch the multimedia<br />commentary on this work</div>');
		var tipL = ($(".tee_enlarged .tee_av_link").offset().left - $(".tip3").outerWidth()) + "px";
		var tipT = e.pageY + "px";
		$('.tip3').css({'top':tipT,'left':tipL}).stop(true,true).fadeIn(200); 
		$('.tee_enlarged .tee_av_link .topdisc').stop(true,true).fadeOut(200);
	},function(){
		$('.tee_enlarged .tee_av_link .topdisc').stop(true,true).fadeIn(200);
		$('.tip3').stop(true,true).fadeOut(200,function(){$('.tip3').remove();});
	});
	
	$(".tee_enlarged .tee_av_link, .tee_enlarged .topdisc").click(function() { // reshape box and contents to display av
		$('.tip').remove();
		var top_position = Math.max(getPageScroll() + ((getWindowHeight() - (av_box_h+2))/ 2), tate_enlarge_content_height_offset);
		var left_position = Math.max((tate_enlarge_content_width - (av_box_w+2)) / 2, tate_enlarge_content_width_offset);
		$(".tee_enlarged .tee_av_link").stop(true,true).fadeOut(100);
		$(".tee_enlarged .credit").stop(true,true).animate({'width':av_cap_w+'px','top':(av_h+40)+'px','left':(sm_img_w+32)+'px'},300,'swing');
		$(".tee_enlarged img").stop(true,true).animate({'width':sm_img_w+'px','height':sm_img_h+'px','top':(av_h+40)+'px'},300,'swing').addClass('smallImg');
		$(".tee_enlarged").stop(true,true).animate({'width':av_box_w+'px','height':av_box_h+'px','top':top_position+'px','left':left_position+'px'},300,'swing',function(){
			expand_image(); // bind switching event to thumbnail image;
			if (videodata.hasOwnProperty(mp4)) { 
				var theobject = getvideoobject( videodata[mp4][0] ); 
				$('.tee_enlarged').append('<div id="objview"></div>');
				$('#objview').html(theobject);
				brightcove.createExperiencesPostLoad();
				} 
 		});
		return false;
    });	
} // av_button ends

// enlarge image (to switch from multimedia view)
function expand_image(){
	$('.smallImg').hover(function(e) { // display 'tool tip' on mouseover
		$('body').append('<div class="tip tip4">View larger image</div>');
		var tipL = ($('.smallImg').offset().left + sm_img_w + 2) + "px";
		var tipT = e.pageY + "px";
		$('.tip4').css({'top':tipT,'left':tipL}).stop(true,true).fadeIn(200); 
	  },function(){
		$('.tip4').stop(true,true).fadeOut(200,function(){$('.tip4').remove();});
	  });
			
	$('.smallImg').click(function(){ // rearrange elements on click
  	  	$('.tip, #objview').remove();
		var top_position = Math.max(getPageScroll() + ((getWindowHeight() - (img_box_h+2))/ 2), tate_enlarge_content_height_offset);
		var left_position = Math.max((tate_enlarge_content_width - (img_box_w+2)) / 2, tate_enlarge_content_width_offset);
		$(".tee_enlarged").stop(true,false).animate({'width':img_box_w+'px','height':img_box_h+'px','top':top_position+'px','left':left_position+'px'},300,'swing');
		$(".tee_enlarged .credit").stop(true,false).animate({'width':img_cap_w+'px','top':(lg_img_h+40)+'px','left':'15px'},300,'swing',function(){
			$(".tee_enlarged .tee_av_link").stop(true,true).fadeIn(100);
			// av_button();
		});
		$(".tee_enlarged img").stop(true,false).animate({'width':lg_img_w+'px','height':lg_img_h+'px','top':'25px'},300,'swing').unbind().removeClass('smallImg');
	});	
} // expand_image ends

// pass this function the id of the BrightCove video and it will return you video object to be embedded
function getvideoobject( videoid ) {

		// create a new video object
		return $('<!-- Start of Brightcove Player --><div style="display:none"></div><!-- By use of this code snippet, I agree to the Brightcove Publisher T and C found at http://corp.brightcove.com/legal/terms_publisher.cfm. --><object id="myExperience' + videoid + '" class="BrightcoveExperience"><param name="bgcolor" value="#FFFFFF" /><param name="width" value="480" /><param name="height" value="320" /><param name="playerID" value="28915011001" /><param name="publisherID" value="1854890877"/><param name="isSlim" value="true" /><param name="@videoPlayer" value="' + videoid + '" /></object><!-- End of Brightcove Player -->');

} // end function getvideoobject( thehtml )

//initialisation funciton 
function init_tate_enlarge_img(){

	// add the div which will overlay the page contents when the enlarge box opens
	$('body').append('<div id="shadebox"></div>');
	// fix height of the shadebox
	$(window).resize(function(){ $('#shadebox').css('height',$(document).height()+'px'); });

	// look for class tate_enlar_img and bind events to the <a>
	// add an enlarge text to the end of the credit
	$(".tate_enlarge_img").each(function(index){

		// create the 'tool tips' on mouseover
		$(".tate_enlarge_img:eq("+index+") img").hover(function(e) { 
		  $('body').append('<div class="tip tip0">View larger image</div>');
		  var tipL = ($(".tate_enlarge_img:eq("+index+") img").offset().left - $(".tip0").outerWidth()) + "px";
		  var tipT = e.pageY + "px";
		  $('.tip0').css({'top':tipT,'left':tipL}).stop(true,true).fadeIn(200); 
		},function(){
		  $('.tip0').stop(true,true).fadeOut(200,function(){$('.tip0').remove();});
		});

		$(".tate_enlarge_img:eq("+index+") .magnify").hover(function(e) { 
		  $('body').append('<div class="tip tip1">View larger image</div>');
		  var tipL = ($(".tate_enlarge_img:eq("+index+") .magnify").offset().left - $(".tip1").outerWidth()) + "px";
		  var tipT = e.pageY + "px";
		  $('.tip1').css({'top':tipT,'left':tipL}).stop(true,true).fadeIn(200); 
		},function(){
		  $('.tip1').stop(true,true).fadeOut(200,function(){$('.tip1').remove();});
		});
	
		$(".tate_enlarge_img:eq("+index+") .tee_av_link").hover(function(e) { 
		  $('body').append('<div class="tip tip2">Watch the multimedia<br />commentary on this work</div>');
		  var tipL = ($(".tate_enlarge_img:eq("+index+") .tee_av_link").offset().left - $(".tip2").outerWidth()) + "px";
		  var tipT = e.pageY + "px";
		  $('.tip2').css({'top':tipT,'left':tipL}).stop(true,true).fadeIn(200); 
		},function(){
		  $('.tip2').stop(true,true).fadeOut(200,function(){$('.tip2').remove();});
		});

		// check if there's a multimedia link
		var isAV = false; // no multimedia link (default)
		if ($(".tate_enlarge_img:eq("+index+") .img").is(":has('.tee_av_link')")) { isAV = true; }
				
		// bind action to 'enlarge image' links
		$(this).children(".img").children(".tee_enlarge_link").click(function(){
			create_overlay(index,'img',isAV);
			// disable the link
			return false;
		});
		
		// bind action to 'enlarge image' links
		if (isAV) { $(this).children(".img").children(".tee_av_link").click(function(){
			create_overlay(index,'av',isAV);
			// disable the link
			return false;
			});
		}
	});
} // init_tate_enlarge_img ends


// bind actions to links to create overlay 
function create_overlay(index,type,isAV){

	// get image attributes
	var img_url = $(".tate_enlarge_img:eq("+index+") .tee_enlarge_link").attr("href");
	var credit = $(".tate_enlarge_img:eq("+index+") .credit").html();
	var alt = $(".tate_enlarge_img:eq("+index+") .img img").attr("alt");
					
	//destroy all previous instances
	$(".tee_loading").remove();
	$(".tee_enlarged").remove();
	$(".tip").remove();
		
	// Hide problematic elements
	$('embed, object, select').css({ 'visibility' : 'hidden' });
		
	// place a shade over the background
	$('#shadebox').css('height',$(document).height()+'px').fadeTo(200,0.7,function(){
		$('#shadebox').css('display','block');
		
		// create the loading image
		$("body").append("<div class='tee_loading'><span>Loading</span></div>");	
		// position it
		$(".tee_loading").tee_centre(0);
		//reveal it
		$(".tee_loading").show();
			
		// work out image dimensions at different scales
		img_w = $(".tate_enlarge_img:eq("+index+") .img img").width();
		img_h = $(".tate_enlarge_img:eq("+index+") .img img").height();
		if (img_h > 246) { // this is a portait image
			lg_img_h = 512;
			lg_img_w = Math.round(512/img_h * 246);
			sm_img_h = 128;
			sm_img_w = Math.round(128/img_h * 246);
		} 
		else { // this is a landscape image
			lg_img_w = 512;
			lg_img_h = Math.round(512/246 * img_h);
			sm_img_w = 128;
			sm_img_h = Math.round(128/246 * img_h);
		}
		// dimensions of container box
		img_box_w = lg_img_w + 30;
		av_box_w = av_w + 30;
		// dimensions of caption
		img_cap_w = lg_img_w;
		av_cap_w = av_w - sm_img_w - 17;
					
		// preload the image
		large_image = new Image();
		large_image.onload = function(){
			
			//display the image and remove the loading div
			$("body").append("<div class='tee_enlarged'></div>");
					
			// add a close button and bind the close event
			$(".tee_enlarged").append("<div class='tee_close text'><a href='#'><span></span>close</a></div>");
			close_button();

			// adds the credit
			$(".tee_enlarged").append("<div class='credit' />");
			$(".tee_enlarged .credit").append(credit);

			// add the headphones button if required and bind events
			if (isAV) {
				avlink = $(".tate_enlarge_img:eq("+index+") .tee_av_link").clone();
				avlink.insertAfter($(".tee_enlarged .credit"));
				av_button();
				// dimensions of the button (these can be changed)
				av_link_w = 89; 
				av_link_h = 74;
				img_cap_w = img_cap_w - av_link_w;
				var av_url = $(".tate_enlarge_img:eq("+index+") .tee_av_link").attr("href");
				mp4 = av_url.substr(av_url.lastIndexOf('_')+1);
			} else { 
				mp4 = "";
				av_link_w = 0;
				av_link_h = 0;
			}

			// determine the height of the caption (and thus the necessary height of container)
			$("body").append('<div class="img_cap testdiv" style="position:absolute;top:-1000px;padding:0;width:'+img_cap_w+'px">'+credit+"</div>");
			$("body").append('<div class="av_cap testdiv" style="position:absolute;top:-1000px;padding:0;width:'+av_cap_w+'px">'+credit+"</div>");
			img_cap_h = $(".img_cap").height();
			av_cap_h = $(".av_cap").height();
			(img_cap_h > av_link_h) ? img_box_h = (lg_img_h + 55 + img_cap_h) : img_box_h = (lg_img_h + 55 + av_link_h) ;
			(av_cap_h > (sm_img_h+2)) ? av_box_h = (av_h + 55 + av_cap_h) : av_box_h = (av_h + 57 + sm_img_h) ;

			$('.testdiv').remove();
			// alert('img_cap_h: '+img_cap_h+', av_link_h: '+av_link_h+', lg_img_h: '+lg_img_h+', img_box_h: '+img_box_h);
			// set the image properties
			$(".tee_enlarged").append("<div><img /></div>");
			$(".tee_enlarged img").attr("alt", alt)
			$(".tee_enlarged img").attr("src", img_url)
				
			// remove the loading div and display the enlarged image div
			$(".tee_loading").remove();
			
			// set the initial size of the conatiner and then centre it
			if (type == 'av') { // create container for AV content
				$(".tee_enlarged").height(av_box_h);
				$(".tee_enlarged").width(av_box_w);
				$(".tee_enlarged .tee_av_link").css('display','none');
				$(".tee_enlarged .credit").css({'width':av_cap_w+'px','top':(av_h+40)+'px','left':(sm_img_w+32)+'px'});
				$(".tee_enlarged img").css({'width':sm_img_w+'px','height':sm_img_h+'px','top':(av_h+40)+'px'}).addClass('smallImg');
				expand_image(); // bind switching event to thumbnail image;
				if (videodata.hasOwnProperty(mp4)) { 
					var theobject = getvideoobject( videodata[mp4][0] ); 
					$('.tee_enlarged').append('<div id="objview"></div>');
					$('#objview').html(theobject);
					brightcove.createExperiencesPostLoad();
					} 
				} 
			else { // create container for large image
				$(".tee_enlarged").height(img_box_h);
				$(".tee_enlarged").width(img_box_w);
				$(".tee_enlarged .credit").css({'display':'block','width':img_cap_w+'px','top':(lg_img_h+40)+'px'});
				}
			$(".tee_enlarged").tee_centre(0);

			} // end load image
			
		large_image.src = img_url;
	
	}); // end of callback from fadeIn of #shadebox
											
} // create_overlay ends

function getPageScroll(){

	var yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}
	return yScroll;
} // getPageScroll ends

function getWindowHeight(){
	var windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowHeight = document.body.clientHeight;
	}	

	return windowHeight;
} // getWindowHeight ends

jQuery.fn.extend({
	tee_centre: function(speed) {
		var top_position = Math.max(getPageScroll() + ((getWindowHeight() - $(this).absHeight())/ 2), tate_enlarge_content_height_offset);
		// don't go over the left margin and don't overlap the header
		var left_position = Math.max((tate_enlarge_content_width - $(this).absWidth()) / 2, tate_enlarge_content_width_offset);
		// Animate if 'speed' is set to a value > 0. Otherwise, just jump to new position.
		if (speed > 0) { $(this).animate({"position":"absolute","top":top_position + "px","left":left_position + "px"},speed,'swing'); }
		else { $(this).css({"position":"absolute","top":top_position + "px","left":left_position + "px"}); }
		// alert("height: "+h+", width: "+w);
		return;
	}
});


// run initialisation function when doc loads
$(document).ready( function(){
	//load the height & width utils first
	$.getScript("http://admin.brightcove.com/js/BrightcoveExperiences.js");
	$.getScript("/javascripts/jquery.tate.hwxy.js", function(){
  		init_tate_enlarge_img();
	});			
							
} ); // end document onload