/*

xFlow!

Created by Paul Whitrow - www.pwhitrow.com

xFlow! Software License - see xFlow! Software License.html in the xFlow! root directory

*/


/* Configuration variables */
var xflow_focus = 5;					// Sets the numbers of images visible on each side of the focused one
var xflow_xstep = 130;					// default central image spacing
var xflow_player_wait = 5000;			// default time between displaying items in autoplay

var xflow_allowed_videos = new Array('flv');
var xflow_allowed_audio = new Array('mp3');

/* Global variables */
var xflow_startimage = 1, xflow_loading = false, xflow_options = new Array(), xflow_loading_count = false, xflow_div = false, xflow_imagebank = false, xflow_captions = false, xflow_scrollbar = false, xflow_slider = false, xflow_barleft = false, xflow_barright = false, xflow_gallerymenu = false, xflow_gallerymenulist = false, xflow_slider_width = 0, xflow_caption_id = 0, xflow_new_caption_id = 0, xflow_current = 0, xflow_target = 0, xflow_memtarget = 0, xflow_timer = 0, xflow_array_images = new Array(), xflow_imgarray = new Array(), xflow_new_slider_pos = 0, xflow_dragging = false, xflow_dragobj = null, xflow_dragx = 0, xflow_posx = 0, xflow_newposx = 0, xflow_max = 0, xflow_vieweropen = false, xflow_imageviewer = false, xflow_viewerimageholder = false, xflow_viewermainimage = false, xflow_viewertext = false, xflow_viewervideo = false, xflow_viewerrightcontrol = false, xflow_viewerclosecontrol = false, xflow_viewerleftcontrol = false, xflow_viewerplaycontrol = false, xflow_preloadedimgs = new Array(), xflow_loadtimer, xflow_percent = 0, xflow_imageid, xflow_isvideo = false, xflow_browser = false, xflow_slidetextlink = false, scrollbar_width = 0, xflow_playing = false, xflow_timerdisplay = false, xflow_play_timer = false, xflow_play_timer_n = 5, xflow_play_timer_step = 1000;

/* Start functions */


/* detect IE! */
var IE = false;
if (document.all) 
{
	IE = true;
}

function XFLOW_init()
{
	/* Cache document objects in global variables */
	xflow_div					=	XFLOW_getByClassName('xflow');
	xflow_loading				=	XFLOW_getByClassName('xflow_loading');
	xflow_loading_count			=	XFLOW_getByClassName('xflow_loadingcount', 'p');
	xflow_imagebank				=	XFLOW_getByClassName('xflow_images');
//	xflow_scrollbar				=	XFLOW_getByClassName('xflow_scrollbar', 'ul');
//	xflow_slider				=	XFLOW_getByClassName('xflow_slider', 'li');
//	xflow_slidetextlink			=	XFLOW_getByClassName('xflow_slidetext','li');
//	xflow_barleft				=	XFLOW_getByClassName('xflow_barleft', 'li');
//	xflow_barright				=	XFLOW_getByClassName('xflow_barright', 'li');
//	xflow_captions				=	XFLOW_getByClassName('xflow_captions');
	xflow_gallerymenu			=	XFLOW_getByClassName('xflow_gallerymenu');
	xflow_gallerymenulist		=	XFLOW_getByClassName('xflow_gallerymenulist', 'ul');
	xflow_imageviewer			=	XFLOW_getByClassName('xflow_imageviewer');
	xflow_viewerimageholder		=	XFLOW_getByClassName('xflow_viewerimageholder');
	xflow_viewermainimage		=	XFLOW_getByClassName('xflow_viewermainimage', 'img');
	xflow_viewertext			=	XFLOW_getByClassName('xflow_viewertext');
	xflow_viewervideo			=	XFLOW_getByClassName('xflow_viewervideo');
	xflow_viewerleftcontrol		=	XFLOW_getByClassName('xflow_viewerleftcontrol');
	xflow_viewerrightcontrol	=	XFLOW_getByClassName('xflow_viewerrightcontrol');
	xflow_viewerclosecontrol	=	XFLOW_getByClassName('xflow_viewerclosecontrol');
	xflow_viewerplaycontrol		=	XFLOW_getByClassName('xflow_viewerplaycontrol');
	xflow_timerdisplay			=	XFLOW_getByClassName('xflow_timerdisplay');

	XFLOW_setUp(true);

	if(xflow_imagebank)
	{
		XFLOW_preLoad();
		XFLOW_show(xflow_imagebank);
//		XFLOW_show(xflow_scrollbar);
		XFLOW_initMouseWheel();
		XFLOW_initMouseDrag();
		XFLOW_goto(xflow_startimage);
//		XFLOW_disableSelection(xflow_scrollbar);
		XFLOW_hide(xflow_loading);
	}
	
	XFLOW_menuSet();

}

function XFLOW_disableSelection(target)
{
	if(xflow_slider)
	{
		if (typeof target.onselectstart != 'undefined') /* IE route */
		{
			target.onselectstart = function(){return false};
		}
		else if (typeof target.style.MozUserSelect != 'undefined') /* Firefox route */
		{
			target.style.MozUserSelect = 'none'
		}
		else /* All other route (ie: Opera) */
		{
			target.onmousedown = function(){return false;};
			target.style.cursor = 'default';
		}
	}
}

function XFLOW_preLoad()
{
	var preLoadImages = xflow_imagebank.getElementsByTagName('IMG');
	
	for(var i=0; i < preLoadImages.length; i++) 
	{
		xflow_preloadedimgs[i] = new Image();
		xflow_preloadedimgs[i].src = XFLOW_str_replace('/thumbs', '', preLoadImages[i].src);
		XFLOW_checkLoadStatus(i);
	}
}

function XFLOW_checkLoadStatus(i)
{
	var imgbg = xflow_imagebank.getElementsByTagName('IMG')[i].parentNode;

	if(XFLOW_isImgLoaded(xflow_preloadedimgs[i]))
	{
		xflow_percent += 1;

		var p = Math.round((xflow_percent / xflow_preloadedimgs.length) * 100);
		
		xflow_loading_count.innerHTML = p + '%';

		if(XFLOW_hasClass(imgbg, 'loading'));
		{
			XFLOW_removeClass(imgbg, 'loading');
		}

		if((i + 1) >= xflow_preloadedimgs.length)
		{
			clearTimeout(xflow_loadtimer);
			//window.status = 'xFlow Ready.';
		}
	}
	else
	{

		if(!XFLOW_hasClass(imgbg, 'loading'));
		{
			XFLOW_addClass(imgbg, 'loading');
		}

		xflow_loadtimer = setTimeout('XFLOW_checkLoadStatus(' + i + ')', 100)
	}
}

function XFLOW_isImgLoaded(img) 
{
	if (!img.complete) 
	{
        return false;
    }

    if (typeof img.naturalWidth != 'undefined' && img.naturalWidth == 0) 
	{
        return false;
    }

    return true;
}

function XFLOW_getFileExtension(file)
{
	var tmp = file.split('.');
	return (tmp[tmp.length - 1]);
}

function XFLOW_in_array(needle, haystack, argStrict) 
{
    var found = false, key, strict = !!argStrict;
 
    for (key in haystack) 
	{
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) 
		{
            found = true;
            break;
        }
    }
 
    return found;
}


function XFLOW_pause(ms) 
{
	var now = new Date();
	var exitTime = now.getTime() + ms;
	while (true) 
	{
		now = new Date();
		if (now.getTime() > exitTime)
		{
			return;
		}
	}
}

function XFLOW_menuSet()
{
	if(!xflow_gallerymenu) return;

	if(xflow_scrollbar.style)
	{
		xflow_gallerymenu.style.width = xflow_scrollbar.style.width;
	}

	XFLOW_show(xflow_gallerymenu);

	/* is menu hide enabled? */
	if(xflow_gallerymenu.getAttribute('lang'))
	{
		XFLOW_changeOpac(0, xflow_gallerymenulist);

		xflow_gallerymenu.onmouseover = function()
		{
				XFLOW_changeOpac(100, xflow_gallerymenulist);
		}

		xflow_gallerymenu.onmouseout = function()
		{
				XFLOW_changeOpac(0, xflow_gallerymenulist);
		}
	}
}

function XFLOW_goto(n)
{
	n = n -1;
	xflow_new_caption_id = n;
	XFLOW_glideTo(-(xflow_xstep * n), n);
}

function XFLOW_playpause()
{
	xflow_playing = !xflow_playing;

	if(xflow_playing)
	{
		XFLOW_addClass(xflow_viewerplaycontrol, 'hidden');
		XFLOW_removeClass(xflow_timerdisplay, 'hidden');
	}
	else
	{
		XFLOW_removeClass(xflow_viewerplaycontrol, 'hidden');
		XFLOW_addClass(xflow_timerdisplay, 'hidden');
	}

	xflow_play_timer_n = 5;

	XFLOW_play();
}

function XFLOW_play()
{
	if(xflow_play_timer_n != 0)
	{
		XFLOW_showTimer(xflow_play_timer_n);
	}

	if(xflow_playing)
	{
		if(xflow_play_timer_n == 0)
		{
			xflow_play_timer_n = 5;

			if(xflow_new_caption_id < (xflow_imgarray.length - 1))
			{
				XFLOW_handle(-1);
				XFLOW_play();
			}
			else
			{
				XFLOW_updateImageViewer(0, false);
				XFLOW_goto(1);
				XFLOW_play();
				return false;
			}
		}
		else
		{
			xflow_play_timer = setTimeout(function()
			{
				xflow_play_timer_n--;
				XFLOW_play();
			}, 
			xflow_play_timer_step);
		}
	}
	else
	{
		XFLOW_stopPlayer();
		return false;
	}
}

function XFLOW_stopPlayer()
{
	stopPlayer();
	clearTimeout(xflow_play_timer);
	xflow_playing = false;
	XFLOW_removeClass(xflow_viewerplaycontrol, 'hidden');
	XFLOW_addClass(xflow_timerdisplay, 'hidden');
}

function XFLOW_showTimer(n)
{
	/*
	xflow_timerdisplay.innerHTML = n;
	*/
	switch(n)
	{
		case (1):	xflow_timerdisplay.style.backgroundPosition = '0px -125px';
					break;
		case (2):	xflow_timerdisplay.style.backgroundPosition = '0px -100px';
					break;
		case (3):	xflow_timerdisplay.style.backgroundPosition = '0px -75px';
					break;
		case (4):	xflow_timerdisplay.style.backgroundPosition = '0px -50px';
					break;
		case (5):	xflow_timerdisplay.style.backgroundPosition = '0px -25px';
					break;
		default:	xflow_timerdisplay.style.backgroundPosition = '0px 0px';
					break;
	}
}

function XFLOW_minimiseText(str, n)
{
	if(str.length > n)
	{
		return str.substring(0, n) + '&#8230;[more]';
	}
	else
	{
		return str;
	}
}

function XFLOW_getOptions(obj)
{
	var cls = obj.className.split(" ");
	for(i = 0; i < cls.length; i++)
	{
		if(i == 0) continue;
		var tmp = cls[i].split("_");
		xflow_options[tmp[0]] = tmp[1];
	}
}

/* position elements on page after load */
function XFLOW_positionElements()
{
	/* drop captions,slider,and menu under the main image by setting image holder div height */
	var fh = parseInt(xflow_options["fadeheight"]);
	var image_height = parseInt(XFLOW_str_replace('px', '', xflow_imgarray[0].style.height));
	var image_top = parseInt(XFLOW_str_replace('px', '', xflow_imgarray[0].parentNode.style.top));

	if(fh > 0)
	{
		fh = fh / 1.2;
	}

	var bank_height = (image_height + image_top) - fh;

	xflow_imagebank.style.height = bank_height + 'px';
}

/* Main function */
function XFLOW_setUp(onload)
{
	
	if(typeof xFlowRemoteWidth != 'undefined' && xflow_div)
	{
		xflow_div.style.width = xFlowRemoteWidth + 'px';
	}

	if(xflow_imagebank)
	{
		/* Cache global variables, that only change on XFLOW_setUp */
		XFLOW_getOptions(xflow_imagebank);

		if(xflow_options['startimage'] != '')
		{
			xflow_startimage = xflow_options['startimage'];
		}
		else
		{
			xflow_startimage = 1;
		}

		images_width = xflow_imagebank.offsetWidth;
		images_top = xflow_div.offsetTop;
		images_left = xflow_div.offsetLeft;
		max_xflow_focus = xflow_focus * xflow_xstep;
		size = images_width * 0.5;
		max_height = images_width * 0.5;

		xflow_imagebank.style.height = images_width * 0.33 + 'px';  

		xflow_browser = XFLOW_getBrowserInfo();

//		if(xflow_captions)
//		{
//			xflow_captions.style.width = xflow_scrollbar.offsetWidth + 'px';
//		}
//
//		scrollbar_width = images_width / 2.5;
//
//		if(xflow_slidetextlink)
//		{
//			if(xflow_slidetextlink.offsetWidth > scrollbar_width)
//			{
//				xflow_slidetextlink.innerHTML = XFLOW_minimiseText(xflow_slidetextlink.innerHTML, 30);
//			}
//
//			xflow_slidetextlink.style.left = ((scrollbar_width / 2) - (xflow_slidetextlink.offsetWidth / 2)) + 10 + 'px';
//		}
//
//		if(xflow_scrollbar.style)
//		{
//			xflow_scrollbar.style.width = scrollbar_width + 'px';
//			/* centralise the scroll bar a little more!  */
//			xflow_scrollbar.style.left = 10 + 'px';
//		}
//
//		 /* IE fix! */
//		if(IE)
//		{
//			if(xflow_barleft) xflow_barleft.style.left = -27 + 'px';
//			if(xflow_barright) xflow_barright.style.right = -47 + 'px';
//		}
//
//		/* Set slider attributes */
//		xflow_slider.onmousedown = function () 
//		{ 
//			XFLOW_dragStart(this); 
//		};

		/* Cache EVERYTHING! */

		XFLOW_loadImagesToArray();

		var i = 0;
		for (var index = 0; index < xflow_max; index++)
		{ 
			var image = xflow_imgarray[index];

			if (image.nodeType == 1)
			{
				xflow_array_images[i] = index;
				
				/* Set image onclick by adding i and x_pos as attributes! */
				image.onclick = function() 
				{ 
					XFLOW_glideTo(this.x_pos, this.i); 
				};

				image.x_pos = (-i * xflow_xstep);
				image.i = i;
				
				/* Add width and height as attributes ONLY once on first load */
				if(onload)
				{
					image.w = image.width;
					image.h = image.height;
					image.defWidth = (image.width / 2.8);
				}

				image.url = XFLOW_str_replace('thumbs/', '', image.src);

				i++;
			}
		}

		xflow_max = xflow_array_images.length;

		XFLOW_moveTo(xflow_current);
		XFLOW_glideTo(xflow_current, xflow_caption_id);

		/* set viewer controls */
		xflow_viewerleftcontrol.onclick = function()
		{
			if(xflow_imageid > 0)
			{
				XFLOW_handle(1);
			}
			this.blur();
		};

		xflow_viewerrightcontrol.onclick = function()
		{
			if(xflow_imageid < index)
			{
				XFLOW_handle(-1);
			}
			this.blur();
		};

		xflow_viewerclosecontrol.onclick = function()
		{
			XFLOW_closeViewer();
		};

		xflow_viewerplaycontrol.onclick = function()
		{
			XFLOW_playpause();
		};

		xflow_timerdisplay.onclick = function()
		{
			XFLOW_playpause();
		};

		xflow_barleft.onclick = function()
		{
			XFLOW_handle(1);
		};

		xflow_barright.onclick = function()
		{
			XFLOW_handle(-1);
		};

		XFLOW_positionElements();
		
	}

	/* set menu size */
	if(xflow_gallerymenu)
	{
		xflow_gallerymenu.style.width = (xflow_div.offsetWidth / 1.5) + 'px';
	}
}

function XFLOW_step()
{
	switch (xflow_target < xflow_current-1 || xflow_target > xflow_current+1) 
	{
		case true:
			XFLOW_moveTo(xflow_current + (xflow_target-xflow_current)/3);
			window.setTimeout(XFLOW_step, 50);
			xflow_timer = 1;
			break;

		default:
			xflow_timer = 0;
			break;
	}
}

function XFLOW_glideTo(x, xflow_new_caption_id)
{	
	/* Animate gliding to new x position */

	if(xflow_imgarray.length <= 1)
	{
		return;
	}

	xflow_target = x;
	xflow_memtarget = x;

	/* Display new caption */
	xflow_caption_id = xflow_new_caption_id;
	var caption = xflow_imgarray[xflow_caption_id].alt;
	var description = xflow_imgarray[xflow_caption_id].title;
	if (caption == '') caption = '&nbsp;';

	caption = XFLOW_minimiseText(caption, 30);

	description = XFLOW_minimiseText(description, 30);

	xflow_captions.innerHTML = '<p><strong>' + caption + '</strong></p><p><em>' + XFLOW_convertURL(description) + '</em></p>';

	/* Set scrollbar slider to new position */
	if(!xflow_dragging && xflow_slider)
	{
		xflow_new_slider_pos = Math.round((scrollbar_width * (-(x*100/((xflow_max-1)*xflow_xstep))) / 100));

		xflow_slider.style.left = Math.round(xflow_new_slider_pos - xflow_slider_width) + 'px';

	}

	if (xflow_timer == 0)
	{
		window.setTimeout(XFLOW_step, 50);
		xflow_timer = 1;
	}
	
}

function XFLOW_moveTo(x)
{
	xflow_current = x;
	var zIndex = xflow_max;

	/* loop through images... */
	for (var index = 0; index < xflow_max; index++)
	{ 
		var image = xflow_imgarray[index];
		var current_image = index * -xflow_xstep;
		var imgbg = image.parentNode;

		/* Don't display images that are not focused */
		if ((current_image + max_xflow_focus) < xflow_memtarget || (current_image - max_xflow_focus) > xflow_memtarget)
		{
			image.style.visibility = 'hidden';
			image.style.display = 'none';
			imgbg.style.visibility = 'hidden';
			imgbg.style.display = 'none';
		}
		else 
		{
			XFLOW_css3(image, imgbg);

			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';
			imgbg.style.display = 'block';
			imgbg.style.backgroundColor = '#' + xflow_options['mainbgcolor'];
		

			/* Process new image height and image width */
			var new_img_h = (image.h / image.w * image.defWidth) / z * size;

			if(isNaN(new_img_h)) continue; /* IE fix! */

			switch ( new_img_h > max_height )
			{
				case false:
					var new_img_w = image.defWidth / z * size;
					break;

				default:
					new_img_h = max_height;
					var new_img_w = image.w * new_img_h / image.h;
					break;
			}

			/* Set new image properties */
			var imgleft = xs - (image.defWidth / 2) / z * size + images_left + 'px';

			var new_img_top = (images_width * 0.34 - new_img_h) + images_top + new_img_h;

			if(new_img_w > xflow_div.offsetWidth)
			{
				new_img_h = (image.h / image.w * new_img_w) / z * size;
				new_img_w = parseInt(xflow_div.offsetWidth) / 2;
				imgleft = xs - (new_img_w / 2) / z * size + images_left + 'px';
			}

			imgbg.style.left = imgleft;
			imgbg.style.height = new_img_h + 'px';
			imgbg.style.width = new_img_w + 'px';
			imgbg.style.visibility = 'visible';


			

			image.style.height = new_img_h + 'px';
			image.style.width = new_img_w + 'px';
			image.style.visibility = 'visible';
			image.id = index;

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

				default:
					zIndex = zIndex - 1;
					break;
			}

			/* Change zIndex and onclick function of the focused image */
			switch ( image.i == xflow_caption_id )
			{
				case false:
					image.onclick = function() 
					{ 
						XFLOW_glideTo(this.x_pos, this.i); 
					};
					break;

				default:
					zIndex = zIndex + 1;

					if(image.url != '')
					{
						/* events when clicking central image */
						image.onclick = function()
						{
							/* check if the description is a URL and go there if clicked */
							if(this.title.substr(0,4) == 'http')
							{
								document.location.href = this.title;
							}
							/* open main viewer if not a URL */
							else
							{
								XFLOW_openViewer(this);
							}
						}
					}
					
					/* set opacities for images either side of main */
					for(a=0; a < xflow_max; a++)
					{
						if((a > index + 3) || (a < index - 3))
						{ 
							XFLOW_changeOpac(15, xflow_imgarray[a]);
						}
						else if((a > index + 2) || (a < index - 2))
						{ 
							XFLOW_changeOpac(35, xflow_imgarray[a]);
						}
						else if((a > index + 1) || (a < index - 1))
						{
							XFLOW_changeOpac(50, xflow_imgarray[a]);
						}
						else if((a > index) || (a < index))
						{
							XFLOW_changeOpac(70, xflow_imgarray[a]);
						}
						else
						{
							// central image
							XFLOW_changeOpac(100, xflow_imgarray[a]);
						}

					}
					break;
			}

			/* make images appear on a curved plain? */
			if(xflow_options['curved'] == 'true')
			{
				var defTop = 30;
				var new_img_top = (new_img_h / 5) + images_top;
			}
			else
			{
				var defTop = 125;
				var new_img_top = (new_img_h / -5) + images_top;
			}


			if(new_img_top < (new_img_top + defTop))
			{
				new_img_top += defTop;
			}

			imgbg.style.top = Math.floor(new_img_top) + 'px';

			imgbg.style.zIndex = zIndex;
		}

		x += xflow_xstep;

	}
}

/* This function is called on mouse movement and moves the slider on user action */
function XFLOW_drag(e)
{
	xflow_posx = IE ? window.event.clientX : e.pageX;

	if(xflow_dragobj != null)
	{

		xflow_dragging = true;
		xflow_newposx = (xflow_posx - xflow_dragx) + xflow_slider_width;

		/* Make sure, that the slider is moved in proper relation to previous movements by the XFLOW_glideTo function */
		if(xflow_newposx < ( - xflow_new_slider_pos)) xflow_newposx = - xflow_new_slider_pos;
		if(xflow_newposx > (scrollbar_width - xflow_new_slider_pos)) xflow_newposx = scrollbar_width - xflow_new_slider_pos;
		
		var slider_pos = (xflow_newposx + xflow_new_slider_pos);
		var step_width = slider_pos / ((scrollbar_width) / (xflow_max-1));
		var image_number = Math.round(step_width);
		var new_target = (image_number) * -xflow_xstep;
		var xflow_new_caption_id = image_number;

		xflow_dragobj.style.left = slider_pos + 'px';

		XFLOW_glideTo(new_target, xflow_new_caption_id);
	}
	else
	{
		xflow_dragging = false; 
	}
}

function XFLOW_loadImagesToArray()
{
	if(xflow_imagebank)
	{
		var imgs = xflow_imagebank.getElementsByTagName('IMG');
		xflow_max = imgs.length;
		for (var i = 0; i < xflow_max; i++)
		{ 
			xflow_imgarray[i] = imgs[i];
		}
	}
}

function XFLOW_css3(image, imgbg)
{
	XFLOW_removeClass(imgbg, 'xflow_imgcentral');

	/* are CSS3 classes enabled? */
	if(XFLOW_hasClass(imgbg, 'css3'))
	{
		XFLOW_removeClass(imgbg, 'xflow_imgskewright');
		XFLOW_removeClass(imgbg, 'xflow_imgskewleft');

		if(image.i < xflow_caption_id)
		{
			if(!XFLOW_hasClass(imgbg, 'xflow_imgskewleft'))
			{
				XFLOW_addClass(imgbg, 'xflow_imgskewleft');
			}
		}
		else if(image.i > xflow_caption_id)
		{
			if(!XFLOW_hasClass(imgbg, 'xflow_imgskewright'))
			{
				XFLOW_addClass(imgbg, 'xflow_imgskewright');
			}
		}
	}

	if(image.i == xflow_caption_id)
	{
		if(!XFLOW_hasClass(imgbg, 'xflow_imgcentral'))
		{
			XFLOW_addClass(imgbg, 'xflow_imgcentral');
		}
	}
}

function XFLOW_basename(file)
{
	var tmp = file.split('/');
	return (tmp[tmp.length - 1]);
}

function XFLOW_isVideo(str)
{
	if(XFLOW_isYouTube(str))
	{
		return str;
	}

	var ext = XFLOW_getFileExtension(str);
	var video = XFLOW_basename(str);

    if(XFLOW_in_array(ext, xflow_allowed_videos))
	{
		return video;
	}
    else if(XFLOW_in_array(ext, xflow_allowed_audio))
	{
		return video;
	}
	else
	{
		return false;
	}
}

function XFLOW_isYouTube(str)
{
	if(str.indexOf('youtube') > 0)
	{
		return true;
	}
	else
	{
		return false;
	}
}

// FLV PLAYER MONITOR FUNCTIONS
function playerReady(obj)
{
	player = document.getElementById('XFLOW_MediaPlayer');
	player.addModelListener('STATE', 'stateMonitor');
}

function stopPlayer() 
{
	player = document.getElementById('XFLOW_MediaPlayer');
	if(player) 
	{
		player.sendEvent("STOP");
	}
}

function stateMonitor(obj)
{
	if(obj.newstate == 'COMPLETED')
	{
		if(xflow_new_caption_id < (xflow_imgarray.length - 1))
		{
			XFLOW_handle(-1);
		}
		else
		{
			XFLOW_updateImageViewer(0, false);
			XFLOW_goto(1);
		}
	}
}


function XFLOW_video(file)
{
	var url = file.getAttribute('longdesc');
	var src = file.src;
	var video = XFLOW_isVideo(url);

	if(video)
	{
		xflow_isvideo = true;
		var width = XFLOW_str_replace('px','',xflow_viewerimageholder.style.width);
		var height = XFLOW_str_replace('px','',xflow_viewerimageholder.style.height);
		var preview = XFLOW_basename(src);

		var s1 = new SWFObject('../../extras/player-viral.swf', 'XFLOW_MediaPlayer', width, height, '9.0.124');
		s1.addParam('quality', 'best');
		s1.addParam('allowfullscreen', 'true');
		s1.addParam('allownetworking', 'all');
		s1.addParam('allowscriptaccess', 'always');
		s1.addVariable('enablejs', 'true');
		s1.addVariable('javascriptid', 'XFLOW_MediaPlayer');

		if(XFLOW_hasClass(xflow_imageviewer, 'autoplay'))
		{
			var autoplay = '&autostart=true';
		}
		else
		{
			var autoplay = '';
		}

		if(XFLOW_isYouTube(video))
		{
			s1.addParam('flashvars', 'file=' + url + '&image=' + src + autoplay);
			s1.addVariable('type','youtube');
		}
		else
		{
			s1.addParam('flashvars', 'file=' + XFLOW_str_replace('thumbs/' + preview, XFLOW_basename(url), src) + '&image=' + src + autoplay);
		}

		s1.write('xflow_viewervideo');

		xflow_viewerimageholder.style.height = (xflow_viewerimageholder.offsetHeight + xflow_viewertext.offsetHeight) - 12 + 'px';

		XFLOW_centreViewer(40);
	}
	else
	{
		xflow_isvideo = false;
		return false;
	}
}

function XFLOW_openViewer(img)
{
	if(!XFLOW_isImgLoaded(xflow_preloadedimgs[parseFloat(img.id)]))
	{
		XFLOW_overlay(true, '<h2>Still preloading this image!</h2><p>Please be patient...</p>');

		var t = setTimeout(function(t)
		{
			XFLOW_overlay(false, false);
			clearTimeout(t);
		},  1000);

		return false;
	}
	else
	{
		XFLOW_updateImageViewer(parseFloat(img.id), false);
	}
}

function XFLOW_updateImageViewer(i, h)
{
	xflow_viewervideo.innerHTML = '';

	img = xflow_imgarray[i];

	XFLOW_setViewerImage(xflow_preloadedimgs[i].src, img.alt, img.title, img.rel, i);

	xflow_imageid = i;

	if(h)
	{
		i = XFLOW_handle(i, true);
	}
}

function XFLOW_setViewerImage(src, alt, txt, rel, i)
{

	if(!XFLOW_isImgLoaded(xflow_viewermainimage))
	{
		var t = setTimeout(function(src, alt, txt, rel, i, t)
		{
			XFLOW_setViewerImage(src, alt, txt, rel, i);
		}, 1);
	}
	else
	{

		xflow_viewermainimage.src = src;
		xflow_viewermainimage.alt = alt;
		
		XFLOW_resizeImage(xflow_imgarray[i]);

		var imgTitle = XFLOW_getByClassName('xflow_imagetitle', 'p');
		var imgDesc = XFLOW_getByClassName('xflow_imagetext', 'p');

		imgTitle.innerHTML = alt;
		imgDesc.innerHTML = XFLOW_convertURL(txt);

		if(document.getElementById('code_' + i))
		{
			imgDesc.innerHTML += XFLOW_safeHTML(document.getElementById('code_' + i).value);
		}

		if(!xflow_vieweropen)
		{
			XFLOW_viewerDisplay('show');
		}

		xflow_viewerimageholder.style.width = xflow_viewermainimage.offsetWidth + 'px';
		xflow_viewerimageholder.style.height = xflow_viewermainimage.offsetHeight + 'px';

		XFLOW_video(xflow_imgarray[i]);
		
		if(xflow_isvideo)
		{
			xflow_viewertext.style.display = 'block';

			xflow_viewerimageholder.onmouseover = function()
			{
				xflow_viewertext.style.display = 'block';

			}

			xflow_viewerimageholder.onmouseout = function()
			{
				xflow_viewertext.style.display = 'block';
			}
		}
		else
		{

			xflow_viewerimageholder.onmouseover = function()
			{
				xflow_viewertext.style.display = 'block';


			};

			xflow_viewerimageholder.onmouseout = function()
			{
				xflow_viewertext.style.display = 'none';
			};

		}

		XFLOW_setViewerTextSize(200);

		xflow_viewermainimage.onclick = function()
		{
			/* use this to capture a click on the main image! */
		};

		XFLOW_viewerControls(i);
	}
}

function XFLOW_viewerControls(i)
{
	xflow_viewerleftcontrol.style.display = 'block';
	xflow_viewerrightcontrol.style.display = 'block';

	if(i == 0)
	{
		xflow_viewerleftcontrol.style.display = 'none';
	}

	if(i >= (xflow_array_images.length - 1))
	{
		xflow_viewerrightcontrol.style.display = 'none';
	}
}

function XFLOW_setViewerTextSize(val)
{
	xflow_viewertext.style.height = 'auto';

	if(xflow_viewertext.style.overflow)
	{
		xflow_viewertext.style.overflow = 'none';
	}

	if(xflow_viewertext.offsetHeight > val)
	{
		xflow_viewertext.style.height = val + 'px';
		xflow_viewertext.style.overflowY = 'auto';
	}
}

function XFLOW_resizeImage(img)
{
	/* get image dimensions */
	imgSize = img.className.split(':');
	imgWidth = parseFloat(imgSize[0]);
	imgHeight = parseFloat(imgSize[1]);

	/* arbitrary value to get a nice image size! */
	var xBy = 120;

	/* resize the image */
	if((imgHeight + xBy) > xflow_browser['H'])
	{
		xflow_viewermainimage.style.width = 'auto';
		xflow_viewermainimage.style.height = Math.round(xflow_browser['H'] - xBy) + 'px'; 
	}
	else if((imgWidth + xBy) > xflow_browser['W'])
	{
		xflow_viewermainimage.style.width = Math.round(xflow_browser['W'] - xBy) + 'px';
		xflow_viewermainimage.style.height = 'auto'; 
	}
	else
	{
		xflow_viewermainimage.style.width = imgWidth + 'px';
		xflow_viewermainimage.style.height = imgHeight + 'px'; 
	}
	
	XFLOW_centreViewer();
}

function XFLOW_centreViewer(offset)
{
	if(!offset)
	{
		offset = 5;
	}
	var top = Math.round((xflow_browser['H'] / 2) - parseInt(XFLOW_str_replace('px','',xflow_viewermainimage.style.height)) / 2) - offset + 'px';
	xflow_viewerimageholder.style.top = top;
}

function XFLOW_getBrowserInfo()
{
	xflow_browser = new Array();

	if( typeof( window.innerHeight ) == 'number' ) 
	{
		xflow_browser['W'] = window.innerWidth;
		xflow_browser['H'] = window.innerHeight;
	} 
	else 
	{
		xflow_browser['W'] = document.documentElement.clientWidth;
		xflow_browser['H'] = document.documentElement.clientHeight;
	}

	return xflow_browser;
}

function XFLOW_viewerDisplay(val)
{
	if(val == 'show')
	{
		xflow_imageviewer.style.display				= 'none';
		xflow_viewerimageholder.style.display		= 'block';
		xflow_viewermainimage.style.display			= 'block';
		xflow_viewerclosecontrol.style.display		= 'block';
		xflow_viewertext.style.display				= 'block';
		xflow_imageviewer.style.display				= 'block';
		xflow_vieweropen = true;
	}
	if(val == 'hide')
	{
		xflow_viewerimageholder.style.display		= 'none';
		xflow_viewermainimage.style.display			= 'none';
		xflow_viewerclosecontrol.style.display		= 'none';
		xflow_viewertext.style.display				= 'none';
		xflow_imageviewer.style.display				= 'none';
		xflow_vieweropen = false;
	}
	if(val == 'loading')
	{
		xflow_viewerimageholder.style.display		= 'none';
		xflow_viewermainimage.style.display			= 'none';
		xflow_viewerclosecontrol.style.display		= 'none';
		xflow_viewertext.style.display				= 'none';
		xflow_imageviewer.style.display				= 'block';
		xflow_vieweropen = true;
	}
}

function XFLOW_closeViewer()
{
	XFLOW_stopPlayer();
	XFLOW_viewerDisplay('hide');
}

/* Change opacity for image (cross browser) */
function XFLOW_changeOpac(opacity, obj) 
{
	var object = obj.style;
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = 'alpha(opacity=' + opacity + ')';
}

/* Handle the wheel angle change (delta) of the mouse wheel */
function XFLOW_handle(delta, ret)
{
	var change = false;
	switch (delta > 0)
	{
		case true:
			if(xflow_caption_id >= 1)
			{
				xflow_target = xflow_target + xflow_xstep;
				xflow_new_caption_id = xflow_caption_id - 1;
				change = true;
			}
			break;

		default:
			if(xflow_caption_id < (xflow_max-1))
			{
				xflow_target = xflow_target - xflow_xstep;
				xflow_new_caption_id = xflow_caption_id + 1;
				change = true;
			}
			break;
	}
	
	/* Glide to next (mouse wheel down) / previous (mouse wheel up) image */
	if (change == true)
	{
		XFLOW_glideTo(xflow_target, xflow_new_caption_id);
	}
	
	/* update main viewer if it's open */
	if(xflow_vieweropen)
	{
		XFLOW_updateImageViewer(xflow_new_caption_id, false);
	}

	if(ret) return xflow_new_caption_id;
}

/* Event handler for mouse wheel event, also will capture and move xflow_imageviewer accordingly */
function XFLOW_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)
	{
		var n = XFLOW_handle(delta, true);

		/* update main viewer if it's open */
		if(xflow_vieweropen)
		{
			XFLOW_updateImageViewer(n, false);
		}
	}
	if (event.preventDefault) event.preventDefault();
	event.returnValue = false;
}

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

/* This function is called to drag an object (= slider div) */
function XFLOW_dragStart(element)
{
	xflow_dragobj = element;
	xflow_dragx = xflow_posx - xflow_dragobj.offsetLeft + xflow_new_slider_pos;
}

/* This function is called to stop dragging an object */
function XFLOW_dragStop()
{
	xflow_dragobj = null;
	xflow_dragging = false;
}

/* Initialize mouse event listener */
function XFLOW_initMouseDrag()
{
	document.onmousemove = XFLOW_drag;
	document.onmouseup = XFLOW_dragStop;
}


/* Capture keyboard actions */
document.onkeydown = function(ev) 
{
    ev = ev || window.event;
    kCode = ev.keyCode || ev.which;

	/* Login: ctrl + shift + x */
    if (ev.ctrlKey && ev.shiftKey && kCode == 19 || ev.ctrlKey && ev.shiftKey && kCode == 88) 
	{
		/* grab a string from a .js file path and parse it to get root location, append admin dir and redirect */
		document.location.href = XFLOW_str_replace('js/xflow_global.js', '', document.getElementById('globalscript').src) + 'admin' + (XFLOW_getByClassName('xflow_adminlinks','fieldset') ? '?logout=true' : '');
        return false;
    }

	/* P key */
	if(kCode == 80)
	{
		if(xflow_vieweropen)
		{
			XFLOW_playpause();
		}
		else
		{
			XFLOW_stopPlayer();
		}
	}

	/* Right arrow */
	if(kCode == 39)
	{
		XFLOW_handle(-1);
	}

	/* Left arrow */
	if(kCode == 37)
	{
		XFLOW_handle(1);
	}

	/* Escape */
	if(kCode == 27)
	{
		if (xflow_vieweropen)
		{
			XFLOW_closeViewer();
		}
	}

	/* Enter */
	if(kCode == 13)
	{
		if (xflow_vieweropen)
		{
			XFLOW_closeViewer();
		}
		else
		{
			XFLOW_openViewer(document.getElementById(xflow_new_caption_id));

		}
	}
};

/* Convert textual links to actual urls */
function XFLOW_convertURL(text)
{
	if( !text ) return text;
	text = text.replace(/((https?\:\/\/|ftp\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,function(url){
	nice = url;
	if( url.match('^https?:\/\/') )
	{
		nice = nice.replace(/^https?:\/\//i,'');
	}
	else
		url = 'http://'+url;
		return '<a href="'+ url +'">'+ nice.replace(/^www./i,'') +'</a>';
	});
	return text;
}

/* XFLOW_setUp xflow on window resize */
//window.onresize = function()
//{
//	if(XFLOW_getByClassName('xflow'))
//	{
//		XFLOW_setUp(false);
//	}
//};

/* start code */
XFLOW_addLoadEvent(XFLOW_init);




