//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatus = 0;
var popupActiveId = null;

//loading popup with jQuery magic!
function loadPopup(popupID){
	//loads popup only if it is disabled
	if(popupStatus==0){
		$("#backgroundPopup").css({
			"opacity": "0.7"
		});
		$("#backgroundPopup").fadeIn("fast");
		$("#" + popupID).fadeIn("fast");
		popupStatus = 1;
		popupActiveId = popupID;
	}
}

//disabling popup with jQuery magic!
function disablePopup(){
	//disables popup only if it is enabled
	if(popupStatus==1){
		$("#backgroundPopup").fadeOut("fast");
		$("#" + popupActiveId).fadeOut("fast");
		popupStatus = 0;
		popupActiveId = null;
	}
}


//centering popup
function centerPopup(popupID){
	//request data for centering
	var scroll_top = document.documentElement.scrollTop || document.body.scrollTop;
    var scroll_height = document.documentElement.scrollHeight;
    var client_height = window.innerHeight || document.documentElement.clientHeight;
	
	var windowWidth = document.documentElement.clientWidth;
	
	var popupHeight = $("#" + popupID).height();
	var popupWidth = $("#" + popupID).width();
	//centering
	$("#" + popupID).css({
		"position": "absolute",
		"top": scroll_top + client_height/2-popupHeight/2,				
		"left": windowWidth/2-popupWidth/2
	});
	//only need force for IE6
	$("#backgroundPopup").css({
		"height": scroll_height
	});
	
}

function onSubmitPopupForm(form, saveAction) {
	var query_string_obj = {};
	
	$("input,textarea,select", form).each( function() {
			var id = $(this).attr("id");			
			query_string_obj[id] = $(this).val();
	});	
	query_string_obj["ajax"] = 1;
	query_string_obj["doFAct"] = "save";
	
	ajaxStart(form);
	
	$("input[type='submit']", form).attr("disabled", true);
	
	$.post(saveAction, query_string_obj, 
		function(response) {
			$("input[type='submit']", form).removeAttr("disabled");
			ajaxStop();
			eval(response);
	});

}

function initCommentPopup() {
	//CLOSING POPUP
	//Click the x event!
	$(".popupCommentClose").click(function(){
		disablePopup();		
		return false;
	});
}

function loadCommentForm(containerID, link, id) {
	$.get('comment_js_render.php', {'link':link, 'id':id}, function(data){
		  $("#" + containerID).html(data);
		  initCommentPopup();
	});
}

$(document).ready(function(){
		
	$(".addcomm").click(function() {
		var aID = $(this).attr("artID");		
		if(aID) {
			$("#formComment #articleID").val(aID);
		}
		centerPopup("popupComment");	
		loadPopup("popupComment");		
		return false;
	});
	
	$(".addart").click(function(){		
		centerPopup("popupArticle");
		loadPopup("popupArticle");	
		return false;
	});
	
	initCommentPopup();
	
	//Click out event!
	$("#backgroundPopup").click(function(){
		disablePopup();
	});
	//Press Escape event!
	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			disablePopup();
		}
	});
	
	

});
