var popupStatus = 0;

function loadPopup(){ 
  if(popupStatus==0){ 
    $("#backgroundPopup").css({ 
      "opacity": "0.7" 
    }); 
    $("#backgroundPopup").fadeIn("slow"); 
    $("#popupContact").show("slow"); 
    popupStatus = 1; 
  } 
}

function disablePopup(){ 
  if(popupStatus==1){ 
    $("#backgroundPopup").fadeOut("slow"); 
    $("#popupContact").fadeOut("slow"); 
    popupStatus = 0; 
  } 
}

function centerPopup(pict, width, height, id){ 
  
  height = Math.min(height*(800/width), height); 
  width = Math.min(800, width)

  //var windowTop = self.screenY || self.screenTop;
  //var windowTop = 0;

  var windowScrollTop = (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop) || 0;
//  var windowScrollTop = self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);

//  var windowWidth = $(window).width(); 
  var windowWidth = window.innerWidth || (document.documentElement && document.documentElement.clientWidth) || document.body.clientWidth; 
//  var windowWidth = document.documentElement.clientWidth; 

//  var windowHeight = $(window).height(); 
  var windowHeight = document.body.clientHeight; 

  var popupHeight = Math.max(0, windowHeight/2-height/2); // + $("#"+id).offsetTop/2; 
  //var popupHeight = $("#"+id).offsetTop; 

  var popupWidth = Math.max(0, windowWidth/2-width/2); 
 
  $("#popupContact").css({ 
    //"background": "url(" + pict + ")",
    //"position": "absolute", 
    "top": popupHeight+"px", 
    "left": popupWidth+"px",
    "width": width+"px",
    "height": height+"px"
  }); 
  $("#pic").attr('src', pict); 
  $("#pic").attr('width', width); 

  $("#backgroundPopup").css({ 
    //"top": windowScrollTop+"px", 
    "height": windowHeight+"px", 
    "width": windowWidth+"px" 
  }); 
  loadPopup();
}

$(document).ready(function(){
  $("#button").click(function(){
    centerPopup();
    //loadPopup();
  });
               
  $("#popupContact").click(function(){
    disablePopup();
  });
  $("#backgroundPopup").click(function(){
    disablePopup();
  });
  $(document).keypress(function(e){
    if(e.keyCode==27 && popupStatus==1) {
      disablePopup();
    }
  });
});

