/**
 *	ImageFlow 0.8
 *
 *	This code is based on Michael L. Perrys Cover flow in Javascript.
 *	For he wrote that "You can take this code and use it as your own" [1]
 *	this is my attempt to improve some things. Feel free to use it! If
 *	you have any questions on it leave me a message in my shoutbox [2].
 *
 *	The reflection is generated server-sided by a slightly hacked  
 *	version of Richard Daveys easyreflections [3] written in PHP.
 *	
 *	The mouse wheel support is an implementation of Adomas Paltanavicius
 *	JavaScript mouse wheel code [4].
 *
 *	Thanks to Stephan Droste ImageFlow is now compatible with Safari 1.x.
 *
 *
 *	[1] http://www.adventuresinsoftware.com/blog/?p=104#comment-1981
 *	[2] http://shoutbox.finnrudolph.de/
 *	[3] http://reflection.corephp.co.uk/v2.php
 *	[4] http://adomas.org/javascript-mouse-wheel/
 */


/* Configuration variables */
var conf_reflection_p = 0.5;         // Sets the height of the reflection in % of the source image 
var conf_focus = 4;                  // Sets the numbers of images on each side of the focussed one
var conf_slider_width = 14;          // Sets the px width of the slider div
var conf_images_cursor = 'pointer';  // Sets the cursor type for all images default is 'default'
var conf_slider_cursor = 'default';  // Sets the slider cursor type: try "e-resize" default is 'default'

/* Id names used in the HTML */
var conf_imageflow = 'imageflow';    // Default is 'imageflow'
var conf_loading = 'imgf_loading';        // Default is 'loading'
var conf_images = 'imgf_images';          // Default is 'images'
var conf_captions = 'imgf_captions';      // Default is 'captions'
var conf_scrollbar = 'imgf_scrollbar';    // Default is 'scrollbar'
var conf_slider = 'imgf_slider';          // Default is 'slider'

/* Define global variables */
var caption_id = 0;
var new_caption_id = 0;
var current = 0;
var target = 0;
var mem_target = 0;
var timer = 0;
var array_images = new Array();
var new_slider_pos = 0;
var dragging = false;
var dragobject = null;
var dragx = 0;
var posx = 0;
var new_posx = 0;
var xstep = 150;


function step()
{
	switch (target < current-1 || target > current+1) 
	{
		case true:
			moveTo(current + (target-current)/3);
			window.setTimeout(step, 50);
			timer = 1;
			break;

		default:
			timer = 0;
			break;
	}
}

function glideTo(x, new_caption_id)
{	
	/* Animate gliding to new x position */
	target = x;
	mem_target = x;
	if (timer == 0)
	{
		window.setTimeout(step, 50);
		timer = 1;
	}
	
	/* Display new caption */
	caption_id = new_caption_id;
	caption = img_div.childNodes.item(array_images[caption_id]).getAttribute('alt');
	if (caption == '') caption = '&nbsp;';
	caption_div.innerHTML = caption;

	/* Set scrollbar slider to new position */
	if (dragging == false)
	{
		new_slider_pos = (scrollbar_width * (-(x*100/((max-1)*xstep))) / 100) - new_posx;
		slider_div.style.marginLeft = (new_slider_pos - conf_slider_width) + 'px';
	}
}

function moveTo(x)
{
	current = x;
	var zIndex = max;

	/* Main loop */
	for (var index = 0; index < max; index++)
	{
		var image = img_div.childNodes.item(array_images[index]);
		var current_image = index * -xstep;

		/* Don't display images that are not conf_focussed */
		if ((current_image+max_conf_focus) < mem_target || (current_image-max_conf_focus) > mem_target)
		{
			image.style.visibility = 'hidden';
			image.style.display = 'none';
		}
		else 
		{
			var z = Math.sqrt(10000 + x * x) + 100;
			var xs = x / z * size + size;

			/* Still hide images until they are processed, but set display style to block */
			image.style.display = 'block';
		
			/* Process new image height and image width */
			var new_img_h = (image.h / image.w * image.pc) / z * size;
			switch ( new_img_h > max_height )
			{
				case false:
					var new_img_w = image.pc / z * size;
					break;

				default:
					new_img_h = max_height;
					var new_img_w = image.w * new_img_h / image.h;
					break;
			}
//			var new_img_top = (images_width * 0.34 - new_img_h) + images_top + ((new_img_h / (conf_reflection_p + 1)) * conf_reflection_p);
			var new_img_top = (images_width * 0.34 - new_img_h)+images_top;

			/* Set new image properties */
			image.style.left = xs - (image.pc / 2) / z * size + images_left + 'px';			
		
			if(new_img_h >0) image.style.height = new_img_h + 'px';
			if(new_img_w >0) image.style.width = new_img_w + 'px';
			if(new_img_top >0) image.style.top = new_img_top+'px';
			image.style.visibility = 'visible';

			/* Set image layer through zIndex */
			switch ( x < 0 )
			{
				case true:
					zIndex++;
					break;

				default:
					zIndex = zIndex - 1;
					break;
			}
			
			/* Change zIndex and onclick function of the focussed image */
			switch ( image.i == caption_id )
			{
				case false:
					image.onclick = function() { glideTo(this.x_pos, this.i); }
					break;

				default:
					zIndex = zIndex + 1;
					image.onclick = function() {
						Lightbox_flow.start(this); 
						}
					break;
			}
			image.style.zIndex = zIndex;
		}
		x += xstep;
	}
}

/* Main function */
function refresh(onload)
{
	/* Cache document objects in global variables */
	imageflow_div = document.getElementById(conf_imageflow);
	img_div = document.getElementById(conf_images);
	scrollbar_div = document.getElementById(conf_scrollbar);
	slider_div = document.getElementById(conf_slider);
	caption_div = document.getElementById(conf_captions);

	/* Cache global variables, that only change on refresh */
	offset = $('#imageflow').offset();
	images_width = img_div.offsetWidth;
	images_top = offset.top;
	images_left = 0;//offset.left;
	max_conf_focus = conf_focus * xstep;
	size = images_width * 0.5;
	scrollbar_width = images_width * 0.6;
	conf_slider_width = conf_slider_width * 0.5;
	max_height = images_width * 0.35;//0.51;

	/* Change imageflow div properties */
	imageflow_div.style.height = max_height + 'px';

	/* Change images div properties */
	img_div.style.height = images_width * 0.338 + 'px';

	/* Change captions div properties */
	caption_div.style.width = images_width + 'px';
	caption_div.style.marginTop = '-'+images_width * 0.03 + 'px';

	/* Change scrollbar div properties */
	scrollbar_div.style.marginTop = '-'+images_width * 0.05 + 'px';
	scrollbar_div.style.marginLeft = images_width * 0.2 + 'px';
	scrollbar_div.style.width = scrollbar_width + 'px';
	
	/* Set slider attributes */
	slider_div.onmousedown = function () { dragstart(this); };
	slider_div.style.cursor = conf_slider_cursor;

	/* Cache EVERYTHING! */
	max = img_div.childNodes.length;
	var i = 0;
	for (var index = 0; index < max; index++)
	{ 
		var image = img_div.childNodes.item(index);
		if (image.nodeType == 1)
		{
			array_images[i] = index;
			
			/* Set image onclick by adding i and x_pos as attributes! */
			image.onclick = function() { glideTo(this.x_pos, this.i); }
			image.x_pos = (-i * xstep);
			image.i = i;
			image.style.position = 'absolute';
			
			/* Add width and height as attributes ONLY once onload */
			if(onload == true)
			{
				image.w = image.width;
				image.h = image.height;
			}

			/* Check source image format. Get image height minus reflection height! */
			switch ((image.w + 1) > (image.h / (conf_reflection_p + 1))) 
			{
				/* Landscape format */
				case true:
					image.pc = 128;
					break;

				/* Portrait and square format */
				default:
					image.pc = 65;
					break;
			}

			/* Set ondblclick event */
			image.url = image.getAttribute('longdesc');
/*			image.ondblclick = function() { 
				Lightbox_flow.start(image,image.url,'test');
			}*/

			/* Set image cursor type */
			image.style.cursor = conf_images_cursor;

			i++;
		}
	}
	max = array_images.length;

	/* Display images in current order */
	moveTo(current);
	glideTo(current, caption_id);

}

/* Show/hide element functions */
function show(id)
{
	var element = document.getElementById(id);
	element.style.visibility = 'visible';
}
function hide(id)
{
	var element = document.getElementById(id);
	element.style.visibility = 'hidden';
	element.style.display = 'none';
}

/* Hide loading bar, show content and initialize mouse event listening after loading */
window.onload = function()
{
	
	if(document.getElementById(conf_imageflow))
	{		
		hide(conf_loading);
		refresh(true);
		show(conf_images);
		show(conf_scrollbar);
		initMouseWheel();
		initMouseDrag();
		Lightbox_flow.initialize();			
	}
	
}

/* Refresh ImageFlow on window resize */
/*window.onresize = function()
{
	if(document.getElementById(conf_imageflow)) refresh();
}*/

/* Handle the wheel angle change (delta) of the mouse wheel */
function handle(delta)
{
	var change = false;
	switch (delta > 0)
	{
		case true:
			if(caption_id >= 1)
			{
				target = target + xstep;
				new_caption_id = caption_id - 1;
				change = true;
			}
			break;

		default:
			if(caption_id < (max-1))
			{
				target = target - xstep;
				new_caption_id = caption_id + 1;
				change = true;
			}
			break;
	}

	/* Glide to next (mouse wheel down) / previous (mouse wheel up) image */
	if (change == true)
	{
		glideTo(target, new_caption_id);
	}
}

/* Event handler for mouse wheel event */
function wheel(event)
{
	var delta = 0;
	if (!event) event = window.event;
	if (event.wheelDelta)
	{
		delta = event.wheelDelta / 120;
	}
	else if (event.detail)
	{
		delta = -event.detail / 3;
	}
	if (delta) handle(delta);
	if (event.preventDefault) event.preventDefault();
	event.returnValue = false;
}

/* Initialize mouse wheel event listener */
function initMouseWheel()
{
	if(window.addEventListener) imageflow_div.addEventListener('DOMMouseScroll', wheel, false);
	imageflow_div.onmousewheel = wheel;
}

/* This function is called to drag an object (= slider div) */
function dragstart(element)
{
	dragobject = element;
	dragx = posx - dragobject.offsetLeft + new_slider_pos;
}

/* This function is called to stop dragging an object */
function dragstop()
{
	dragobject = null;
	dragging = false;
}

/* This function is called on mouse movement and moves an object (= slider div) on user action */
function drag(e)
{
	posx = document.all ? window.event.clientX : e.pageX;
	if(dragobject != null)
	{
		dragging = true;
		new_posx = (posx - dragx) + conf_slider_width;

		/* Make sure, that the slider is moved in proper relation to previous movements by the glideTo function */
		if(new_posx < ( - new_slider_pos)) new_posx = - new_slider_pos;
		if(new_posx > (scrollbar_width - new_slider_pos)) new_posx = scrollbar_width - new_slider_pos;
		
		var slider_pos = (new_posx + new_slider_pos);
		var step_width = slider_pos / ((scrollbar_width) / (max-1));
		var image_number = Math.round(step_width);
		var new_target = (image_number) * -xstep;
		var new_caption_id = image_number;

		dragobject.style.left = new_posx + "px";
		glideTo(new_target, new_caption_id);
	}
}

/* Initialize mouse event listener */
function initMouseDrag()
{
	document.onmousemove = drag;
	document.onmouseup = dragstop;
}

function getKeyCode(event)
{
	event = event || window.event;
	return event.keyCode;
}

document.onkeydown = function(event)
{
	var charCode  = getKeyCode(event);
	switch (charCode)
	{
		/* Right arrow key */
		case 39:
			handle(-1);
			break;
		
		/* Left arrow key */
		case 37:
			handle(1);
			break;
	}
}


/*Lightbox js */
var Lightbox_flow = {
	fileLoadingImage : "/tv/images/lightbox/loading.gif",
	fileBottomNavCloseImage : '/tv/images/lightbox/close.gif',
	overlayOpacity : 0.8,
	borderSize : 10,
	imageArray : new Array,
	activeImage : null,
	inprogress : false,
	resizeSpeed : 350,
	destroyElement: function(id){
		if(el = document.getElementById(id)){
			el.parentNode.removeChild(el);
		}
	},
	initialize: function() {		
		Lightbox_flow.destroyElement('overlay'); Lightbox_flow.destroyElement('lightbox');
		
		$("body").append('<div id="overlay"></div><div id="lightbox"><div id="outerImageContainer"><div id="imageContainer"><img id="lightboxImage"><div style="" id="hoverNav"><a href="#" id="prevLink"></a><a href="#" id="nextLink"></a></div><div id="loading"><a href="#" id="loadingLink"><img src="'+Lightbox_flow.fileLoadingImage+'"></a></div></div></div><div id="imageDataContainer"><div id="imageData"><div id="imageDetails"><span id="caption"></span><span id="numberDisplay"></span></div><div id="bottomNav"><a href="#" id="bottomNavClose"><img src="'+Lightbox_flow.fileBottomNavCloseImage+'"></a></div></div></div></div>');
		$("#overlay").click(function(){ Lightbox_flow.end(); }).hide();
		$("#lightbox").click(function(){ Lightbox_flow.end();}).hide();
		$("#loadingLink").click(function(){ Lightbox_flow.end(); return false;});
		$("#bottomNavClose").click(function(){ Lightbox_flow.end(); return false; });
		$('#outerImageContainer').css({width: '250px', height: '250px'});
	},
	
	//	Display overlay and Lightbox_flow. If image is part of a set, add siblings to Lightbox_flow.imageArray.
	//
	start: function(imageSrc) {	
		$("select, embed, object, #imgf_captions, #imgf_scrollbar").hide();
		
		// stretch overlay to fill page and fade in
		var arrayPageSize = Lightbox_flow.getPageSize();
		$("#overlay").hide().css({width: '100%', height: arrayPageSize[1]+'px', opacity : Lightbox_flow.overlayOpacity}).fadeIn();

		Lightbox_flow.imageArray = [];
		imageNum = 0;		
		href = imageSrc.getAttribute('longdesc');

			// loop through anchors, find other images in set, and add them to Lightbox_flow.imageArray
			$('#imgf_images img').each(function(i) {
					Lightbox_flow.imageArray.push(new Array(this.getAttribute('longdesc'), this.title));					 
			});

			for(i = 0; i < Lightbox_flow.imageArray.length; i++){
		        for(j = Lightbox_flow.imageArray.length-1; j>i; j--){        
		            if(Lightbox_flow.imageArray[i][0] == Lightbox_flow.imageArray[j][0]){
		                Lightbox_flow.imageArray.splice(j,1);
		            }
		        }
		    }
			while(Lightbox_flow.imageArray[imageNum][0] != href) { imageNum++;}


		// calculate top and left offset for the lightbox 
		var arrayPageScroll = Lightbox_flow.getPageScroll();
		var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);
		var lightboxLeft = arrayPageScroll[0];
		$('#lightbox').css({top: lightboxTop+'px', left: lightboxLeft+'px'}).show();
		this.changeImage(imageNum);
	},

	//
	//	changeImage()
	//	Hide most elements and preload image in preparation for resizing image container.
	//
	changeImage: function(imageNum) {	
		if(this.inprogress == false){
			this.inprogress = true;
			Lightbox_flow.activeImage = imageNum;	// update global var

			// hide elements during transition
			$('#loading').show();
			$('#lightboxImage').hide();
			$('#hoverNav').hide();
			$('#prevLink').hide();
			$('#nextLink').hide();
			$('#imageDataContainer').hide();
			$('#numberDisplay').hide();	

			imgPreloader = new Image();
		
			// once image is preloaded, resize image container
			imgPreloader.onload=function(){
				document.getElementById('lightboxImage').src = Lightbox_flow.imageArray[Lightbox_flow.activeImage][0];
				Lightbox_flow.resizeImageContainer(imgPreloader.width, imgPreloader.height);
			}
			imgPreloader.src = Lightbox_flow.imageArray[Lightbox_flow.activeImage][0];
		}
	},

	//
	//	resizeImageContainer()
	//
	resizeImageContainer: function( imgWidth, imgHeight) {

		// get curren width and height
		this.widthCurrent = document.getElementById('outerImageContainer').offsetWidth;
		this.heightCurrent = document.getElementById('outerImageContainer').offsetHeight;

		// get new width and height
		var widthNew = (imgWidth  + (Lightbox_flow.borderSize * 2));
		var heightNew = (imgHeight  + (Lightbox_flow.borderSize * 2));

		// scalars based on change from old to new
		this.xScale = ( widthNew / this.widthCurrent) * 100;
		this.yScale = ( heightNew / this.heightCurrent) * 100;

		// calculate size difference between new and old image, and resize if necessary
		wDiff = this.widthCurrent - widthNew;
		hDiff = this.heightCurrent - heightNew;

		$('#outerImageContainer').animate({width: widthNew, height: heightNew},Lightbox_flow.resizeSpeed,'linear',function(){
				Lightbox_flow.showImage();

		});


		// if new and old image are same size and no scaling transition is necessary, 
		// do a quick pause to prevent image flicker.
		if((hDiff == 0) && (wDiff == 0)){
			if (navigator.appVersion.indexOf("MSIE")!=-1){ Lightbox_flow.pause(250); } else { Lightbox_flow.pause(100);} 
		}

		$('#prevLink').css({height: imgHeight+'px'});
		$('#nextLink').css({height: imgHeight+'px'});
		$('#imageDataContainer').css({width: widthNew+'px'});

		
	},
	
	//
	//	showImage()
	//	Display image and begin preloading neighbors.
	//
	showImage: function(){
		$('#loading').hide();
		$('#lightboxImage').fadeIn("fast");
		Lightbox_flow.updateDetails();
		this.preloadNeighborImages();
		this.inprogress = false;
	},

	//
	//	updateDetails()
	//	Display caption, image number, and bottom nav.
	//
	updateDetails: function() {
	$("#imageDataContainer").hide();
		// if caption is not null
		if(Lightbox_flow.imageArray[Lightbox_flow.activeImage][1]){
			$('#caption').html(Lightbox_flow.imageArray[Lightbox_flow.activeImage][1]).show();
		}
		
		// if image is part of set display 'Image x of x' 
		if(Lightbox_flow.imageArray.length > 1){
			$('#numberDisplay').html("Image " + eval(Lightbox_flow.activeImage + 1) + " of " + Lightbox_flow.imageArray.length).show();
		}

		$("#imageDataContainer").hide().slideDown("slow");
		var arrayPageSize = Lightbox_flow.getPageSize();
		$('#overLay').css({height: arrayPageSize[1]+'px'});
		Lightbox_flow.updateNav();
	},

	//
	//	updateNav()
	//	Display appropriate previous and next hover navigation.
	//
	updateNav: function() {

		$('#hoverNav').show();				

		// if not first image in set, display prev image button
		if(Lightbox_flow.activeImage != 0){
			$('#prevLink').show().click(function(){
				Lightbox_flow.changeImage(Lightbox_flow.activeImage - 1); return false;
			});
		}

		// if not last image in set, display next image button
		if(Lightbox_flow.activeImage != (Lightbox_flow.imageArray.length - 1)){
			$('#nextLink').show().click(function(){
				
				Lightbox_flow.changeImage(Lightbox_flow.activeImage +1); return false;
			});
		}
		
		this.enableKeyboardNav();
	},


	enableKeyboardNav: function() {
		document.onkeydown = this.keyboardAction; 
	},

	disableKeyboardNav: function() {
		document.onkeydown = '';
	},

	keyboardAction: function(e) {
		if (e == null) { // ie
			keycode = event.keyCode;
			escapeKey = 27;
		} else { // mozilla
			keycode = e.keyCode;
			escapeKey = e.DOM_VK_ESCAPE;
		}

		key = String.fromCharCode(keycode).toLowerCase();
		
		if((key == 'x') || (key == 'o') || (key == 'c') || (keycode == escapeKey)){	// close lightbox
			Lightbox_flow.end();
		} else if((key == 'p') || (keycode == 37)){	// display previous image
			if(Lightbox_flow.activeImage != 0){
				Lightbox_flow.disableKeyboardNav();
				Lightbox_flow.changeImage(Lightbox_flow.activeImage - 1);
			}
		} else if((key == 'n') || (keycode == 39)){	// display next image
			if(Lightbox_flow.activeImage != (Lightbox_flow.imageArray.length - 1)){
				Lightbox_flow.disableKeyboardNav();
				Lightbox_flow.changeImage(Lightbox_flow.activeImage + 1);
			}
		}

	},

	preloadNeighborImages: function(){

		if((Lightbox_flow.imageArray.length - 1) > Lightbox_flow.activeImage){
			preloadNextImage = new Image();
			preloadNextImage.src = Lightbox_flow.imageArray[Lightbox_flow.activeImage + 1][0];
		}
		if(Lightbox_flow.activeImage > 0){
			preloadPrevImage = new Image();
			preloadPrevImage.src = Lightbox_flow.imageArray[Lightbox_flow.activeImage - 1][0];
		}
	
	},

	end: function() {
		this.disableKeyboardNav();
		$('#lightbox').hide();
		$("#overlay").fadeOut();
		$("select, object, embed, #imgf_captions, #imgf_scrollbar").show();
	},
	
	getPageSize : function(){
		var xScroll, yScroll;

		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}

		var windowWidth, windowHeight;

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

		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}


		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}

		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
		return arrayPageSize;
	},
	getPageScroll : function(){
		
		var xScroll, yScroll;

		if (self.pageYOffset) {
			yScroll = self.pageYOffset;
			xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
			yScroll = document.documentElement.scrollTop;
			xScroll = document.documentElement.scrollLeft;
		} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
			xScroll = document.body.scrollLeft;	
		}

		arrayPageScroll = new Array(xScroll,yScroll) 
		return arrayPageScroll;
	},
	pause : function(ms){
		var date = new Date();
		curDate = null;
		do{var curDate = new Date();}
		while( curDate - date < ms);
	}
};
