/*

lightbox functions
needs:
    jQuery (duh)
    getPageSize() from common.js
    getPageScroll() from common.js
    stripesAjaxAction(...) from stripes.ajax.js
    contextPath variable from html head

*/


var messageType = { info: 'blu', error: 'red', confirm: 'green' };

function getPositionForMessage()
{
    getPageSize();
    getPageScroll();
    var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - 156) / 2);
    if (lightboxTop < arrayPageScroll[1])
    {
        lightboxTop = arrayPageScroll[1];
    }
    return lightboxTop;
};

function resetMessageBox()
{
    //reset messages
    $("#feedbackMsg").html("<!-- -->");
    
    //configure box position
    $("#feedbackBody").css(
        { top : getPositionForMessage() + 'px' }
    );
    //hide
    $("#feedbackLB, #feedbackLB_bg, #feedbackMsg, #feedbackMsg .alert, #feedbackBody").hide();
};

/**
 * add message to the message box
 * @param text the message text, without surrounding span element
 * @param type the message type as defined by messageType
 * @param field the field to which the error message refers 
 * @return undefined
 */
function addMessageToBox(text, type, field)
{
    $("#feedbackMsg").append("<p class='alert " + (type || messageType.info) + "'><span>" + text + "</span></p>");
};

/**
 * @param urlOrFunction url or function to be called when clicking on the OK button
 * @param cancelButton true if the dialog needs a cancel button
 * @return undefined
 */
function configureMessageBoxButtons(urlOrFunction, cancelButton)
{
    var url;
    if(urlOrFunction && typeof urlOrFunction !== 'function') url = urlOrFunction;
    else url = 'javascript:void(0);';

    if($("#feedbackMsgbuttons").length === 0)
        $("#feedbackMsg").append('<p class="buttons" id="feedbackMsgbuttons"><!--  --></p>');
    
    if(cancelButton) 
        $("#feedbackMsgbuttons").html(
            '<a href="' + url + '" class="sdButtS sdButtSGrey" title="OK" id="feedbackLBConfirm" style="float:left"><span>OK</span></a>' + 
            '<a href="javascript:void(0);" class="sdButtS sdButtSGrey" title="Annulla" id="feedbackLBClose" style="float:right"><span>Annulla</span></a>'
        );
    else
        $("#feedbackMsgbuttons").html(
            '<a href="' + url + '" class="sdButtS sdButtSGrey" title="OK" id="feedbackLBClose"><span>OK</span></a>');

    if(urlOrFunction && typeof urlOrFunction === 'function')
        $(cancelButton ? "#feedbackLBConfirm" : "#feedbackLBClose").click(urlOrFunction);

    //configure close event
    $("#feedbackLBClose").click( function(event) {
        $("#feedbackLB, #feedbackLB_bg").hide();
    });
    
};

function showMessageBox()
{
    $("#feedbackLB_bg").css("height", $("html").height());
    $("#feedbackLB_bg").fadeTo("fast", 0.80);
    $("#feedbackLB, #feedbackLB_bg, #feedbackMsg, #feedbackMsg .alert, #feedbackBody").show();
}

niceMessage = promptMessageBox = function(message, iserror, urlOrFunction, canBeCanceled)
{
    resetMessageBox();
    addMessageToBox(message, iserror ? messageType.error : messageType.info);
    configureMessageBoxButtons(urlOrFunction, canBeCanceled);
    showMessageBox();
};

/*

ajaxBoxAction, optionally display a prompt lightbox, then call a stripes action via ajax and display the results
into another lightbox. If no stripes messages and/or validation errors need to be displayed, success and/or failure are
called directly. Note that the contextPath is appended to the action automatically

parameters:
    
    type:
        string - type of the event to bind (e.g. 'click')
    action: 
        string - the stripes action url (including context path)
    params: 
        map - parameters that will be passed to the stripes action
    options:
        map or function - optional, if it's a function or a string will be used as the onSuccess subparameter
        {
        prompt:
            map - optional, display a box prompting the user for a confirmation
            {
                text:
                    string - the text that will be displayed
                isWarning:
                    boolean - whether the prompt should be styled as a warning or as a normal information message
            }
        beforeSubmit: 
            function - executed before sending the ajax request, can abort the request by returning false
        success:
            function(response) or string - function to execute or url to redirect to when the user clicks ok on the 
            message box displaying the action outcome after execution was successful. If a function, will receive the
            stripes response data (data.response) as input
        failure:
            function or string - function to execute or url to redirect to when the user clicks ok on the message box
            displaying the action outcome after execution failed
        }

example usage 1:

    $('a.boxAction').ajaxBoxAction(
        'click',
        '/actions/test.action',
        {test: 'test'},
        { 
            prompt: { text: 'warning: deleting file', isWarning: true },
            success: function()  { alert('success'); }, //or 'http://www.google.com',
            failure: function() { alert('failure') } //or 'http://www.youfail.org'
        } 
    );

example usage 2:

    $('a#doAjax').bind('click', function() {
        return $.ajaxBoxAction(
            '/actions/test.action',
            {test: 'test'},
            'http://www.google.com'
        );
    })

 */

;(function($) { 

$.fn.ajaxBoxAction = function(type, action, params, options)
{
	var that = this;
    $(that).bind(type, function() {
        return $.ajaxBoxAction(action, params, options, that);
    });
};

$.ajaxBoxAction = function(action, params, options, that)
{
    if (typeof options === 'function' || typeof options === 'string')
    {
        options = { success: options };
    } else {
    	options = options || {};
    }
    
    var boxOptions = {
        beforeSubmit: options.beforeSubmit,
        afterResponse: resetMessageBox, 
        message: function(text) { addMessageToBox.apply(that, [text, messageType.confirm] ); },
        validationError: function(text, field) { addMessageToBox.apply(that, [text, messageType.error, field] ); },
        complete: function(data, numProcessed) {
            var complete;
            if(!data || data.errors)
                complete = options.failure && function() { options.failure.apply(that); } ;
            else if(typeof options.success === 'function')
                complete = function() { options.success.apply(that, [data.response]); };
            else
                complete = options.success;
            
            if(numProcessed)
            {
                configureMessageBoxButtons(complete);
                showMessageBox();
            }
            else
            {
                if(typeof complete === 'function')
                    complete();
                else if(typeof complete === 'string')
                    document.location.href = complete;
            }
        }
    };
    var ajaxAction = function() { $.stripesAjaxAction(contextPath + action, params, boxOptions, that); };
    
    if(options.prompt) 
    {
        promptMessageBox(options.prompt.text, options.prompt.isWarning, ajaxAction, true);
    } 
    else 
    {
        ajaxAction();
    }
    return false;
};

})(jQuery);
