
var timer = null;

function submit(/*String*/ namespace, /*:String*/ url, /*Array|Json*/ pparams, /*:Array|String*/pupdateSelector, /*:Function(resultData,result)*/ completeCallback, /*:Array|HtmlElement*/pdataContainers) {
    if (pupdateSelector != null) {
        if (typeof(pupdateSelector) == 'array' ) {
            pupdateSelector = pupdateSelector.join(",");
        }
        if (pupdateSelector.length > 0) {
            //always updating the error_messages id from template.jsp - for showing the errors
            pupdateSelector += ",#error_messages";
        }
        pparams['jquery_selector'] = pupdateSelector;

    }
    if (pparams['page'] ==null) {
        pparams['page'] = (pparams['validate'])?0:-1;
    }

    clearTimeout(timer);

    enableWaitPanel(namespace);
    submitAJAX(
            url,
            pparams,
            onComplete(namespace, pupdateSelector, (completeCallback) ? completeCallback : null),
            (pdataContainers) ? pdataContainers : null,
            (pupdateSelector) ? pupdateSelector : null);

    namespace = null;
    url = null;
    pparams = null;
    pupdateSelector = null;
    completeCallback = null;
    pdataContainers = null;
}

function toggleErrors(pnamespace){
    jQuery('#'+pnamespace+'errors').slideToggle();
}

var
        WAITPANEL_WIDTH = 120,
        WAITPANEL_HEIGHT = 40,
        WAIT_PANEL_TOP = 20;

function isWaitPanelActive(pnamespace) {
    return jQuery('#'+pnamespace+'waitWrapper').length > 0;
}

function getWaitIconTop(pmainView) {
    var ret = WAIT_PANEL_TOP+jQuery(document).scrollTop()-pmainView.offset().top;
    pmainView = null;
    return (ret < WAIT_PANEL_TOP)?WAIT_PANEL_TOP:ret;
}

function enableWaitPanel(pnamespace) {
    if (isWaitPanelActive(pnamespace)) {
        return;
    }
    var
            mainView = jQuery('#'+pnamespace+'mainView'),
            container = jQuery('<div id='+pnamespace+'waitWrapper></div>'),
            filterDiv = jQuery("<div id='"+pnamespace+"waitPanel'></div>"),
            waitPanel = jQuery("<table id='"+pnamespace+"waitEl' cellspacing=0 cellpadding=0><tr><td id='"+pnamespace+"waitImgWrapper'></td><td>Loading ...</td></tr></table>"),
            waitImg = jQuery("<img src='/z_dasuRace/html/main/images/loading.gif' />");

    container.css({
        position:'absolute',
        width:mainView.width(),
        height:mainView.height(),
        zIndex:10000
    });
    filterDiv.css({
        position:'absolute',
        width:mainView.width(),
        height:mainView.height(),
        border:'1px solid blue',
        backgroundColor:'gray',
        opacity:0.1
    });
    waitImg.css({
        padding:'0 3px 0 10px'
    });
    waitPanel.css({
        opacity:1,
        left:(mainView.width()-WAITPANEL_WIDTH)/2+'px',
        top:getWaitIconTop(mainView)+'px',
        width:WAITPANEL_WIDTH+'px',
        height:WAITPANEL_HEIGHT+'px',
        position:'absolute',
        border:'3px solid #0033CC',
        backgroundColor:'white'
    });

     jQuery(window).bind('scroll', function () {
         var top = 20;
         var _mainView = jQuery('#'+pnamespace+'mainView');
         var _waitPanel = jQuery('#'+pnamespace+'waitEl');
         if (_waitPanel.length == 0) {
             jQuery(window).unbind('scroll');
             pnamespace = null;
             return;
         }

         var offset = getWaitIconTop(_mainView);
         if (offset <= _mainView.height()-top-WAITPANEL_HEIGHT) {
            _waitPanel.animate({top:offset+"px"},{duration:500,queue:false});
         }
         
         top = null;
         _mainView = null;
         _waitPanel = null;
     });

    container.append(filterDiv);
    waitPanel.find('#'+pnamespace+"waitImgWrapper").append(waitImg);
    container.append(waitPanel);
    mainView.before(container);

    mainView = null;
    container = null;
    filterDiv = null;
    waitPanel = null;
    waitImg = null;
}

function disableWaitPanel(pnamespace) {
    var
        waitWrapper = jQuery('#'+pnamespace+'waitWrapper');

    waitWrapper.remove();

    jQuery(window).unbind('scroll');

    waitWrapper = null;
    pnamespace = null;
}

function onComplete(namespace, selector, completeCallback) {

    return function(resultData, result) {
        defaultSubmitComplete(resultData, result);
        if (completeCallback) {
            if (typeof(completeCallback) === 'string') {
                eval(completeCallback+'()');
            } else {
                completeCallback(resultData, result);
            }
        }

        resultData = null;
        result = null;
    };

    function defaultSubmitComplete(resText, result) {
        if (result == 'error') {
            alert(resText);
        } else {
            var partialUpdate = false;
            //even if a selector was specified as input, we could still have a view change
            if (typeof(resText.partialUpdate) !== 'undefined') {
                if (resText.partialUpdate == true) {
                    partialUpdate = true;
                } else {
                    resText = resText.content;
                }
            }
            updateZones(resText, partialUpdate);
            updateErrorMessages(namespace);
            if (partialUpdate)
                callPageOnLoad();
            partialUpdate = null;
        }

        resText = null;
        result = null;
    }

    function callPageOnLoad() {
        eval(namespace+'onLoad()');
    }

    function updateErrorMessages(pnamespace) {
        timer = setTimeout("toggleErrors('"+pnamespace+"');",2000);
        pnamespace = null;
    }

    function fadeUpdate(/*:DOMElement*/ pclientEl) {
        if (pclientEl.length == 0) {
            return;
        }
        var parentEl = pclientEl;
        if (pclientEl[0].nodeName.toUpperCase() == "TR") {
            parentEl = pclientEl.children()[0];
        }
//        alert(pclientEl[0].screenLeft);
        var overlayEl = jQuery('<div />').css({
            backgroundColor:'#FFFFD4',
            position:'absolute',
            opacity:0.9,
            width:pclientEl[0].offsetWidth,
            height:pclientEl[0].offsetHeight,
            zIndex:1000
        }).prependTo(parentEl);
        overlayEl.animate({opacity: "hide"}, 700,'linear',function() {
            overlayEl.remove();
        });

        parentEl = null;
        overlayEl = null;
        pclientEl = null;
    }

    function updateZones(resText, isPartialUpdate) {
        if (isPartialUpdate) {
            var mainViewId = '#'+namespace+'mainView';
            jQuery.each(resText, function(id, area) {
//                jQuery('#'+id).html('');
                jQuery(mainViewId+' #'+id).replaceWith(area);
//                jQuery(mainViewId+' #' + id).animate({ opacity: "hide" }, "fast").animate({ opacity: "show" }, "fast");
//                fadeUpdate(jQuery(mainViewId+' #'+id));
            });
            mainViewId = null;
        } else {
            jQuery('#'+namespace+'mainView').html('');
            jQuery('#'+namespace+'mainView').replaceWith(resText);
//            fadeUpdate(jQuery('#'+namespace+'mainView'));
//            jQuery('#mainView').animate({ opacity: "hide" }, "fast").animate({ opacity: "show" }, "fast");
        }
        disableWaitPanel(namespace);

        resText = null;
        isPartialUpdate = null;
    }
}


function submitAJAX(/*:String*/ ppath, /*Array|Json*/ pinputParams, /*:Function*/pcallback, /*:Array|DOMElement*/ pdataContainers, /*:HtmlElement*/ pupdateSelector) {
    var params = {};
    var formData = [];
    if (typeof(pinputParams) != 'array') {
        pinputParams = [pinputParams];
    }
    jQuery.each(pinputParams, function(i,pparamsJson) {
        jQuery.each(pparamsJson, function(key,value) {
            params[key] = value;
        });
    });

    if (pdataContainers != null) {
        if (typeof pdataContainers != "array") {
            pdataContainers = jQuery.makeArray(pdataContainers);
        }
        if (pdataContainers.length > 0) {
            jQuery.each(pdataContainers, function(i, pdataContainer) {
                formData = jQuery.merge(formData, jQuery.makeArray(jQuery("input, textarea, select", pdataContainer)));
            });
        }
    }
    jQuery.each(formData, function(pelem) {
        params[formData[pelem].name] = formData[pelem].value;
    });
    var pflowParams = pinputParams.flow;

    if (pflowParams != null) {
        jQuery.each(pflowParams, function(key,value) {
            params["FLOW_"+key] = value;
        });

        delete pinputParams.flow;
    }
    try {
        if (pupdateSelector != null) {
            jQuery.post(ppath, params, pcallback, 'json');
        } else {
            jQuery.post(ppath, params, pcallback);
        }
    } catch(e) {
        alert('error:=' + e.message);
    }

    params = null;
    formData = null;
    pflowParams = null;

    ppath = null;
    pinputParams = null;
    pcallback = null;
    pdataContainers = null;
    pupdateSelector = null;
}
;
