/* ajax loading effects */
var editMode = false;   // todo: consider switch for the future
var activeButton; // todo: consider remembering active button for the future
var loadBarImg = document.createElement('img');
loadBarImg.setAttribute("src", contextPath + '/images/ajax-loader.gif');
loadBarImg.setAttribute("border", "0");
loadBarImg.setAttribute("align", "top");
loadBarImg.setAttribute("vspace", "0");
loadBarImg.setAttribute("hspace", "4");
Element.extend(loadBarImg);


/**
 * display loading bar image next to button
 * @param element
 */
function displayLoadingLeftToButton(element)
{
    loadBarImg.setAttribute("vspace", ($(element).getHeight() - 16) / 2);
    $(element).ancestors()[0].insertBefore(loadBarImg, $(element));
}

/**
 * hide loading bar image on at the end of loading
 * @param element
 */
function hideLoadingLeftToButton(element)
{
    $(element).ancestors()[0].removeChild(loadBarImg);
    loadBarImg.setAttribute("vspace", "0");
}


/**
 * display loading bar image next to button
 * @param element
 */
function displayLoadingInsteadOfButton(element)
{
    loadBarImg.setAttribute("hspace", ($(element).getWidth() - 16) / 2);
    loadBarImg.setAttribute("vspace", ($(element).getHeight() - 16) / 2);
    $(element).ancestors()[0].insertBefore(loadBarImg, $(element));
    $(element).hide();
}

/**
 * hide loading bar image on at the end of loading
 * @param element
 */
function hideLoadingInsteadOfButton(element)
{
    $(element).show();
    $(element).ancestors()[0].removeChild(loadBarImg);
    loadBarImg.setAttribute("hspace", "4");
    loadBarImg.setAttribute("vspace", "0");
}


// todo : instead of number of fixed parameters receive an array of params
/**
 * Loads form in popup
 * @param targetDiv
 * @param button
 * @param url
 */
function loadDynaForm(targetDiv, button, url)
{
    if (button)
    {
        activeButton = button;
        displayLoadingLeftToButton(button);
    }
    //success:'products', failure:'errors'
    new Ajax.Updater(targetDiv, url, {
        parameters : { refresh : new Date().getTime() + '' },
        method: 'get',
        onComplete :function()
        {
            if (button)
            {
                hideLoadingLeftToButton(button);
            }
            showModalDialog(targetDiv);
        },
        onSuccess : function(transport, json)
        {
            // do nothing
        },
        onFailure : function(transport)
        {
        }
    });
}

function onSuccessAction()
{

}

// todo : give the property to choose loading bar display strategy
function loadDynaFormInline(targetDiv, button, url, successAction, failureAction, submitMethod)
{
    if (button)
    {
        activeButton = button;
        displayLoadingInsteadOfButton(button);
    }
    $(targetDiv).innerHTML = "";
    //success:'products', failure:'errors'
    new Ajax.Updater(targetDiv, url, {
        parameters : {  refresh : new Date().getTime() + '' },
        method: (submitMethod == null ? 'get' : submitMethod),
        evalScripts: true,
        onComplete :function()
        {
            if (button)
            {
                hideLoadingInsteadOfButton(button);
            }
            if (successAction)
            {
                eval(successAction);
            }
        },
        onSuccess : function(transport, json)
        {
            onSuccessAction();
            // do nothing
        },
        onFailure : function(transport)
        {
            if (failureAction)
            {
                eval(failureAction);
            }
        }
    });
}


function locateInCenter(id)
{
    var element = $(id);
    var divHeight = element.getHeight();
    var divWidth = element.getWidth();
    var scrollOffset = getScrollOffset();
    var pageWidth = $(document.body).getWidth();
    var visibleHeight = getVisibleHeight();
    var leftX = (pageWidth - divWidth) / 2;
    var topY = scrollOffset + (visibleHeight - divHeight) / 2;
    element.style.top = topY + "px";
    element.style.left = leftX + "px";
}

function showModalDialog(targetDiv, quickAppearance)
{
    //$(targetDiv).show();
    hideSelectBoxes();
    locateInCenter(targetDiv);
    Event.observe(window, "scroll", function()
    {
        locateInCenter(targetDiv);
    });
    editMode = true;
    /*if(activeButton) {
     activeButton.disabled = true;
     activeButton.style.color = 'darkgray';
     }*/
    $('overlay').style.height = /*$(document.body).getHeight()*/ getPageHeight() + "px";
    $('overlay').style.display = 'inline';
    if (!quickAppearance)
    {
        effectSlowAppearance(targetDiv, 50, 20);
    } else
    {
        $(targetDiv).show();
    }
}

function getVisibleHeight()
{
    if (window.innerWidth) //if browser supports window.innerWidth
        return window.innerHeight;
    else if (document.all)
    {//else if browser supports document.all (IE 4+)
        if (document.documentElement)
            return document.documentElement.offsetHeight;
        else
            return document.body.clientHeight;
    }
    else
        return window.innerHeight;
}

function getScrollOffset()
{
    var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
    return document.all ? iebody.scrollTop : pageYOffset
}

function getPageHeight()
{
    var bottomElementHeight = Position.cumulativeOffset($('bottomElement'))[1];
    var visibleHeight = getVisibleHeight();
    if (visibleHeight > bottomElementHeight)
        return visibleHeight;
    return bottomElementHeight;
}

function cancelDynaFormEdit(targetDiv)
{
    $(targetDiv).empty();
    $(targetDiv).hide();
    editMode = false;
    if (activeButton)
    {
        activeButton.disabled = false;
        activeButton.style.color = '';
    }
    document.getElementById('overlay').style.display = 'none';
    // clear form inputs
}

function closeModalDialog(targetDiv)
{
    restoreSelectBoxes();
    $(targetDiv).hide();
    $('overlay').style.display = 'none';
}


function submitDynaForm(targetDiv, formId, button, successAction, failureAction)
{
    if (button)
        displayLoadingLeftToButton(button);
    new Ajax.Updater(targetDiv, $(formId).action, {
        parameters : $(formId).serialize(),
        method: 'post',
        onComplete :function(transport)
        {
            if (button)
                hideLoadingLeftToButton(button);
        },
        onSuccess : function(transport, json)
        {
            if (json.status == -1)
            {
                //displayErrorMessages(formId,json);
            } else
            {
                cancelDynaFormEdit(targetDiv);
                // perform action on success
            }
        },
        onFailure : function(transport)
        {
            alert('Failure! todo: process failure in more user friendly way');
        }
    });
}

function submitDynaFormInline(targetDiv, formId, button, successAction, failureAction)
{
    displayLoadingLeftToButton(button);
    new Ajax.Updater(targetDiv, $(formId).action, {
        parameters : $(formId).serialize(),
        method: 'post',
        onComplete :function(transport)
        {
            hideLoadingLeftToButton(button);
        },
        onSuccess : function(transport, json)
        {
            if (json.status == -1)
            {
                if (failureAction)
                    eval(failureAction);
            } else
            {
                // perform action on success
                if (successAction)
                {
                    eval(successAction);
                }
            }
        },
        onFailure : function(transport)
        {
            alert('Failure!');
        }
    });
}

function submitDynaRequest(formId, button, successAction, failureAction)
{
    if (button != null)
    {
        displayLoadingInsteadOfButton(button);
    }
    new Ajax.Request($(formId).action, {
        parameters : $(formId).serialize() + "&ignore_enc_filter=true",
        method: 'post',
        onComplete :function(transport)
        {
            if (button != null)
            {
                hideLoadingInsteadOfButton(button);
            }
        },
        onSuccess : function(transport, json)
        {
            if (json != null && json.status == -1)
            {
                if (failureAction)
                    eval(failureAction);
            } else
            {
                if (successAction)
                    eval(successAction);
            }
        },
        onFailure : function(transport)
        {
            alert('Failure! todo: process failure in more user friendly way');
        }
    });
}

/**
 * Submit dynamic background ajax request for given url
 * @param url
 * @param objectType
 * @param id
 * @param button
 */
function submitDynaRequestUrl(url, successAction, failureAction, button, insteadOfButton)
{
    if (button != null)
    {
        if (insteadOfButton)
        {
            displayLoadingInsteadOfButton(button);
        } else
        {
            displayLoadingLeftToButton(button);
        }
    }
    new Ajax.Request(url, {
        parameters : "",
        method: 'post',
        onComplete :function(transport)
        {
            if (button != null)
            {
                if (insteadOfButton)
                {
                    hideLoadingInsteadOfButton(button);
                } else
                {
                    hideLoadingLeftToButton(button);
                }
            }
            //eval(successAction);
        },
        onSuccess : function(transport, json)
        {
            if (json.status == -1)
            {
                if (failureAction)
                    eval(failureAction);
            } else
            {
                // perform action on success
                if (successAction)
                {
                    eval(successAction);
                }
            }
        },
        onFailure : function(transport)
        {
            alert('Failure! todo: process failure in more user friendly way');
        }
    });
}

/**
 * hide all selectboxes on page
 */
function hideSelectBoxes()
{
    var selectBoxes = document.getElementsByTagName("select");
    for (var i = 0; i < selectBoxes.length; i++)
    {
        if ($(selectBoxes[i]).visible())
            $(selectBoxes[i]).hide();
    }
}

/**
 * show all selectboxes on page
 */
function restoreSelectBoxes()
{
    var selectBoxes = document.getElementsByTagName("select");
    for (var i = 0; i < selectBoxes.length; i++)
    {
        if (!$(selectBoxes[i]).visible())
            $(selectBoxes[i]).show();
    }
}

/* custom confirm dialog */

var confirmDialogEvent = null;

function confirmDialog(message, codeToRun)
{
    Event.stopObserving('okConfirmButt', 'click', confirmDialogEvent);
    showModalDialog("modal-window-confirm");
    $('modal-window-confirm-text').innerHTML = "";
    new Insertion.Top($('modal-window-confirm-text'), message);
    confirmDialogEvent = function()
    {
        closeModalDialog('modal-window-confirm');
        eval(codeToRun);
    }
    Event.observe('okConfirmButt', 'click', confirmDialogEvent);
}

function loadingWindow()
{
    showModalDialog("modal-window-loading", true);
}

function cancelLoadingWindow()
{
    closeModalDialog('modal-window-loading');
}

/* VISUAL EFFECTS */

var esaInterval = null;
var esaCounter = 0;
var esaElementId = null;

function effectSlowAppearance(elementId, delay, step)
{
    esaCounter = 0;
    esaElementId = elementId;
    /* initial values */
    $(elementId).style['-moz-opacity'] = "0";
    $(elementId).style['opacity'] = "0";
    $(elementId).style['filter'] = "alpha( opacity = 0 )";
    esaInterval = setInterval(function()
    {
        esaCounter += step;
        $(elementId).style['-moz-opacity'] = "" + (esaCounter / 100);
        $(elementId).style['opacity'] = "" + esaCounter / 100;
        $(elementId).style['filter'] = "alpha( opacity = " + esaCounter + ")";
        if (esaCounter == step)
        {
            $(elementId).show();
        }
        if (esaCounter >= 100)
        {
            clearInterval(esaInterval);
        }
    }, delay);
}

var esdInterval = null;
var esdCounter = 0;
var esdElementId = null;

function effectSlowDisappearance(elementId, delay, step)
{
    esdCounter = 100;
    esdElementId = elementId;
    /* initial values */
    $(elementId).style['-moz-opacity'] = "1.0";
    $(elementId).style['opacity'] = "1.0";
    $(elementId).style['filter'] = "alpha( opacity = 100 )";
    esdInterval = setInterval(function()
    {
        esdCounter -= step;
        if (esdCounter <= 0)
        {
            clearInterval(esdInterval);
            $(elementId).style.visibility = 'hidden';
            esdCounter = 0;
        }
        $(elementId).style['-moz-opacity'] = "" + (esdCounter / 100);
        $(elementId).style['opacity'] = "" + esdCounter / 100;
        $(elementId).style['filter'] = "alpha( opacity = " + esdCounter + ")";
    }, delay);
}

var euInterval = null;
var euCounter = 0;
var euElementId = null;

/* element should be hidden  elementId usually = div id */
function effectUnrolling(elementId, step, delay)
{
    var elementHeight = $(elementId).getHeight();
    var totalTime = elementHeight / step * delay;
    euCounter = 0;
    $(elementId).style.overflow = "hidden";
    $(elementId).style.height = '1px';
    $(elementId).style.visibility = 'visible';
    euInterval = setInterval(function()
    {
        euCounter += step;
        $(elementId).style.height = "" + euCounter + "px";
        if (euCounter >= elementHeight / 2)
        {
            clearInterval(euInterval);
            euInterval = setInterval(function()
            {
                euCounter += step * 4;
                $(elementId).style.height = "" + euCounter + "px";
                if (euCounter >= 3 * elementHeight / 4)
                {
                    clearInterval(euInterval);
                    euInterval = setInterval(function()
                    {
                        euCounter += step * 4;
                        $(elementId).style.height = "" + euCounter + "px";
                        if (euCounter >= elementHeight)
                        {
                            clearInterval(euInterval);
                            euInterval = null;
                        }
                    }, delay / 16);
                }
            }, delay / 8);
        }
    }, delay);
    return totalTime;
}


var eriInterval = null;
var eriCounter = 0;
var eriElementId = null;

function effectRollingIn(elementId, step, delay)
{
    var elementHeight = $(elementId).getHeight();
    var totalTime = elementHeight / step * delay;
    eriCounter = elementHeight;
    $(elementId).style.overflow = "hidden";
    $(elementId).style.visibility = "visible";
    eriInterval = setInterval(function()
    {
        eriCounter -= step;
        $(elementId).style.height = "" + eriCounter + "px";
        if (eriCounter <= elementHeight / 2)
        {
            clearInterval(eriInterval);
            eriInterval = setInterval(function()
            {
                eriCounter -= step * 4;
                $(elementId).style.height = "" + eriCounter + "px";
                if (eriCounter <= 3 * elementHeight / 4)
                {
                    clearInterval(eriInterval);
                    eriInterval = setInterval(function()
                    {
                        eriCounter -= step * 4;
                        if (eriCounter <= 0)
                        {
                            $(elementId).style.height = "1px";
                            clearInterval(eriInterval);
                            eriInterval = null;
                            $(elementId).style.visibility = 'hidden';
                            $(elementId).style.position = 'absolute'
                        } else
                        {
                            $(elementId).style.height = "" + eriCounter + "px";
                        }
                    }, delay / 16);
                }
            }, delay / 8);
        }
    }, delay);
    return totalTime;
}


function checkUserSession(userId, pe)
{
    new Ajax.Request('session_indicator.do', {
        parameters : "",
        method: 'post',
        onComplete :function(transport)
        {
        },
        onSuccess : function(transport, json)
        {
            if (json.status == -1 ||
                (json.status == 0 && json.attributes['loggedinUserId'] != userId))
            {
                pe.stop();
                showSessionExpiredScreen();
            } else
            {
                // ...
            }
        },
        onFailure : function(transport)
        {
            // keep silence
        }
    });
}

function showSessionExpiredScreen()
{
    showModalDialog('modal-window-expired', true)
}