/**
 *	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/
 */
 
/**
 * Notiz Tino Siebert
 * 2008-01-23 
 * Namensraum mit iflow_ als Praefix versehen um diese Anwendung 
 * von den weiteren Skripten abzugrenzen.
 * - Workaround in Zeile 151, fuer images_top wurde eine Variable mit dem Praefix iflow_ vergeben. 
 *   Dies ermoeglicht die manuelle Uebergabe einer Hoehe und behebt so den offsetTop-Bug.
 * - Selbes gilt fuer offsetLeft-Bug im IE, siehe Zeile 156.
 */


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

/* Id names used in the HTML */
var iflow_conf_imageflow = 'iflow_imageflow';    // Default is 'imageflow'
var iflow_conf_loading = 'iflow_loading';        // Default is 'loading'
var iflow_conf_images = 'iflow_images';          // Default is 'images'
var iflow_conf_captions = 'iflow_captions';      // Default is 'captions'
var iflow_conf_scrollbar = 'iflow_scrollbar';    // Default is 'scrollbar'
var iflow_conf_slider = 'iflow_slider';          // Default is 'slider'

/* Define global variables */
var iflow_caption_id = 0;
var iflow_new_caption_id = 0;
var iflow_current = 0;
var iflow_target = 0;
var iflow_mem_target = 0;
var iflow_timer = 0;
var iflow_array_images = new Array();
var iflow_new_slider_pos = 0;
var iflow_dragging = false;
var iflow_dragobject = null;
var iflow_dragx = 0;
var iflow_posx = 0;
var iflow_new_posx = 0;
var iflow_xstep = 150;

/* cewe */
var iflow_start_id = 0;
var iflow_images_top = 0;
var iflow_images_left = 0;

function iflow_step()
{
	switch (iflow_target < iflow_current-1 || iflow_target > iflow_current+1) 
	{
		case true:
			iflow_moveTo(iflow_current + (iflow_target-iflow_current)/3);
			window.setTimeout(iflow_step, 50);
			iflow_timer = 1;
			break;

		default:
			iflow_timer = 0;
			break;
	}
}

function iflow_glideTo(x, iflow_new_caption_id)
{	
	/* Animate gliding to new x position */
	iflow_target = x;
	iflow_mem_target = x;
	if (iflow_timer == 0)
	{
		window.setTimeout(iflow_step, 50);
		iflow_timer = 1;
	}
	
	/* Display new caption */
	iflow_caption_id = iflow_new_caption_id;
	caption = img_div.childNodes.item(iflow_array_images[iflow_caption_id]).getAttribute('alt');
	if (caption == '') caption = '&nbsp;';
	caption_div.innerHTML = '<h1>'+caption+'</h1>'; //caption_div.innerHTML = caption;

	/* Set scrollbar slider to new position */
	if (iflow_dragging == false)
	{
		iflow_new_slider_pos = (scrollbar_width * (-(x*100/((max-1)*iflow_xstep))) / 100) - iflow_new_posx;
		slider_div.style.marginLeft = (iflow_new_slider_pos - iflow_conf_slider_width) + 'px';
	}
}

function iflow_moveTo(x)
{
	iflow_current = x;
	var zIndex = max;
	
	/* Main loop */
	for (var index = 0; index < max; index++)
	{
		var image = img_div.childNodes.item(iflow_array_images[index]);
		var current_image = index * -iflow_xstep;

		/* Don't display images that are not iflow_conf_focussed */
		if ((current_image+max_iflow_conf_focus) < iflow_mem_target || (current_image-max_iflow_conf_focus) > iflow_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 / (iflow_conf_reflection_p + 1)) * iflow_conf_reflection_p); //orig
			if(iflow_images_top>0) {images_top = iflow_images_top;}
			var new_img_top = (images_width * 0.34 - new_img_h) + images_top + ((new_img_h / (iflow_conf_reflection_p + 1)) * iflow_conf_reflection_p);

			/* Set new image properties */
			//image.style.left = xs - (image.pc / 2) / z * size + images_left + 'px'; //orig
			if(iflow_images_left>0) {images_left = iflow_images_left;}
			image.style.left = xs - (image.pc / 2) / z * size + images_left + 'px'; 
			image.style.height = new_img_h + 'px';
			image.style.width = new_img_w + 'px';
			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 == iflow_caption_id )
			{
				case false:
					image.onclick = function() { iflow_glideTo(this.x_pos, this.i); }
					break;

				default:
					zIndex = zIndex + 1;
					image.onclick = function() { document.location = this.url; }
					break;
			}
			image.style.zIndex = zIndex;
		}
		x += iflow_xstep;
	}
}

/* Main function */
function iflow_refresh(onload)
{
	/* Cache document objects in global variables */
	imageflow_div = document.getElementById(iflow_conf_imageflow);
	img_div = document.getElementById(iflow_conf_images);
	scrollbar_div = document.getElementById(iflow_conf_scrollbar);
	slider_div = document.getElementById(iflow_conf_slider);
	caption_div = document.getElementById(iflow_conf_captions);

	/* Cache global variables, that only change on refresh */
	images_width = img_div.offsetWidth;
	images_top = imageflow_div.offsetTop; //alert('top '+images_top);
	images_left = imageflow_div.offsetLeft;
	max_iflow_conf_focus = iflow_conf_focus * iflow_xstep;
	size = images_width * 0.5;
	scrollbar_width = images_width * 0.6;
	iflow_conf_slider_width = iflow_conf_slider_width * 0.5;
	max_height = images_width * 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.02 + 'px';
	scrollbar_div.style.marginLeft = images_width * 0.2 + 'px';
	scrollbar_div.style.width = scrollbar_width + 'px';
	
	/* Set slider attributes */
	slider_div.onmousedown = function () { iflow_dragstart(this); };
	slider_div.style.cursor = iflow_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)
		{
			iflow_array_images[i] = index;
			
			/* Set image onclick by adding i and x_pos as attributes! */
			image.onclick = function() { iflow_glideTo(this.x_pos, this.i); }
			image.x_pos = (-i * iflow_xstep);
			image.i = i;
			
			/* 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 / (iflow_conf_reflection_p + 1))) 
			{
				/* Landscape format */
				case true:
					image.pc = 118;
					break;

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

			/* Set ondblclick event */
			image.url = image.getAttribute('longdesc');
			image.ondblclick = function() { document.location = this.url; }

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

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

	/* Display images in current order */
	iflow_moveTo(iflow_current);
	iflow_glideTo(iflow_current, iflow_caption_id);
}

/* Show/hide element functions */
function iflow_show(id)
{
	var element = document.getElementById(id);
	element.style.visibility = 'visible';
}
function iflow_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(iflow_conf_imageflow))
	{
		iflow_hide(iflow_conf_loading);
		iflow_refresh(true);
		iflow_show(iflow_conf_images);
		iflow_show(iflow_conf_scrollbar);
		iflow_initMouseWheel();
		iflow_initMouseDrag();
		if(iflow_start_id>0) {iflow_start_id--; iflow_glideTo( (-150*iflow_start_id), iflow_start_id);}
	}
}

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

/* Handle the wheel angle change (delta) of the mouse wheel */
function iflow_handle(delta)
{
	var change = false;
	switch (delta > 0)
	{
		case true:
			if(iflow_caption_id >= 1)
			{
				iflow_target = iflow_target + iflow_xstep;
				iflow_new_caption_id = iflow_caption_id - 1;
				change = true;
			}
			break;

		default:
			if(iflow_caption_id < (max-1))
			{
				iflow_target = iflow_target - iflow_xstep;
				iflow_new_caption_id = iflow_caption_id + 1;
				change = true;
			}
			break;
	}

	/* Glide to next (mouse wheel down) / previous (mouse wheel up) image */
	if (change == true)
	{
		iflow_glideTo(iflow_target, iflow_new_caption_id);
	}
}

/* Event handler for mouse wheel event */
function iflow_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) iflow_handle(delta);
	if (event.preventDefault) event.preventDefault();
	event.returnValue = false;
}

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

/* This function is called to drag an object (= slider div) */
function iflow_dragstart(element)
{
	iflow_dragobject = element;
	iflow_dragx = iflow_posx - iflow_dragobject.offsetLeft + iflow_new_slider_pos;
}

/* This function is called to stop dragging an object */
function iflow_dragstop()
{
	iflow_dragobject = null;
	iflow_dragging = false;
}

/* This function is called on mouse movement and moves an object (= slider div) on user action */
function iflow_drag(e)
{
	iflow_posx = document.all ? window.event.clientX : e.pageX;
	if(iflow_dragobject != null)
	{
		iflow_dragging = true;
		iflow_new_posx = (iflow_posx - iflow_dragx) + iflow_conf_slider_width;

		/* Make sure, that the slider is moved in proper relation to previous movements by the iflow_glideTo function */
		if(iflow_new_posx < ( - iflow_new_slider_pos)) iflow_new_posx = - iflow_new_slider_pos;
		if(iflow_new_posx > (scrollbar_width - iflow_new_slider_pos)) iflow_new_posx = scrollbar_width - iflow_new_slider_pos;
		
		var slider_pos = (iflow_new_posx + iflow_new_slider_pos);
		var step_width = slider_pos / ((scrollbar_width) / (max-1));
		var image_number = Math.round(step_width);
		var new_target = (image_number) * -iflow_xstep;
		var iflow_new_caption_id = image_number;

		iflow_dragobject.style.left = iflow_new_posx + "px";
		iflow_glideTo(new_target, iflow_new_caption_id);
	}
}

/* Initialize mouse event listener */
function iflow_initMouseDrag()
{
	document.onmousemove = iflow_drag;
	document.onmouseup = iflow_dragstop;
}

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

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