/* 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 = 20;          // Sets the px width of the slider div
var conf_images_cursor = 'default';  // 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_slideshow = "";    // Default is 'slideshow'
var conf_images_url = "";   // Images div.innerHTML
var conf_image_landscape = 150;
var conf_image_square = 100;
var conf_image_width = 640;
var conf_image_height = 480;

/* 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 = 100;
var timer_step = 2;

/*

function getXmlHttp() {
   if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
   } else if (window.ActiveXObject) {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
   }
   if (xmlhttp == null) {
      alert("Your browser does not support XMLHTTP.");
   }
   return xmlhttp;
}

function readFileHttp(fname) {
  var sResult = false;
  var strText = "";
  try
  {
    xmlhttp = getXmlHttp();
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4)
      {
        strText = xmlhttp.responseText;
        sResult = true;
      }
      //alert(xmlhttp.responseText);
    }
    xmlhttp.open("GET", fname, true);
    xmlhttp.send(null);
    do {} while(!sResult);
  }
  catch(e) {}
  return strText;
}

*/

function step()
{
	switch (target < current-1 || target > current+1) 
	{
		case true:
			moveTo(current + (target-current)/3);
			window.setTimeout(step, timer_step);
			timer = 1;
			break;

		default:
			timer = 0;
			break;
	}
}

function glideTo(x, new_caption_id)
{	
	/* Animate gliding to new x position */
	if (max_images == 0) return;
	target = x;
	mem_target = x;
	if (timer == 0)
	{
		window.setTimeout(step, timer_step);
		timer = 1;
	}
	
	/* Display new caption */
	caption_id = new_caption_id;
	var image = img_div.childNodes[array_images[caption_id]]
	var caption = image.getAttribute('caption');
	if (caption == '') caption = '&nbsp;';
	var comments = image.getAttribute('comment');
	caption_div.innerHTML = caption;
	comments = comments.replace(/^\s+|\s+$/g,"");
	if (comments.length > 0 && false)
	{
    var s = comments;
    comments = "";
    for (i=0;i<5;i++)
    {
      comments += s + "<br>";
    }
  }
	comments_div.innerHTML = comments;
	if (comments.length > 0)
    show(conf_comments)
  else
    hide(conf_comments);

	/* Set scrollbar slider to new position */
	if (dragging == false)
	{
		new_slider_pos = (scrollbar_width * (-(x*100/((max_images-1)*xstep))) / 100) - new_posx;
		slider_div.style.marginLeft = (new_slider_pos - conf_slider_width) + 'px';
	}
}

function moveTo(x)
{
	current = x;
	var zIndex = max_images;
	
	/* Main loop */
	for (var index = 0; index < max_images; 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 a = (images_width * 0.28 - new_img_h) + images_top + ((new_img_h / (0.1 + 1)) * 0.1);
			var new_img_top = (images_width * 0.28 - new_img_h) + ((new_img_h / (conf_reflection_p + 1)) * conf_reflection_p);

			/* Set new image properties */
			image.style.left = xs - (image.pc / 2) / z * size + '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 true:
					zIndex = zIndex + 1;
					image.ondblclick = showImage;
					image.style.filter = "";
					slider_div.innerText = caption_id +1;
					break;

				default:
					image.onclick = function() { glideTo(this.x_pos, this.i); }
					image.style.filter = "alpha(opacity=85)";
					break;
			}
			image.style.zIndex = zIndex;
		}
		x += xstep;
	}
}

function showImage()
{
  show(conf_loading); hide(conf_display);
  var s = "";
  s += "<table width='100%' height='100%'>";
  s += "  <tr valign=middle>";
  s += "    <td><img class='image' id='" + 
            conf_display_image + "' onload='resizeImage(this)' src='" +
            this.url + "'></td>";
  s += "  </tr>";
  s += "</table>";
  display_div.innerHTML = s;
}

function resizeImage(img)
{
  var w = conf_image_width, h = conf_image_height;
  if (img.offsetWidth < img.offsetHeight)
  {
    var w1 = w; w = h; h = w1;
  }
  if (img.offsetWidth > w)
  {
    var w1 = w / img.offsetWidth;
    var h1 = img.offsetHeight * w1;
    img.style.width = w + 'px';
    img.style.height = h1 + 'px';
  } else if (img.offsetHeight > h) {
    var h1 = h / img.offsetHeight;
    var w1 = img.offsetWidth * h1;
    img.style.width = w1 + 'px';
    img.style.height = h + 'px';
  }
  hide(conf_loading);
  show(conf_display);
}

/* Main function */
function refresh(onload)
{
	/* Cache global variables, that only change on refresh */
	images_width = img_div.offsetWidth;
	images_top = -img_div.offsetTop + slideshow_div.offsetTop;
	images_left = -img_div.offsetLeft + slideshow_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.58;
	
  flowcenter_top = slideshow_div.offsetHeight / 2;
  flowcenter_left = slideshow_div.offsetWidth / 2;

	/* Change slideshow div properties */
	slideshow_div.style.height = max_height + 'px';
	slideshow_div.oncontextmenu = function() { return false; }
	slideshow_div.onselectstart = function() { return false; }

	/* Change images div properties */
	img_div.style.height = images_width * 0.338 + 'px';
	
	/* Change scrollbar div properties */
	scrollbar_div.style.marginTop = '20px';
	scrollbar_div.style.marginLeft = images_width * 0.2 + 'px';
	scrollbar_div.style.width = scrollbar_width + 'px';
	
		/* Change captions div properties */
	caption_div.style.marginTop = "-30px";
	caption_div.style.marginLeft = scrollbar_div.style.marginLeft;
	caption_div.style.width = scrollbar_width + 'px';
	
	/* Set slider attributes */
	slider_div.onmousedown = function () { dragstart(this); };
	slider_div.style.cursor = conf_slider_cursor;
	
  display_div.style.width = conf_image_width + 'px';
  display_div.style.height = conf_image_height + 'px';
  display_div.style.top = flowcenter_top - display_div.offsetHeight / 2 + 'px';
  display_div.style.left = flowcenter_left - display_div.offsetWidth / 2 + 'px';

	/* Cache EVERYTHING! */
	max_images = img_div.childNodes.length;
	var i = 0;
	for (var index = 0; index < max_images; index++)
	{
    var image = img_div.childNodes[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;
			
			/* 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 > image.h) 
			{
				/* Landscape format */
				case true:
					image.pc = conf_image_landscape;
					break;

				/* Portrait and square format */
				default:
					image.pc = conf_image_square;
					break;
			}

			/* Set ondblclick event */
			image.url = image.getAttribute('location');
			//image.ondblclick = showImage;

			/* Set image cursor type */
			image.style.cursor = conf_images_cursor;

			i++;
		}
	}
	max_images = array_images.length;

	/* Display images in current order */
	moveTo(current);
	glideTo(current, caption_id);
}

function loadElements()
{

  conf_loading = conf_slideshow + "_loading";        // Default is 'loading'
  conf_images = conf_slideshow + "_images";          // Default is 'images'
  conf_captions = conf_slideshow + "_captions";      // Default is 'captions'
  conf_scrollbar = conf_slideshow + "_scrollbar";    // Default is 'scrollbar'
  conf_slider = conf_slideshow + "_slider";          // Default is 'slider'
  conf_comments = conf_slideshow + "_comments";
  conf_slider_prev = conf_slider + "_prev";
  conf_slider_next = conf_slider + "_next";
  conf_display = conf_slideshow + "_display";  // Default is 'slide_display'
  conf_display_image = conf_display + "_image";

  /* Cache document objects in global variables */
	slideshow_div = document.getElementById(conf_slideshow);
	
	s = "";
	
	//s += "<div id='" + conf_images + "' class='images'>";
  //s += "</div>";
	
  //s += "<div id='" + conf_loading + "' class='loading'>";
	//s += "  <b>Yükleniyor..</b><br/>";
	//s += "  <img src='images/loading.gif' width=208 height=13 title='loading' />";
	//s += "</div>";

	s += "<div id='" + conf_captions + "' onselectstart='return false' class='captions'>";
	s += "</div>";
	  
  s += "<div id='" + conf_scrollbar + "' class='scrollbar'>";
  s += "   <div id='" + conf_slider + "' class='slider' align='center'></div>";
  s += "</div>";
  
  s += "<div id='" + conf_comments + "' class='comments'>";
  s += "</div>";
  
  s += "<div id='" + conf_display + "' class='display'>";
  s += "</div>";
  
  slideshow_div.innerHTML += s;
    
  display_div = document.getElementById(conf_display);
  img_div = document.getElementById(conf_images);
	scrollbar_div = document.getElementById(conf_scrollbar);
	slider_div = document.getElementById(conf_slider);
	caption_div = document.getElementById(conf_captions);
	comments_div = document.getElementById(conf_comments);
	//slider_prev_div = document.getElementById(conf_slider_prev);
	//slider_next_div = document.getElementById(conf_slider_next);
	
	display_div.onclick = function(){ hide(this.id);}
	//slider_prev_div.onclick = function(){ handle(-1); }
	//slider_next_div.onclick = function(){ handle(1); }
	slideshow_div.onselectstart = function(){ return false;}
	
  //img_div.innerHTML = readFileHttp(conf_images_url);
}

/* Show/hide element functions */
function show(id, fun)
{
	var element = document.getElementById(id);
	element.style.visibility = 'visible';
	if (fun)
    element.style.display = '';
}
function hide(id, fun)
{
	var element = document.getElementById(id);
	element.style.visibility = 'hidden';
	if (fun)
    element.style.display = 'none';
}

function doc_onload(){}

function AttachOnLoad(sFunc)
{
  if (window.onload != null)
    doc_onload = window.onload;
  window.onload = function() { doc_onload(); sFunc(); }
}

/* Hide loading bar, show content and initialize mouse event listening after loading */
function SlideShow(divSlideShow, pURL)
{
  conf_images_url = pURL;
  conf_slideshow = divSlideShow;
  //if (old_unload != null) old_unload();
	if(document.getElementById(conf_slideshow))
	{
    loadElements();
    hide(conf_loading);
		refresh(true);
		if (max_images == 0)
      hide(conf_slideshow);
		initMouseWheel();
		initMouseDrag();
	}
}

/* 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_images-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)
    slideshow_div.addEventListener('DOMMouseScroll', wheel, false);
	slideshow_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;
		//if (new_posx > scrollbar_div.offsetWidth - slider_div.offsetWidth +4)
    //  new_posx = scrollbar_div.offsetWidth - slider_div.offsetWidth +4;
		
		var slider_pos = (new_posx + new_slider_pos);
		var step_width = slider_pos / ((scrollbar_width) / (max_images-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;
}

function doc_onkeydown(){};
doc_onkeydown = document.onkeydown;

document.onkeydown = function(event)
{
  if (doc_onkeydown != null)
    doc_onkeydown();
	var charCode  = getKeyCode(event);
	switch (charCode)
	{
		/* Right arrow key */
		case 39:
			handle(-1);
			break;
		
		/* Left arrow key */
		case 37:
			handle(1);
			break;
	}
}
