/**
 *	ImageFlow 0.9.1 - Hacked version for Lightbox2 compatibility, opacity and carousel mode
 *
 *	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.
 *
 * And Daniel M. created the needed images dynamically - see duplicate(el).
 * Caveat: As of now images must have dimensions assigned in HTML
 * 		  due to browser compatibility.
 *
 *	[1] http://www.adventuresinsoftware.com/blog/?p=104#comment-1981
 *	[2] http://shoutbox.finnrudolph.de/
 *	[3] http://reflection.corephp.co.uk/v3.php
 *	[4] http://adomas.org/javascript-mouse-wheel/
 */


/* Configuration variables */
var conf_reflection_p = 0.5;           // Sets the height of the reflection as multiplier of the source image height
if (!conf_focus) {
	var conf_focus = 2;						// Sets the numbers of images on each side of the focussed one
}
var conf_slider_width = 60;            // 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'
var opacityArray = new Array(10,10,6);  // Sets the opacity (range: 0 to 10) first value is for the focussed image
var conf_focussed_pc = 100;					// Zoom in % for centered image?
var conf_normal_pc = 100;					// Zoom in % for other images?

/* Id names used in the HTML */
var conf_imageflow = 'imageflow';      // Default is 'imageflow'
var conf_loading = 'loading_bar';      // Default is 'loading'
var conf_images = 'images';            // Default is 'images'
var conf_captions = 'captions';        // Default is 'captions'
var conf_scrollbar = 'scrollbar';      // Default is 'scrollbar'
var conf_slider = '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 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 duplicate(el) {
/* Clone elements for carousel on the fly */
	var item_list = img_div.getElementsByTagName(el);
	var item_index = item_list.length -1;
	var pre,post;
	// Duplicate required amount of images for carousel
	for (var k=0; k<conf_focus; k++) {
		// Duplicate first element completely and insert at bottom
		pre = item_list[k*2].cloneNode(true);
		img_div.appendChild(pre);
		// Duplicate x-last item completely and prepend at top
		post = item_list[item_index].cloneNode(true);
		img_div.insertBefore(post,item_list[0]);
	}
}

/* Main function */
function redraw(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 */
	images_width = img_div.offsetWidth;
	images_top = imageflow_div.offsetTop;
	images_left = imageflow_div.offsetLeft;
	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.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 () { dragstart(this); return false; }
	slider_div.style.cursor = conf_slider_cursor;

	/* initialize images - BUT ONLY ONCE ON LOAD! */
	if(onload) {
		/* pass it the name of the outmost tag inside conf_images */
		if (conf_focus >= 1) { duplicate('a'); }
		image_array = img_div.getElementsByTagName('img'); // This is no array btw. - it's a DOM list

		/* Cache EVERYTHING! */
		maxim = image_array.length;
	
		var i = 0, j = 0;
		for (var index = 0; index < maxim; index++)
		{ 
			var image = image_array[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.jumppoint = false;
	
			/* Define jumpoints */
			var first_jumppoint = conf_focus;
			var last_jumppoint = maxim - conf_focus;
	
			if(i < first_jumppoint) {
				var glideTo_id = conf_focus - j; 
				image.x_pos = -last_jumppoint * xstep;
				image.i = last_jumppoint-glideTo_id;
				image.x_glide_pos = -(last_jumppoint-glideTo_id) * xstep;
				image.onclick = function() { moveTo(this.x_pos); glideTo(this.x_glide_pos, this.i); }
				image.jumppoint = true;
				j++;
			}
			if(i >= last_jumppoint) {
				var glideTo_id = conf_focus - j; 
				image.x_pos = -(first_jumppoint-1) * xstep;
				image.i = first_jumppoint+glideTo_id;
				image.x_glide_pos = -(first_jumppoint+glideTo_id) * xstep;
				image.onclick = function() { moveTo(this.x_pos); glideTo(this.x_glide_pos, this.i); }
				image.jumppoint = true;
				j = j -1;
			}
			
			/* Add width and height as attributes ONLY once on load */
			//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 = conf_normal_pc;
					break;
	
				/* Portrait and square format */
				default:
					image.pc = 100;
					break;
			}
			
			image.url = image.getAttribute('longdesc');
			/* Set ondblclick event only if the longdesc attribute is set and not empty 
			if(image.url !== null && image.url !== '') { //IE <=7 only knows !=
				image.ondblclick = function() { document.location = this.url; }
			}*/
	
			/* Set image cursor type */
			image.style.cursor = conf_images_cursor;
			i++;
		}
		glideTo(current, caption_id);
	} // endif (onload)
	moveTo(current); // Display images in current order
} // end redraw()

function glideTo(x, new_caption_id) {
	/* Set opacity for centered image */
	setOpacity(image_array[new_caption_id], opacityArray[0]);
	image_array[new_caption_id].pc = conf_focussed_pc;

	/* 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 = image_array[caption_id].getAttribute('alt');
	if (caption == '') caption = '&nbsp;';
	caption_div.innerHTML = caption;

	/* Set opacity for the other images that are displayed */
	for (var i = 1; i < (conf_focus+1); i++) 	{
		var left_id = caption_id - i;
		var right_id = caption_id + i;

		if (right_id < maxim) {
			setOpacity(image_array[right_id], opacityArray[i]);
			image_array[right_id].pc = conf_normal_pc;
		}
		if (left_id >= 0) {
			setOpacity(image_array[left_id], opacityArray[i]);
			image_array[left_id].pc = conf_normal_pc;
		}
	}

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

function setOpacity(object, value) {
	object.style.opacity = value/10;
	/*	if (object.nodeName == 'IMG' && document.all) {
		object.style.filter += "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + object.src + ")";
	}
	// this breaks 32bit PNGs in IE !! 
	object.style.filter = 'alpha(opacity=' + value*10 + ')';
	object.style.filter += 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + value*10 + ')';*/
}

function moveTo(x) {
	current = x;
	var zIndex = maxim;
	
	/* Main loop */
	for (var index = 0; index < maxim; index++)	{
		var image = image_array[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.37 - new_img_h) + images_top + ((new_img_h / (conf_reflection_p + 1)) * conf_reflection_p);

			/* Set new image properties */
			image.style.left = xs - (image.pc / 2) / z * size + images_left + 'px';
			if(new_img_w && new_img_h) { 
				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 == caption_id ) {
				case false:
					if(image.jumppoint == true) {
						image.onclick = function() {  glideTo(this.x_glide_pos, this.i);moveTo(this.x_pos); }
					}
					else {
						image.onclick = function() { glideTo(this.x_pos, this.i); }
					}
					break;

				default:
					zIndex = zIndex + 1;
					if(image.url !== null && image.url !== '' && image.jumppoint == false)
					{	// INDIGO PDF in neuem Fenster/Tab
						var url_test = image.url.toLowerCase().substr(image.url.length-3);
						if (url_test == 'pdf')
						{
							image.onclick = function() { //alert(this.url);
							window.open(this.url);
						}
						}
						else
						{
							image.onclick = function() { document.location = this.url;
							// INDIGO w/Mootools 1.2
							imageflow_div.fade('out');
							if($('company')) {$('company').fade('out');}
							}
						}
					}
					break;
			}
			image.style.zIndex = zIndex;
		}
		x += xstep;
	}
}

/* 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';
}

/* 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 < (maxim-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) {
		var next_img = image_array[new_caption_id];
		if(next_img.jumppoint == true) {
			glideTo(next_img.x_glide_pos, next_img.i);
			moveTo(next_img.x_pos);
		}
		else {
			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) / (maxim-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;
	
	/* Avoid text and image selection while dragging  */
	document.onselectstart = function () {
		if (dragging == true) {
			return false;
		}
		else {
			return true;
		}
	}
}

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

window.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;
	}
}

/* Hide loading bar, show content and initialize mouse event listening after loading */
window.onload = function() {
	if(document.getElementById(conf_imageflow)) {
		hide(conf_loading);
		redraw(true);
		show(conf_images);
		show(conf_scrollbar);
		if(document.getElementById('company')) {
			show('company');
		}
		initMouseWheel();
		initMouseDrag();
		glideTo( -xstep*conf_focus, conf_focus); //set startimg to first in conf_images
	}
}

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

/* Fixes the back button issue */
window.onunload = function() {
  document = null;
}

