/**
 * clearFusionCMS lightbox.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS
 * @copyright Copyright (c) 2012 - 2014 fusionLib. All rights reserved.
 * @link http://clearFusionCMS.com
 */

$fl(document).ready(function() {

	// Look through style sheets for lightbox CSS rules
	var hasLightboxCSS = false,
		lightboxOpen = false;
	r = new RegExp('\\#cfLightbox\\b','i');
	var sheets = document.styleSheets;
	for(var i=0;i<sheets.length && !hasLightboxCSS;i++) {
		try {
			var rules = sheets[i].rules ? sheets[i].rules : sheets[i].cssRules;
			if(rules) {
				for(var n=0;n<rules.length && !hasLightboxCSS;n++) {
					var s = rules[n].selectorText ? rules[n].selectorText : rules[n].cssText;
					if(r.test(s))
						hasLightboxCSS = true;
				}
			}
		} catch(e) {}
	}

	// If no lightbox CSS then load our default CSS
	if(!hasLightboxCSS) {
		var link = document.createElement("link");
		link.rel = "stylesheet";
		link.href = "system/app/js/cfLightbox.css";
		document.getElementsByTagName("head")[0].appendChild(link);
	}

	// Add lightbox HTML to the page
	$fl('body').append('<div id="cfLightbox"><div id="cfLightboxContent" role="dialog" aria-labelledby="cfLightboxCaptionCtnt"><img id="cfLightboxImage" /><div id="cfLightboxCaption"><div id="cfLightboxCaptionCtnt"></div></div><div id="cfLightboxPrev"></div><div id="cfLightboxNext"></div><div id="cfLightboxClose"></div></div></div>');

	// Handle clicks off the image
	$fl('#cfLightbox').bind('click', function(evt) {
		$fl('#cfLightbox').css('display', 'none');
		lightboxOpen = false;
		evt.preventDefault();
		evt.stopPropagation();
		return false;
	});

	// Handle close
	$fl('#cfLightboxClose').bind('click', function(evt) {
		$fl('#cfLightbox').css('display', 'none');
		lightboxOpen = false;
		evt.preventDefault();
		evt.stopPropagation();
		return false;
	});

	// Escape to close
	$fl(window).bind('keyup', function(evt) {
		if(lightboxOpen && evt.keyCode == 27) {
			$fl('#cfLightbox').css('display', 'none');
			lightboxOpen = false;
			evt.preventDefault();
			evt.stopPropagation();
			return false;
		}
	});

	// Handle back/forward through images
	$fl('#cfLightboxContent').bind('click', function(evt) {
		$fl('#cfLightbox').css('display', 'none');
		var activeImg = lightboxOpen;
		lightboxOpen = false;

		// Find siblings
		var lbGrps = $fl('.cfLightbox'),
			siblings = [],
			found = false;
		for(var i=0;i<lbGrps.length && !found;i++) {
			var imgs = $fl(lbGrps[i]).find('img');
			for(var n=0;n<imgs.length;n++) {
				siblings[n] = imgs[n];
				if(imgs[n] == activeImg)
					found = true;
			}
			if(!found)
				siblings = [];
		}

		// Step forward/back 1 image
		if(found) {
			for(var n=0;n<siblings.length;n++) {
				if(siblings[n] == activeImg) {
					var d = evt.screenX - ($fl(window).width() / 2)
					if(d <= 0)
						$fl(siblings[n ? n - 1 : siblings.length - 1]).trigger('click');
					else
						$fl(siblings[(n + 1) % siblings.length]).trigger('click');
					break;
				}
			}
		}

		evt.preventDefault();
		evt.stopPropagation();
		return false;
	});

	// Attach to all the thumbs to perform lightbox
	$fl('.cfLightbox img').bind('click', function(evt) {

		$fl('#cfLightboxImage').css('display', 'none');
		$fl('#cfLightboxCaption').css('visibility', 'hidden');
		$fl('#cfLightboxContent')
			.width(60)
			.height(60)
			.css('margin-left', '-30px')
			.css('margin-top', '-30px');
		$fl('#cfLightbox').css('display', 'block');

		var parent = $fl(this);
		while(parent && !parent.hasClass('cfLightbox'))
			parent = parent.parent();
		if(parent.find('img').length > 1) {
			$fl('#cfLightboxNext').css('visibility', 'visible');
			$fl('#cfLightboxPrev').css('visibility', 'visible');
		}
		else {
			$fl('#cfLightboxNext').css('visibility', 'hidden');
			$fl('#cfLightboxPrev').css('visibility', 'hidden');
		}

		lightboxOpen = evt.target;

		// The image loader
		var loader = new Image();
		loader.onload = function(evt) {

			// Get the size of the image
			var width = loader.width,
				height = loader.height;

			// Calculate border around image
			var border = parseInt($fl('#cfLightboxImage').css('margin-top')),
				border2 = border * 2,
				border4 = border * 12;

			// If image too big to fit in the available window, scale it down
			if((width + border4) >= $fl(window).width() || (height + border4) >= $fl(window).height()) {
				var tw = $fl(window).width() - border4,
					th = $fl(window).height() - border4,
					vertRatio = th / height,
					horizRatio = tw / width;

				// Calculate the new size of the image
				if(horizRatio * height < th)
					th = horizRatio * height;
				else
					tw = vertRatio * width;

				// Set the size of the image
				loader.width = width = tw;
				loader.height = height = th;
			}

			// Set the image
			$fl('#cfLightboxImage').width(width).height(height)[0].src = loader.src;
			$fl('#cfLightboxImage').css('display', 'block');

			// Position caption
			$fl('#cfLightboxCaption')
				.width(width)
				.css('visibility', 'visible');

			// Set size of container
			var captionHeight = $fl('#cfLightboxCaption').height() - border;
			$fl('#cfLightboxContent')
				.width(width + border2)
				.height(height + border2 + captionHeight)
				.css('margin-left', (-(width + border2) / 2) + 'px')
				.css('margin-top', (-(height + border2 + captionHeight) / 2) + 'px');
		}

		// Load the large version as the popup
		// If cfLightboxReplace function is defined use it to get the URL of the large image.
		try {
			loader.src = cfLightboxReplace(evt.target.src);
		}
		catch(e) {
			loader.src = evt.target.src.replace(/\/[tsmlo]\/(.+)$/, "/l/$1");
		}

		// If image has an outer A tag then add it to caption
		if(evt.target.parentNode.href == undefined)
			$fl('#cfLightboxCaptionCtnt').html(evt.target.alt);
		else {
			$fl('#cfLightboxCaptionCtnt').html('<a href="' + evt.target.parentNode.href + '">' + evt.target.alt + ' &raquo;</a>');
			$fl('#cfLightboxCaptionCtnt a').bind('click', function(evt) {
				window.location.href = evt.target.href;
				evt.preventDefault();
				evt.stopPropagation();
				return false;
			});
		}

		evt.preventDefault();
		evt.stopPropagation();
		return false;
	});
});
