var popupStatus = 0;

function getScrollXY() {
	  var scrOfX = 0, scrOfY = 0;
	  if( typeof( window.pageYOffset ) == 'number' ) {

		scrOfY = window.pageYOffset;
	    scrOfX = window.pageXOffset;
	  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {

	    scrOfY = document.body.scrollTop;
	    scrOfX = document.body.scrollLeft;
	  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {

	    scrOfY = document.documentElement.scrollTop;
	    scrOfX = document.documentElement.scrollLeft;
	  }
	  return [ scrOfX, scrOfY ];
}

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

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

function centerPopup(id){
	try {
		var src = $("#id_image_"+id).attr("src");
		src = src.replace("thumb3", "thumb5");
	} catch (e) {
		src="";
	}
	
	$("#id_p_title").html($("#id_title_"+id).html());
	$("#id_p_price").html($("#id_price_"+id).html());
	$("#id_p_body").html($("#id_h_"+id).html());
	$("#id_p_image").attr({"src":src});

	if($("#period_prices_" + id).length >0){
		$("#id_period_prices").html($("#period_prices_" + id).html());
	}
	
	var scroll = getScrollXY();
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $("#popupContact").height();
	var popupWidth = $("#popupContact").width();

	$("#popupContact").css({
		"position": "absolute",
		"top": windowHeight/2-popupHeight/2 + scroll[1],
		"left": windowWidth/2-popupWidth/2 + scroll[0]
	});
	
	$("#backgroundPopup").css({
		"position": "absolute",
		"height": windowHeight
	});
}


$(document).ready(function(){
	$(".car-request").click(function(){
		var id = this.id;
		id = id.split("_");
		id = id[1];
		centerPopup(id);
		loadPopup();
		
	});
	
	$("#popupContactClose").click(function(){
		disablePopup();
	});

	$(".popupListClose").click(function(){
		disablePopup();
	});
	
	$("#backgroundPopup").click(function(){
		disablePopup();
	});

	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			disablePopup();
		}
	});

});
