
//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 ligthboxLink <a>'s click events with startOverlay method
$(document).ready(function(){
    bindDeployboxLinks(0);
});
function bindDeployboxLinks(id) {
    // make string for optional container id
    var contid = "";
    if (id!=0)
        contid = "#"+id+" ";
    // add a click event
	$(contid+".deployboxLink").click(function() {
		deployboxLink = $(this).attr("href");
		window.startDeployment(deployboxLink);
		return false;
	});
}



function startDeployment(deployboxLink) {
    //retrieve the target and former content
    var date = new Date();
    var stamp = date.getTime(); //timestamp in millisecs
    var targetid = getURLParam("targetid", deployboxLink);
    var remember = (getURLParam("remember", deployboxLink)=="true" ? $("#"+targetid).html() : "");
    
    //add the elements to the DOM
    $("#"+targetid)
           .html('<div class="deployboxContainer" id="deployboxContainer_'+stamp+'"><div class="deployboxClose" id="deployboxClose_'+stamp+'"></div></div>');
    
    //verify if alternate url
    var url = (getURLParam("alturl", deployboxLink) ? getURLParam("alturl", deployboxLink)+deployboxLink : deployboxLink);
    
    //fill the deploybox container with html
    $.ajax({
       type: "GET",
       url: url,
       async: true,
       success: function(msg) {
            $("#deployboxContainer_"+stamp).append(msg); // append pour ne pas ecraser la div de close
       }
    });

    //show it correctly after downloading
    $("#deployboxContainer_"+stamp)
        .animate({"opacity":"1"}, 400, "linear", function() {
            /*$(".deployboxContainer_"+stamp+" div").focus();*/ //focus() dessine une dotted border peu heureuse dans FF...
            $("#deployboxClose_"+stamp)
                .css({
                    "opacity":    1
                });
        });

    //initiate the removeDeployment
    window.removeDeployment(stamp, targetid, remember);
}

function removeDeployment(stamp, targetid, remember) {
    // allow users to be able to close the deploybox
	$("#deployboxClose_"+stamp).click(function() {
		$("#deployboxContainer_"+stamp).animate({"opacity":"0"}, 200, "linear", function() {
			$("#deployboxContainer_"+stamp).remove();
            $("#"+targetid).html(remember);
            bindDeployboxLinks(targetid); //to rebind anything that would have been erased by the deployment
            bindLightboxLinks(targetid);
		});
	});
}
