function popSlideshow(url, caption) 
{
	$.slimbox(url, caption);
}

// This function creates a new anchor element and uses location
// properties (inherent) to get the desired URL data. Some String
// operations are used (to normalize results across browsers).
 
function parseURL(url) {
	var a =  document.createElement('a');
	a.href = url;
	return {
		/*
		source: url,
		protocol: a.protocol.replace(':',''),
		host: a.hostname,
		port: a.port,
		query: a.search,
		hash: a.hash.replace('#',''),
		path: a.pathname.replace(/^([^\/])/,'/$1'),
		relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
		segments: a.pathname.replace(/^\//,'').split('/'),
		*/
		file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
		params: (function(){
         var ret = {},
             seg = a.search.replace(/^\?/,'').split('&'),
             len = seg.length, i = 0, s;
         for (;i<len;i++) {
             if (!seg[i]) { continue; }
             s = seg[i].split('=');
             ret[s[0]] = s[1];
         }
         return ret;
		})()
    };
}

function showFlash(rssfeed, force)
{
	var ie6	= !window.XMLHttpRequest;

	var overlay, flashbox, compatibleOverlay;

	overlay = $('#gtOverlayFlash');
	flashbox = $('#gtFlashBox');

	flashvars = {};
	popAttr = {
		video: false
	}
	
	/*
	flashvars = {	
		useExternalInterface : true,
		initialURL: escape(document.location)
	}
	*/

	// are we serving video?
	//
	var isVideo = rssfeed.indexOf("vid=") != -1;
	var isVimeo = rssfeed.indexOf("vim=") != -1;

	if (isVideo) {
		flashvars.paramXMLPath = "/wp-content/plugins/slidepress/tools/param.php?gid=video";
		flashvars.xmlFilePath = "/gt_videofeed.php?" + rssfeed;
		popAttr.video = true;
	}
	else if (isVimeo) {
		flashvars.clip_id = rssfeed.slice(4);
		flashvars.show_portrait = 0;
		flashvars.show_byline = 0;
		flashvars.show_title = 0;
		flashvars.js_api = 1;
		flashvars.autoplay = 1;
		popAttr.video = true;
	}
	else {
		// find content ID to start with
		//
		var startID = $('div[id^=ngg-image]:visible');
		startID = startID.attr("id").slice(10);

		flashvars.paramXMLPath = "/wp-content/plugins/slidepress/tools/param.php?gid=popFlash";
		flashvars.startAlbumID = rssfeed.slice(4);
		flashvars.startContentID = startID;
		flashvars.xmlFilePath = "/wp-content/plugins/nextgen-gallery/xml/ssp-rss.php?" + rssfeed;
		popAttr.video = false;
	}

	// process force param
	//
	if (!isVimeo) {
		var arr = force.split(',');
		var x, y;
		for (x in arr)
		{
			y = arr[x].split(':');
			flashvars[y[0]] = y[1];
		}
	}

	if (isVimeo) {
		swfobject.embedSWF("http://vimeo.com/moogaloop.swf", "flashcontent", "100%", "100%", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
	}
	else {
		swfobject.embedSWF("/wp-content/uploads/slidepress/flash/slideshowpro.swf", "flashcontent", "100%", "100%", "9.0.0", false, flashvars, params, attributes);
	}

	compatibleOverlay = ie6 || (overlay.currentStyle && (overlay.currentStyle.position != "fixed"));
	if (compatibleOverlay) {
		overlay.style.position = "absolute";
	}

	flashResize();
	overlay.css({ "opacity" : 0.8 }).fadeIn(400);
	flashbox.fadeIn(400);
	$('.closeButtonParent').data('t', setTimeout("$('.closeButton').fadeOut('slow')", 3000));

	$(document).keydown(keyDown);

}

function flashResize()
{
	var	documentElement	= document.documentElement, 
			operaFix				= window.opera && (document.compatMode == "CSS1Compat") && ($.browser.version >= 9.3),
			win					= $(window);

	var nonWide = (flashvars.nonWide === 'true' || !flashvars.nonWide) ? 1.5 : flashvars.nonWide;

	var	ww	= (operaFix ? documentElement.clientWidth : win.width()),
			hh	= operaFix ? documentElement.clientHeight : win.height(),
			h	= Math.min(750, Math.round(hh * 0.97));

	var w = (nonWide) ? h * nonWide : ww - 40;

	if (popAttr.video == true) {
		w = 832;
		h = 468;
	}

	var	l = (ww / 2) - (w / 2),
			t = (hh / 2) - (h / 2);

	$('#gtFlashBox').css( { 'left': l - 5, 'top' : win.scrollTop() + t, 'height': h, 'width': w } );
}

function closeFlash()
{
	$('#gtOverlayFlash').fadeOut(400);
	$('#gtFlashBox').hide();
	$(document).unbind('keydown');
}

function keyDown(event) {
	
	// Array of keycodes to close Slimbox, default: Esc (27), 'x' (88), 'c' (67)
	//
	switch (event.keyCode)
	{
		case 27:
		case 88:
		case 67:
			closeFlash();
			return false;
			break;

		default:
			return true;
	}
}

$(document).ready(function() {

	// popflash interaction
	//
	$(function() {
		/*
		$('.popflash').hover(
			function(){
				$(this).css( { 'border': '1px solid red' } );
			},
			function(){
				$(this).css( { 'border': 'none' } );
			}
		);*/
	});

	// $.extend($.fn.jScrollPane.defaults, {showArrows:true});
	// $.extend($.fn.jScrollPane.defaults, {showArrows:false, dragMaxHeight:30});

	$('h2.widgettitle.entry-title', '#ngg-images-2').append('<span id="gtrefbutton" class="rndimgrefresh" />').click(gtrefresh);
	$('h3.entry-title', "div[id^='ngg-images']").append('<span id="gtrefbutton" class="rndimgrefresh" />').click(gtrefresh);

	// $('.ngg-widget.entry-content', '#ngg-images-2').wrap('<div class="randimage" id="ajax" />').attr('id', 'randimg');
	$('.ngg-widget.entry-content', "div[id^='ngg-images']").wrap('<div class="randimage" id="ajax" />').attr('id', 'randimg');
	$('#ajax').append('<div id="tmpdiv" />')
	$('#tmpdiv').css( {'display' : 'none' } ).data('fetch', 0);

	$('object[id^=ssp]').css( { 'outline': 'none' } );

	// pre-load gallery images on load
	//
	$("div[id^='ngg-gallery-']").each(function() {
	   var tmp = $('.gallery_tmp',this);
	   var that = $(this);

	   $(this).addClass("lbLoading tmpdiv");

	   $('img',tmp).hide();
	   preloadImgs($('img',tmp), function() {
	      that.removeClass("lbLoading tmpdiv");
	      that.html(tmp.html()).ready(function() {
	         $('.ngg-navigation a',this).click(galleryNav);
	         reSlimbox();
	      });
	      $('img',that).fadeIn("slow");
			$('.gtNGScroll', that).jScrollPane();
	   });
	});

	// flash stuff
	//
	$(function() {

		$('<div id="gtOverlayFlash" />').appendTo($("body")).css({ 'display': 'none' }).click(closeFlash);
		$('<div id="gtFlashBox" />').appendTo($("body")).css({ 'display': 'none' });

		$('#gtFlashBox').append('<div id="flashcontent"><p>This SlideShowPro photo gallery requires the Flash Player plugin and a web browser with JavaScript enabled.</p></div>');
		$('<div class="closeButtonParent"></div>').appendTo($('#gtFlashBox'));
		$('<div class="closeButton"></div>').appendTo($('.closeButtonParent')).click(closeFlash);

		$('.closeButtonParent').hover(
			function(){
				if ($(this).data('t')) clearTimeout($(this).data('t'));
				$('.closeButton').show();
			},
			function(){
				$(this).data('t', setTimeout("$('.closeButton').fadeOut('slow')", 3000));
			}
		);

	//+ 'paramXMLPath: "/wp-content/plugins/slidepress/tools/param.php?gid=popFlash",\n'

		var script = 'var flashvars = {\n'
							+ 'initialURL: escape(document.location),\n'
							+ 'useExternalInterface : true\n'
							+ '};\n';

		script += 'var params = { \n'
					+ 'base: ".",\n'
					+ 'bgcolor: "#121212",\n'
					+ 'wmode: "transparent",\n'
					+ 'allowfullscreen: "true",\n'
					+ 'allowScriptAccess: "always"\n'
					+ '};\n';

		script += 'var attributes = {};\n'
						+ 'var popAttr = {};\n';
		var el  = document.createElement('script');
		el.type = 'text/javascript';
		el.text = script;
		$('#gtFlashBox').append(el);
		
		$(window).resize(flashResize);

	});

	// overlay for ajax navs
	//
	if (	$('.ngg-galleryoverview .ngg-navigation a').length ) {
		var win = $(window);
		var mn = $('#container');
		var gt_overlay = $('<div id="gtOverlay" />').appendTo($('#wrap')).css("display", "none");
		var gt_wait = $('<div id="gtWait" class="lbLoading" />').appendTo($('#wrap'));
		var nt = $('#main .content').position();
		var navdiv = $('<div id="navtmpdiv" />').appendTo($('body')).css("display", "none");
	
		gt_wait.css({ left: win.scrollLeft() + ((win.width())/2) - 180, top: win.scrollTop()+ 300, 'z-index': '9999', 
					'-moz-border-radius': 10,
					width: 360, height:64, display: 'none', position: 'absolute' });
		gt_overlay.css( { left : mn.offset().left, top: mn.offset().top, width : mn.width(), 
				height: mn.height(), 'opacity' : 0.8});
	
		// $('.ngg-albumoverview .ngg-navigation a').click(albumNav);
		// $('.ngg-album a').attr("target","_blank");
		$('.ngg-galleryoverview .ngg-navigation a').click(galleryNav);

	}

function galleryNav() {
   var myURL = parseURL($(document)[0].URL);

   if (myURL.params.hasOwnProperty('gid')) {
      var url = this.href + '?gid=' + myURL.params.gid + " .gallery_tmp > *";
   }
   else {
      var url = this.href + " .gallery_tmp > *";
   }

   gt_overlay.css( { left : mn.offset().left, 'top': mn.offset().top,
      width : mn.width(), height: mn.height(), 'opacity' : 0.8}).fadeIn(400, function() {

      gt_wait.css({ left: win.scrollLeft() + ((win.width())/2) - 180,
            top: win.scrollTop() + 200  }).show();

      navdiv.load(url, null, function() {
         preloadImgs($('#navtmpdiv img'), function() {
            $('#main .content .ngg-galleryoverview').html(navdiv.html()).ready(function() {
               $('.ngg-navigation a',this).click(galleryNav);
            });
            navdiv.empty();
            gt_overlay.css( { 'height': mn.height(), 'left': mn.offset().left } );
            // $('.ngg-galleryoverview .ngg-navigation a').click(galleryNav);
            reSlimbox();
            gt_wait.fadeOut(200);
            gt_overlay.fadeOut(400);
         });
      });

   });
   return false;
}

function galleryNav2() {
	var myURL = parseURL($(document)[0].URL);

	if (myURL.params.hasOwnProperty('gid')) {
		var url = this.href + '?gid=' + myURL.params.gid + " .ngg-galleryoverview";
	}
	else {
		var url = this.href + " .ngg-galleryoverview";
	}

	gt_overlay.css( { left : mn.offset().left, 'top': mn.offset().top, 
		width : mn.width(), height: mn.height(), 'opacity' : 0.8}).fadeIn(400, function() {

		gt_wait.css({ left: win.scrollLeft() + ((win.width())/2) - 180, 
				top: win.scrollTop() + 200  }).show();

		navdiv.load(url, null, function() {
			preloadImgs($('#navtmpdiv img'), function() {
				$('#main .content .ngg-galleryoverview').replaceWith(navdiv.html());
				navdiv.empty();
				gt_overlay.css( { 'height': mn.height(), 'left': mn.offset().left } );
				$('.ngg-galleryoverview .ngg-navigation a').click(galleryNav);
				reSlimbox();
				gt_wait.fadeOut(200);
				gt_overlay.fadeOut(400);
			});
		});

	});
	return false;
}

function preloadImgs(obj, func)
{
	var i = obj.length;
	var cache = [];

	obj.each(function() {
		var cacheImage = document.createElement('img');
		cacheImage.onload = function(){
			if (--i < 1)
				func();
		}
		cacheImage.src = $(this).attr('src');
		cache.push(cacheImage);
	});
}

function albumNav() {
	// $("#links").load("/Main_Page #jq-p-Getting-Started li");
	// 
	var ht = $('.ngg-albumoverview').height();
	$('.ngg-albumoverview').addClass("lbLoading").height(ht);
	$('.ngg-albumoverview > *').remove();
	$('#main .content').load(this.href + " .ngg-albumoverview", null, function() {
		$('.ngg-albumoverview .ngg-navigation a').click(albumNav);
		// $('.ngg-album a').attr("target","_blank");
	});
	return false;
}

function gtrefresh() {
	doit();
	$('#gtrefbutton').data('clicked', 1);
}

function reSlimbox() {
   $("a[rel^='lightbox']").slimbox({/* Put custom options here */},
      function(el) {

         var sTitle ='';

         if (el.title.length) {
            var s = el.title.split('|');

            sTitle = '<b>' + s[0] + '</b>';

            if (s.length == 2)
               sTitle = sTitle + '<br>' + s[1];
            sTitle = sTitle + '|';
         }

         var sCaption = sTitle + ( (el.nextSibling && el.nextSibling.firstChild && el.nextSibling.firstChild.nodeValue) || '');

         return [el.href, sCaption];
         },
      function(el) { return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel)); }
   );
}

function doit() {

	// check if we've fetched and have not been reset
	//
	if ($('#tmpdiv').data('fetch') == 1) {
		return;
	}
	else {
		$('#tmpdiv').data('fetch', 1);
	}

	var url = "/wp-content/plugins/nextgen-gallery/widgets/gt_randimage.php";

	if ($('h3.entry-title').length)
		url += " .ngg-widget > *";

	$('#tmpdiv').load(url, {}, function() {

		$('#tmpdiv').data('fetch',0);

		// preload images
		//
		preloadImgs($('#tmpdiv img'), function() {
			$('#randimg').fadeTo(2000, 0, function() {

				$('#randimg').html($('#tmpdiv').html());
				// $('#randimg').html($('#tmpdiv')[0].innerHTML);
				$('#randimg').contents().filter(function() { return this.nodeType == 3; }).remove();
				$('#tmpdiv').empty();
				reSlimbox();
				$('#randimg').fadeTo(2000, 1);
			});
		});
	});

}

setInterval(function(){

	if ($('#lbOverlay1').is(":visible") || $('#gtFlashBox').is(":visible") ) {
		return;
	}

	// we'll miss a cycle if we've been manually refreshed
	//
	if ($('#gtrefbutton').data('clicked') == 1) {
		$('#gtrefbutton').data('clicked', 0);
		return;
	}

	if ($('#randimg').length)
		doit();

}, 12000);

});

