var imageflow = function() {

/**
 *	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;         // Sets the height of the reflection in % of the source image 
var conf_focus =5;                  // Sets the numbers of images on each side of the focussed one
var conf_slider_width = 0;          // 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 = 'e-resize';  // 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 = 'loading';        // Default is 'loading'
var conf_images = 'empty';          // Default is 'images'
var conf_scrollbar = 'scrollbar';    // Default is 'scrollbar'
var conf_slider = 'slider';          // Default is 'slider'
var conf_captions = 'captions';      // Default is 'captions'

/* 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;
var middlepos = 3;

var nav_clicked = 0;

function runfade(){	
	var fadein = dojo.fadeIn({ node:'tipleft', delay: 10000, duration:1000});
	dojo.connect(fadein, "onEnd", function() {
		var fadeout = dojo.fadeOut({ node:'tipleft', delay:10000, duration:1000});
		dojo.connect(fadeout, "onEnd", function() {
			runfade();
		});
		fadeout.play();	
	 });
	 fadein.play();
}

function checkuserinput(){
		if(dojo.byId("tipleft").style.opacity == "1"){
			var fadeOut = dojo.fadeOut({ node:'tipleft', duration:1000});
			dojo.connect(fadeOut, "onEnd" , function() {
				dojo.byId('tipleft').style.left = "200px";
				dojo.byId('tipleft').innerHTML = "";
				runfade();
			});
			fadeOut.play();
			
					
	return;
	
	}
	/*if(nav_clicked == 0){
		if(dojo.byId("tipleft").style.opacity == "0"){
			dojo.fadeIn({ node:'tipleft', duration:1000}).play();
			window.setTimeout(checkuserinput,8000);
			return;
		}	
	}*/
}


var firsttime = 1;

return {


handle: function(delta)
{
	nav_clicked = 1;
	checkuserinput();
	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);
	}
},

init : function(){
	if(document.getElementById(conf_imageflow))
	{
		hide(conf_loading);
		imageflowrefresh(true);
		show(conf_images);
		initMouseWheel();
		initMouseDrag();
	}
},


setsrc : function (type,pos){
if(type == -1)
return;
if(pos != -1)
middlepos = pos;

if(pos ===6)
pageTracker.trackPageView("/tamponger");
if(pos ===16)
pageTracker.trackPageView("/bindor");
if(pos ===37)
pageTracker.trackPageView("/trosskydd");

/*
if(firsttime){
	messageDialog = new dijit.Dialog({title: messages.valjsjalvtitle});
	messageDialog.setContent("<img src='images/info.gif'/> "+messages.valjsjalvlong+"<br><center><button class='submitBtn' onclick='javascript:closeMessage();'><span> OK</span></button></center>");
	messageDialog.startup();
	messageDialog.show();
	firsttime = 0;
}
*/
/*if(preventclick == true)
	return; 
	*/
dojo.byId('imageflow').style.display = "block";
if(dojo.byId('kassaknapp') != null)
	dojo.byId('kassaknapp').style.display = "block";
backToOrder();
try{
	var oldid = img_div.childNodes.item(array_images[caption_id]).getAttribute('productid');
	if(oldid!= 'na')
	{
		dojo.byId(oldid).style.display = "none";
		dojo.byId(oldid).style.opacity = "0";
		
		var oldr = oldid.match(/[\d\.]+/g);
		dojo.byId("title"+oldr).style.display = "none";
	}
}catch(e){
	dojo.back.setInitialState(state);
}

/* Define global variables */
 //caption_id = 0;
 //new_caption_id = 0;
 current = 0;
 target = 0;
 mem_target = 0;
 timer = 0;
 array_images = new Array();
 new_slider_pos = 0;
 dragging = false;
 dragobject = null;
 dragx = 0;
 posx = 0;
 new_posx = 0;
 xstep = 150;
 if(type==0){
 	conf_images = 'tamponger';
 	nav(dojo.byId('tampongknapp'));
 	dojo.byId('empty').style.display = "none";
	dojo.byId('bindor').style.display = "none";
	dojo.byId('tamponger').style.display = "block";
	dojo.byId('tamponger').style.opacity = "1";
	
	dojo.byId('trosskydd').style.display = "none";
	dojo.byId('hjalp').style.display = "none";
 	dojo.byId('ovrigt').style.display = "none";
 	dojo.byId('halsa').style.display = "none";
	if(pos == -1)middlepos = 5;
	var state = {
				back: function() { setsrc(type,-1); },
				forward: function() { setsrc(type,-1); },
				changeUrl: "TAMPONGER"
	};
	try{
		dojo.back.addToHistory(state);
	}catch(e){
		dojo.back.setInitialState(state);
	}
	if(dojo.byId('tamponger').innerHTML.length < 100){
		dojo.byId("tamponger").style.visibility = "visible";
		dojo.byId("tamponger").innerHTML ="<img style='position:inherit;margin-top:100px;margin-left:370px;' height='50px' src='../images/ajax-loader.gif'>";
		dojo.xhrGet({ 
			url: "/products/loadtamponger", 
			handleAs : "json", 
			timeout: 15000,
			load: function(response, ioArgs){
				hide(conf_loading);
				dojo.byId("tamponger").innerHTML = response.produkter;  
				//dojo.byId("titles").innerHTML += response.titles;
				dojo.byId("description").innerHTML += response.description;  	
				dojo.parser.parse(dojo.byId("description"));
				imageflowrefresh(true); 
				if(parseInt(dojo.byId("antalpoang").innerHTML) > 0){
					dojo.query(".poangpris", document).forEach("item.style.display = 'block';");
		    		dojo.query(".pris", document).forEach("item.style.display = 'none';");
		    		dojo.byId("poang").style.display = 'block';
				}
				if(pageTracker)pageTracker.trackPageView("/tamponger");}});
		
		return;
	}
	
 	}
 if(type==1){
 	
	conf_images = 'bindor';
 	nav(dojo.byId('bindknapp'));
 	dojo.byId('empty').style.display = "none";
	dojo.byId('tamponger').style.display = "none";
 	dojo.byId('bindor').style.display = "block";
 	dojo.byId('trosskydd').style.display = "none";
 	dojo.byId('hjalp').style.display = "none";
 	dojo.byId('ovrigt').style.display = "none";
 	dojo.byId('halsa').style.display = "none";
 	if(pos == -1)middlepos = 5;
 	var state = {
				back: function() { setsrc(type,-1); },
				forward: function() { setsrc(type,-1); },
				changeUrl: "BINDOR"
	};
	dojo.back.addToHistory(state);
 	if(dojo.byId('bindor').innerHTML.length < 100){
 		dojo.byId("bindor").style.visibility = "visible";
		dojo.byId("bindor").innerHTML ="<img style='position:inherit;margin-top:100px;margin-left:370px;' height='50px' src='../images/ajax-loader.gif'>";
		dojo.xhrGet({ 
			url: "/products/loadbindor", 
			handleAs : "json", 
			timeout: 15000,
			load: function(response, ioArgs){
			hide(conf_loading);
				dojo.byId("bindor").innerHTML = response.produkter;	
				//dojo.byId("titles").innerHTML += response.titles;  
				dojo.byId("description").innerHTML += response.description;  				
				dojo.parser.parse(dojo.byId("description"));
				imageflowrefresh(true); 
				if(parseInt(dojo.byId("antalpoang").innerHTML) > 0){
					dojo.query(".poangpris", document).forEach("item.style.display = 'block';");
		    		dojo.query(".pris", document).forEach("item.style.display = 'none';");
		    		dojo.byId("poang").style.display = 'block';
				}
				if(pageTracker)pageTracker.trackPageView("/bindor");}});
		
		return;
	}
}
if(type==2){
 	conf_images = 'trosskydd';
 	nav(dojo.byId('trosknapp'));
 	dojo.byId('empty').style.display = "none";
 	dojo.byId('tamponger').style.display = "none";
 	dojo.byId('bindor').style.display = "none";
 	dojo.byId('trosskydd').style.display = "block";
 	dojo.byId('hjalp').style.display = "none";
 	dojo.byId('ovrigt').style.display = "none";
 	 	dojo.byId('halsa').style.display = "none";
  	if(pos == -1)middlepos = 4;
  	var state = {
				back: function() { setsrc(type,-1); },
				forward: function() { setsrc(type,-1); },
				changeUrl: "TROSSKYDD"
	};
	dojo.back.addToHistory(state);
  	if(dojo.byId('trosskydd').innerHTML.length < 100){
		dojo.byId("trosskydd").style.visibility = "visible";
		dojo.byId("trosskydd").innerHTML ="<img style='position:inherit;margin-top:100px;margin-left:370px;' height='50px' src='../images/ajax-loader.gif'>";
		dojo.xhrGet({ url: "/products/loadtrosskydd", handleAs : "json", timeout: 15000,load: function(response, ioArgs){
			dojo.byId("trosskydd").innerHTML = response.produkter;
			hide(conf_loading);
			//dojo.byId("titles").innerHTML += response.titles;  
			dojo.byId("description").innerHTML += response.description;  				
			dojo.parser.parse(dojo.byId("description"));
			if(parseInt(dojo.byId("antalpoang").innerHTML) > 0){
				dojo.query(".poangpris", document).forEach("item.style.display = 'block';");
        		dojo.query(".pris", document).forEach("item.style.display = 'none';");
        		dojo.byId("poang").style.display = 'block';
			}
			imageflowrefresh(true); if(pageTracker)pageTracker.trackPageView("/trosskydd");}});
			
		return;
	}
 	
}
if(type==3){
 	conf_images = 'ovrigt';
 	nav(dojo.byId('ovrigtknapp'));
 	dojo.byId('empty').style.display = "none";
 	dojo.byId('tamponger').style.display = "none";
 	dojo.byId('bindor').style.display = "none";
 	dojo.byId('trosskydd').style.display = "none";
 	dojo.byId('ovrigt').style.display = "block";
 	dojo.byId('halsa').style.display = "none";
 	dojo.byId('hjalp').style.display = "none";
  	if(pos == -1)middlepos = 3;
  	var state = {
				back: function() { setsrc(type,-1); },
				forward: function() { setsrc(type,-1); },
				changeUrl: "OVRIGT"
	};
	dojo.back.addToHistory(state);
  	if(dojo.byId('ovrigt').innerHTML.length < 100){
		dojo.byId("ovrigt").style.visibility = "visible";
		dojo.byId("ovrigt").innerHTML ="<img style='position:inherit;margin-top:100px;margin-left:370px;' height='50px' src='../images/ajax-loader.gif'>";
		dojo.xhrGet({ url: "/products/loadovrigt", handleAs : "json", timeout: 15000,load: function(response, ioArgs){
			hide(conf_loading);
			dojo.byId("ovrigt").innerHTML = response.produkter;	
			//dojo.byId("titles").innerHTML += response.titles;  
			dojo.byId("description").innerHTML += response.description;  				
			dojo.parser.parse(dojo.byId("description"));
			if(parseInt(dojo.byId("antalpoang").innerHTML) > 0){
				dojo.query(".poangpris", document).forEach("item.style.display = 'block';");
	    		dojo.query(".pris", document).forEach("item.style.display = 'none';");
	    		dojo.byId("poang").style.display = 'block';
			}
			imageflowrefresh(true); if(pageTracker)pageTracker.trackPageView("/ovrigt");}});
	
		return;
	}
 	
}
if(type==4){
 	conf_images = 'halsa';
 	nav(dojo.byId('halsaknapp'));
 	dojo.byId('empty').style.display = "none";
 	dojo.byId('tamponger').style.display = "none";
 	dojo.byId('bindor').style.display = "none";
 	dojo.byId('trosskydd').style.display = "none";
 	dojo.byId('ovrigt').style.display = "none";
 	dojo.byId('halsa').style.display = "block";
 	dojo.byId('hjalp').style.display = "none";
  	if(pos == -1)middlepos = 3;
  	var state = {
				back: function() { setsrc(type,-1); },
				forward: function() { setsrc(type,-1); },
				changeUrl: "HALSA"
	};
	dojo.back.addToHistory(state);
  	if(dojo.byId('halsa').innerHTML.length < 100){
		dojo.byId("halsa").style.visibility = "visible";
		dojo.byId("halsa").innerHTML ="<img style='position:inherit;margin-top:100px;margin-left:370px;' height='50px' src='../images/ajax-loader.gif'>";
		dojo.xhrGet({ url: "/products/loadhalsa", handleAs : "json", timeout: 15000,load: function(response, ioArgs){
			hide(conf_loading);
			dojo.byId("halsa").innerHTML = response.produkter;
			//dojo.byId("titles").innerHTML += response.titles;  
			dojo.byId("description").innerHTML += response.description;  				
			dojo.parser.parse(dojo.byId("description"));
			if(parseInt(dojo.byId("antalpoang").innerHTML) > 0){
				dojo.query(".poangpris", document).forEach("item.style.display = 'block';");
	    		dojo.query(".pris", document).forEach("item.style.display = 'none';");
	    		dojo.byId("poang").style.display = 'block';
			}
			imageflowrefresh(true); if(pageTracker)pageTracker.trackPageView("/halsa");}});
		
		return;
	}
 	
}

 imageflowrefresh(true);
}
};


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

		default:
			timer = 0;
			break;
	}
}


function glideTo(x, new_caption_id)
{	
if(img_div.id == "empty"){
	return;
}
	
	var id = img_div.childNodes.item(array_images[new_caption_id]).getAttribute('productid');
	var oldid = img_div.childNodes.item(array_images[caption_id]).getAttribute('productid');
	
	var f= dojo.fadeOut({ node:oldid, duration:300});
	dojo.connect(f, "onEnd" , function() {
		dojo.byId(oldid).style.display = "none";
		dojo.byId(oldid).style.opacity = "0";
		dojo.byId(id).style.opacity = "1";
		dojo.byId(id).style.display = "block";
		var fadein = dojo.fadeIn({ node:id, duration:500});
		dojo.connect(fadein, "onEnd" , function() {
			preventclick = false;
		});
		fadein.play();
	});
	preventclick = true;
	f.play();
	
	var r = id.match(/[\d\.]+/g);
	//dojo.byId("vhcountSlider"+r).select();
	
	var oldr = oldid.match(/[\d\.]+/g);
	dojo.byId("title"+oldr).style.display = "none";
	dojo.byId("title"+r).style.display = "block";


	/* Animate gliding to new x position */
	target = x;
	mem_target = x;
	if (timer == 0)
	{
		window.setTimeout(step, 30);
		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;';
	
	
	
}

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.014 + new_img_h/100) + images_top + ((new_img_h / (conf_reflection_p + 1)) * conf_reflection_p);
			
			
			
	
			/* Set new image properties */
			if ( image.i != caption_id )
			{
			image.style.left = (xs - (image.pc / 2) / z * size + images_left)+ 'px';
			image.style.height = new_img_h/1.1 + 'px';
			image.style.width = new_img_w/1.1 + 'px';
			var tmp = new_img_top + 25;
			image.style.top = tmp+ 'px';
			image.style.visibility = 'visible';
			}else{
				image.style.left = xs - (image.pc/2 ) / z * size + images_left + 'px';
				image.style.height = new_img_h /1.1 + 'px';
				image.style.width = new_img_w /1.1+ 'px';
				var tmp = new_img_top + 25;
				image.style.top = tmp+ '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:
					image.onclick = function() { glideTo(this.x_pos, this.i); }
					break;

				default:
					image.onclick = function() { dojo.byId("vhcountSlider"+this.url).select();/*addProduct(this.url);*/ }
			
					zIndex = zIndex + 1;
					break;
			}
			image.style.zIndex = zIndex;
		}
		x += xstep;
	}
}
/* Main function */
function imageflowrefresh(onload)
{


	/* Cache document objects in global variables */
	imageflow_div = document.getElementById(conf_imageflow);
	img_div = document.getElementById(conf_images);
	

	

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

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

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

    var customh = '256px';
	imageflow_div.style.height = customh;
	img_div.style.height = customh;
	
	
   /* 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;
			
			/* 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 = 118;
					break;

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

			/* Set ondblclick event */
			image.url = image.getAttribute('longdesc');
			
			image.ondblclick = function() {   dojo.byId("vhcountSlider"+this.url).select();/*addProduct(this.url);*/ }
			image.onclick = function() {  dojo.byId("vhcountSlider"+this.url).select();/*addProduct(this.url);*/ }
			/* Set image cursor type */
			image.style.cursor = conf_images_cursor;

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

	/* Display images in current order */
	//glideTo(current, caption_id);
	var par1 = -(middlepos-1)*150;
	glideTo(par1,middlepos-1);	
	
}

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



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


/* 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) imageflow.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:
			imageflow.handle(-1);
			break;
		
		/* Left arrow key */
		case 37:
			imageflow.handle(1);
			break;
	}
}
}();
