/**
 * JS
 * ajaxlightbox.js
 * 
 * @author msavary
 * Copyright 2010-2011 © USER STUDIO. All Rights Reserved.
 * 
 * ajax lightbox handling
 * 
 */


//returns the requested GET parameter from the specified URL or window.location.href by default
function getURLParam(param, url) {
    if (!url) url = window.location.href;
    var regex = '[?&]' + param + '=([^&#]*)';
    var results = (new RegExp(regex)).exec(url);
    if(results) return results[1];
    return 0;
}


//binds lightboxLink <a>'s click events with startOverlay method
$(document).ready(function(){
    bindLightboxLinks(0);
});
function bindLightboxLinks(id){
    // make string for optional container id and add a click event
	$((id!=0 ? "#"+id+" " : "")+".lightboxLink").click(function() {
		if ($(this).attr("href"))
			lightboxLink = $(this).attr("href");
		else if ($(this).attr("rel"))
			lightboxLink = $(this).attr("rel");
		else
			return true;
		window.startOverlay(lightboxLink);
		return false;
	});
}


function startOverlay(lightboxLink) {
    //get the body scroll position and height
    var bodyScrollTop = $(window).scrollTop(); //only works if body has overflow
    var bodyScrollHeight = $(window).height();
    var bodyScrollWidth = $(window).width();
    var docHeight = $(document).height();
    
    //make sure there aint no nuttin overlayin'
	$(".lightboxClose, .lightboxContainer, .lightboxOverlay").remove();    

    //add the elements to the DOM
	$("body")
		.append('<div class="lightboxOverlay"><img src="http://www.smallab.org/layout/loading_black.gif" style="position:absolute; left:'+bodyScrollWidth/2+'px; top:'+(bodyScrollTop+bodyScrollHeight/2)+'px; margin-top:-16px; margin-left:-16px;" class="loading" alt="Loading..." /></div><div class="lightboxContainer"></div><div class="lightboxClose">×</div>');
		//.css({"overflow":"hidden"});

    //animate the semitransparent layer
    $(".lightboxOverlay")
    	.css({"top":"0px", "height":docHeight+"px"})
		.animate({"opacity":"0.6"}, 400, "linear");

    //verify if alternate url
    var url = (getURLParam("alturl", lightboxLink) ? getURLParam("alturl", lightboxLink)+lightboxLink : lightboxLink);
    
    //fill the lightbox container with html
    $.ajax({
       type: "GET",
       url: url,
       async: true,
       success: function(msg) {
            $(".lightboxContainer").html(msg);
       }
    });

    //position it correctly after downloading
    border = 12;
    if (getURLParam("border",lightboxLink))
    	border = getURLParam("border",lightboxLink);
    
    var mediaItemWidth = getURLParam("width", lightboxLink);
    var mediaItemHeight = getURLParam("height", lightboxLink);
    var containerMarginTop = (bodyScrollHeight/2-mediaItemHeight/2-border<25 ? 25 : (bodyScrollHeight/2 - mediaItemHeight/2 - border));
    var containerMarginLeft = -mediaItemWidth/2 - border;

	$(".lightboxContainer")
		.css({
		    "border":     border+"px solid #eee",
			"top":        bodyScrollTop + "px",
			"left":       "50%",				
			"width":      mediaItemWidth,
			"height":     mediaItemHeight,
			"margin-top": containerMarginTop + "px",
			"margin-left":containerMarginLeft + "px" //to position it in the middle
		})
		.animate({"opacity":"1"}, 400, "linear", function() {
            $(".lightboxClose")
                .css({
                    "top":        bodyScrollTop + "px",
                    "left":       "50%",				
                    "margin-top": containerMarginTop + "px",
                    "margin-left":containerMarginLeft + mediaItemWidth/1.0 + 15 + "px",
                    "opacity":    1
                });
		});

    //initiate the removeOverlay
    window.removeOverlay(lightboxLink);
}

function removeOverlay(lightboxLink) {
    //façon Android Gingerbread :)
	$(".lightboxClose, .lightboxOverlay"+(getURLParam("link", lightboxLink)==0 ? ", .lightboxContainer" : "")).click(function(){ //, .lightboxContainer
		$(".lightboxOverlay .loading").remove();
		$(".lightboxClose").css({'opacity':0});
		$(".lightboxOverlay").animate({'opacity':.95}, 250, 'linear');
		var newTop = $(window).scrollTop() + getURLParam("height", lightboxLink)/2;
		$(".lightboxContainer").css({'min-height':0}).animate({'top':newTop+'px', 'height':0}, 250, 'linear', function() {
			$(this)
				.html("")
				.css({'left':'0', 'margin-left':'25px', 'width':$(window).width()-50+'px', 'height':0, 'border':'solid 1px #fff'})
				.animate({'opacity':0.2, 'width':'20%', 'left':'40%'}, 350, 'linear', function() {
					$(".lightboxClose, .lightboxContainer, .lightboxOverlay").fadeOut(100, function() {
						$(this).remove();
					});
				});
		});
	});
}

