var cancleLightboxClick = false;
var overlay = $(jQuery('<div id="overlay" style="display: none"></div>'));
var container = $(jQuery('<div id="lightbox" style="display: none"></div>'));
var target = $(jQuery('<div class="target"></div>'));
var head = $(jQuery("<h2></h2>"));
var info = $(jQuery("<span></span>"));
var closeButton = $(jQuery('<div class="close"><img src="/js/capica_lightbox/close.png" alt=""></div>'));
var flvobj = $(jQuery("<div id=\"flashobj\"></div>"));
var prev = $(jQuery('<a href="#prev" class="prev"><img src="/js/capica_lightbox/left.gif" alt=""></a>'));
var next = $(jQuery('<a href="#next" class="next"><img src="/js/capica_lightbox/right.gif" alt=""></a>'));
var relPages = $(jQuery('<div class="relpages"></div>'));
var relLink = $(jQuery('<a href="#"></a>'));
var lightBoxOn = false;
var listlinks;
var linkspopup;
var arrlinks;
var activeRel;
var activeIndex;
var activeClick;

function lightbox() {
	//linkspopup = $('a[target^=popuplink]');
	
	$('body').append(overlay).append(container);
	
	dh = $(document.body).height();
	wh = $(window).height();
	h = dh > wh ? dh : wh;
	overlay.css('width', $(window).width());
	overlay.css('height', h);
	
	container.append(closeButton);
	container.append(target);
	container.append(flvobj);
	
	container.append(head);
	container.append(info);

	container.append(relPages);
	container.append(prev);
	container.append(next);
	
	container.show().css({
				'top': Math.round(($(window).height() - container.outerHeight()) / 2) + 'px',
				'left': Math.round(($(window).width() - container.outerWidth()) / 2) + 'px',
				'marginTop': 0,
				'marginLeft': 0
				}).hide();
	
	closeButton.click(function(c) {
		c.preventDefault();
		closeLightbox();
	});
	overlay.click(function() {
		closeLightbox();
	})
	
	prev.add(next).click(function(c) {
		c.preventDefault();
		
		if(arrlinks[activeRel]) {
			if($(this).is('.prev')) {
				activeIndex--;
				if(activeIndex < 0) {
					activeIndex = arrlinks[activeRel].length-1;
				}
			} else {
				activeIndex++;
				if(activeIndex >= arrlinks[activeRel].length) {
					activeIndex = 0;
				}
			}
			to = arrlinks[activeRel][activeIndex];
			activeClick = false;
		} else {
			
			var current = parseInt(listlinks.filter('.selected').attr('lb-position'),10);
			var to = $(this).is('.prev') ? listlinks.eq(current - 1) : listlinks.eq(current + 1);
			if(!to.size()) {
				to = $(this).is('.prev') ? listlinks.eq(listlinks.size() - 1) : listlinks.eq(0);
			}
			
		}
		if(to.size()) {
			to.click();
		}
	});
	
	
	$(document).keyup(function(evt) {
		if (evt.keyCode == '27') {
			closeLightbox();
		}
		if(lightBoxOn) {
			if (evt.keyCode == 37) {
				prev.click();
			}
			if (evt.keyCode == 39) {
				next.click();
			}
		}
	});
}

function closeLightbox() {
	lightBoxOn = false;
	overlay.add(container).fadeOut('normal');
	flvobj.children().remove();
}
function openImage(url, t, ii) {
	prev.hide();
	next.hide();

	if(activeRel) {
		relPages.children().removeClass("active");
		relPages.children().eq(activeIndex).addClass("active");
	}
	if(container.is(':visible')) {
		if(target.children().children().length > 0) {
			target.children().fadeOut('normal', function() {
				target.children().remove();
				flvobj.children().remove();
				loadimage(url, t, ii);
			});
		} else {
			target.children().remove();
			flvobj.children().remove();
			loadimage(url, t, ii);
		}
	} else {
		target.children().remove();
		overlay.add(container).fadeIn('normal',function(){
			loadimage(url, t, ii);
		});
	}
}


function loadpage(u, t) {
	if(container.is('.loading')) { 
		return; 
	}
	container.addClass('loading');
	lightBoxOn = true;
	
	$.get(u, function(data) {
		head.text(t);
		wdh = 800;
		hgt = 650;
		_top = Math.round(($(window).height() - hgt - 75 - parseInt(container.css('padding-top'),10) - parseInt(container.css('padding-bottom'),10)) / 2) + $(window).scrollTop();
		
		container.animate({'width': wdh,'height': hgt + 50, 'top': _top + 'px', 'left': Math.round(($(document).width() - wdh - parseInt(container.css('padding-left'),10) - parseInt(container.css('padding-right'),10)) / 2) + 'px'},'normal', function(){
			
			target.html($("#small", data).html());
			container.removeClass('loading');
			initForm();
		});
	});
	
}
function openlink(url, t) {
	
	prev.hide();
	next.hide();
	
	if(container.is(':visible')) {
		target.children().fadeOut('normal', function() {
			target.children().remove();
			loadpage(url, t);
		});
	} else {
		target.children().remove();
		overlay.add(container).fadeIn('normal',function(){
			loadpage(url, t);
		});
	}
}
function openrel(rr, t) {
	
	prev.hide();
	next.hide();
	
	if(container.is(':visible')) {
		target.children().fadeOut('normal', function() {
			target.children().remove();
			loadrel(rr, t);
		});
	} else {
		target.children().remove();
		overlay.add(container).fadeIn('normal',function(){
			loadrel(rr, t);
		});
	}
}

function loadrel(rr, t) {
	if(container.is('.loading')) { 
		return; 
	}
	container.addClass('loading');
	lightBoxOn = true;
	
	var content = $("#" + rr).html();
	
	head.text(t);
	wdh = 800;
	var maxHeight = $(window).height() - 200;
	hgt = 650;
	if(maxHeight < hgt) {
		hgt = maxHeight;
	}
	_top = Math.round(($(window).height() - hgt - 75 - parseInt(container.css('padding-top'),10) - parseInt(container.css('padding-bottom'),10)) / 2) + $(window).scrollTop();
	
	
	container.animate({'width': wdh,'height': hgt + 50, 'top': _top + 'px', 'left': Math.round(($(document).width() - wdh - parseInt(container.css('padding-left'),10) - parseInt(container.css('padding-right'),10)) / 2) + 'px'},'normal', function(){
		target.html(content);
		if(maxHeight < target.outerHeight()) {
			target.css("height", maxHeight-1);
			target.css("overflow", "auto");
		} else {
			target.css("overflow", "auto");
		}
		
		container.removeClass('loading');
		initForm();
	});
	
}

function loadimage(url, t, ii) {
	if(container.is('.loading')) { return; }
	container.addClass('loading');
	lightBoxOn = true;
	
	if(url.indexOf("swf") > -1) {
		wid = 850;
		hei = 550;
		_top = Math.round(($(window).height() - hei - 75 - parseInt(container.css('padding-top'),10) - parseInt(container.css('padding-bottom'),10)) / 2) + $(window).scrollTop();
		_left = Math.round(($(document).width() - wid - parseInt(container.css('padding-left'),10) - parseInt(container.css('padding-right'),10)) / 2);
		var swf = url;
		head.text(t);
		info.text(ii);
		
		container.animate({'width': (wid+20) + "px",'height': hei + "px", 'top': _top + 'px', 'left': _left + 'px'}, 'normal', function(){
			flvobj.show();
			flvobj.css("width", (wid) + "px");
			flvobj.css("height", (hei) + "px");
			$("#flashobj").flashembed("/flashbook/pageflip_loader.swf", {"bgColor":"#0f455c"});
		});
		
	} else if(url.indexOf("flv") > -1 || url.indexOf("mp4") > -1) {
		wid = 750;
		hei = 450;
		_top = Math.round(($(window).height() - hei - 75 - parseInt(container.css('padding-top'),10) - parseInt(container.css('padding-bottom'),10)) / 2) + $(window).scrollTop();
		_left = Math.round(($(document).width() - wid - parseInt(container.css('padding-left'),10) - parseInt(container.css('padding-right'),10)) / 2);
		var flv = url;
		head.text(t);
		info.text(ii);
		
		container.animate({'width': (wid+20) + "px",'height': hei + "px", 'top': _top + 'px', 'left': _left + 'px'}, 'normal', function(){
		
			target.hide();
			flvobj.show();
			flvobj.css("width", (wid) + "px");
			flvobj.css("height", (hei) + "px");
		
			flowplayer("flashobj", {
				src: "/flowplayer/flowplayer.commercial-3.2.7.swf",
				version: [9, 115],
				onFail: function()  {
					document.getElementById("info").innerHTML =
					"You need the latest Flash version to view MP4 movies. " +
					"Your version is " + this.getVersion()
					;
				}
			}, {
				key: '',
				clip:{
					url:flv,
					scaling:'fit'
				}
			});
		
			container.removeClass('loading');
		});
	} else {
		var img = new Image();
		img.onload = function() {
			img.style.display = 'none';
			
			var maxWidth = ($(window).width() - parseInt(container.css('padding-left'),10) - parseInt(container.css('padding-right'), 10)) - 100;
			var maxHeight = ($(window).height() - parseInt(container.css('padding-top'),10) - parseInt(container.css('padding-bottom'), 10)) - 150;
			if(img.width > maxWidth || img.height > maxHeight) { // One of these is larger than the window
				var ratio = img.width / img.height;
				if(img.height >= maxHeight) {
					img.height = maxHeight;
					img.width = maxHeight * ratio;
				} else {
					img.width = maxWidth;
					img.height = maxWidth * ratio;
				}
			}
			
			//head.text(t);
			head.text(t);
			flvobj.hide()
			target.show();
			target.animate({'width': img.width,'height': img.height}, 'normal');
			_top = Math.round(($(window).height() - img.height - 75 - parseInt(container.css('padding-top'),10) - parseInt(container.css('padding-bottom'),10)) / 2) + $(window).scrollTop();
			container.animate({'width': img.width+20,'height': img.height+0, 'top': _top + 'px', 'left': Math.round(($(document).width() - img.width - parseInt(container.css('padding-left'),10) - parseInt(container.css('padding-right'),10)) / 2) + 'px'},'normal', function(){
				target.append(img);
				$(img).fadeIn('normal', function() {
					prev.show();
					next.show();
					container.removeClass('loading');
				});
			})
		}
		img.src = url;
	}
}
function initlinks () {
	activeClick = true;
	arrlinks = [];
	listlinks = $('a[target^=popup]');
	listlinks.each(function(index) {
		var l = $(this);
		var r = l.attr("rel");
		l.attr("lb-position", index);
		if(r) {
			if(arrlinks[r]) {
			} else {
				arrlinks[r] = [];
			}
			al = arrlinks[r].length;
			arrlinks[r][al] = l;
		}
	});
	
}
var listlinks;
$(document).ready(function() {
	lightbox();
	initlinks();
	
	$('a[target^=poplink]').live("click", function(c) {
		var l = $(this);
		c.preventDefault();
		if(l.attr('href') == "#") {
			openrel(l.attr('rel'), l.attr('title'));
		} else {
			openlink(l.attr('href'), l.attr('title'));
		}
		return false;
	});
	
	$('a[target^=popup]').live("click", function(c) {
		
		var l = $(this);
		activeRel = l.attr("rel");
		if(activeClick) {
			activeIndex = 0;
			activeIndex = initLighboxPages(this);
		}
		activeClick = true;
		
		c.preventDefault();
		openImage(l.attr('href'), l.attr('title'), l.attr('info'));
		listlinks.filter('.selected').removeClass('selected');
		l.addClass('selected');
	});
	
	var initLighboxPages = function(w) {
		ch = $(w).attr("href");
		num = 0;
		relPages.children().remove();
		if(activeRel) {
			len = arrlinks[activeRel].length;
			if(len > 1) {
				for(i = 0 ; i < len ; i++) {
					if(ch == $(arrlinks[activeRel][i]).attr("href")) {
						num = i;
					}
					l = relLink.clone();
					relPages.append(l);
					l.click(function() {
						var me = $(this);
						activeIndex = me.index();
						activeClick = false;
						arrlinks[activeRel][activeIndex].click();
					});
				}
			}
		}
		return num;
	}
});

