
//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() {
		lightboxLink = $(this).attr("href");
		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 docScrollHeight = $(document).height();

    //add the elements to the DOM
	$("body")
		.append('<div class="lightboxOverlay"></div><div class="lightboxContainer"></div>');

    //animate the semitransparent layer
    //$(".lightboxOverlay").css({"top":bodyScrollTop+"px"});
    $(".lightboxOverlay").css({"top":"0px", "height":docScrollHeight+"px"});
	$(".lightboxOverlay").animate({"opacity":"0.8"}, 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
		    var mediaItemWidth = getURLParam("width", lightboxLink);
		    $(".lightboxContainer")
		        .css({
		            "top":         bodyScrollTop+75+"px",
		            "left":        "50%",
		            "height":	   bodyScrollHeight-75+"px",
		            "margin-left": -mediaItemWidth/2 + "px" //to position it in the middle
		        })
		        .animate({"opacity":"1"}, 400, "linear", function() {});
		    $("#lightboxOverflow")
		        .css({
		            "height":	   bodyScrollHeight-107+"px"
		        });
       }
    });

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

function removeOverlay() {
    // allow users to be able to close the lightbox
	$(".lightboxOverlay").click(function(){
		$(".lightboxContainer, .lightboxOverlay").animate({"opacity":"0"}, 200, "linear", function(){
			$(".lightboxContainer, .lightboxOverlay").remove();	
		});
	});
}

function removeOverlayNow() {
	$(".lightboxContainer, .lightboxOverlay").animate({"opacity":"0"}, 200, "linear", function(){
		$(".lightboxContainer, .lightboxOverlay").remove();	
	});
}

