// ******** [+] When page loaded ********
$(document).ready(function(){
    popupLinks();
}); 
// ******** [-] When page loaded ********

// ******** [+] Popups and external links ********
// Usage:
//   <a rel="popup">      = pop up window (default size)
//   <a rel="popup 800">  = popup up window (800 x 600)
//   <a rel="popup 640">  = popup up window (640 x 480)
//   <a rel="popup external">      = external link (new tab / page)
function popupLinks(){
     $("a[rel~='popup']").click(function(event){
        event.preventDefault();
        var url = $(this).attr("href");
        var name = $(this).text().replace(/[^a-zA-Z0-9]/g,"");
        if($(this).find("img").attr("alt")){
             name += $(this).find("img").attr("alt").replace(/[^a-zA-Z0-9]/g,"");
        }
        // Default attributes 
        var width = 1024;
        var height = 768;
        var resize = "yes";        
        var toolb = "no";
        var loc = "no";
        var scroll = "yes";
        var status = "no";
        var menubar = "no";
        var dirs = "no";
        // Custom attributes 
        if ($(this).attr("rel").indexOf(" 800")!=-1){
            width = 800;
            height = 600;
        }
        else if($(this).attr("rel").indexOf(" 640")!=-1){
            width = 640;
            height = 480;
        }
        // Calculated attributes
        var top = Math.floor((screen.availHeight - height)/2);
        var left = Math.floor((screen.availWidth - width)/2);
        if($(this).attr("rel").indexOf("top")!=-1){
            top = 0;
        }
        else if($(this).attr("rel").indexOf("bottom")!=-1){
            top = screen.availHeight - height;
        }
        else{
            top = Math.floor((screen.availHeight - height)/2);
        }

        if($(this).attr("rel").indexOf("left")!=-1){
            left = 0;
        }
        else if($(this).attr("rel").indexOf("right")!=-1){
            left = screen.availWidth - width;
        }
        else{
            left = Math.floor((screen.availWidth - width)/2);
        }
            
        // Tools for popupups only, don't control how external links look 
        var tools = "resizable=" + resize +",toolbar="+ toolb +",location="+ loc +",scrollbars="+ scroll +",status="+ status +",menubar="+ menubar +",directories="+ dirs +",width="+ width +",height="+ height +",top="+ top +",left="+ left;
        newWin = (($(this).attr("rel").indexOf("external")==-1) ? window.open(url,name,tools) : window.open(url,name));
        newWin.focus();
     });
}
// ******** [-] Popups and external links ********