
var PopupLayer = {
   
    popupId : null,
    onReadyHandler : null,
    
    getSuccessCallback : function() {
        return function(response) {
            var $popupViewLayer = $('#'+popupId);
            var $popupViewContent = $popupViewLayer.find(".popup_content");
            $popupViewContent.html(response.stateContent);
            epoint.ow.DocumentReadyManager.runAllActions();
            $popupViewContent.find('form').unbind('submit');
            PopupLayer.unlockDiv(popupId);
            if (typeof PopupLayer.onReadyHandler == "function") {
                PopupLayer.onReadyHandler.call(this);
            }
        }
    },

    open : function(id, link, onReadyHandler) {
        popupId = id;
        this.onReadyHandler = onReadyHandler;
        $.ajax({
            type: "GET",
            url: link,
            dataType: "json",
            success: function(response) {
                PopupLayer.getSuccessCallback().call(this, response);
                fn.popup(popupId);
            }
        });
    },

    makeAction : function(link) {
    	
    	PopupLayer.lockDiv(popupId);
    	
        $.ajax({
            type: "GET",
            url: link,
            dataType: "json",
            success: this.getSuccessCallback()
        });
    },

    submitForm : function(formName, link) {
        var form = epoint.ow.Utils.getForm(formName);
        var params = $(form).serializeArray();
        
        PopupLayer.lockDiv(popupId);
        
        params.push({"name" : "formName", "value" : formName});
        $.ajax({
            type: "POST",
            url: link,
            dataType: "json",
            data: params, 
            success: this.getSuccessCallback()
        });
    },

    close : function () {
        fn.hidePopups();
    },
    
	lockDiv : function(divId) {
		var o = $("#" + divId).find(".popup_content");
		$("<div>").addClass('box_cover').attr('id', PopupLayer.getLockDivId(divId)).css({
			left: o.position().left,
			top: o.position().top,
			width: o.width(),
			height: o.height(),
			"opacity": 0.5,
			"z-index": o.css('z-index') + 1
		}).insertBefore(o);
	},
	
	unlockDiv : function(divId) {
		$("#" + PopupLayer.getLockDivId(divId)).remove();
	},
	
	getLockDivId : function(divId) {
		return divId + "_cover";
	}
};

