/**
 * Helper over prototype.js for nownow-specific pattern
 *
 * NOTE: THIS requires prototype.js version 1.5.0_rc0
 * and upgrading will require two things:
 *
 * 1) Fixing the inheritance of ProgressableUpdater (this.containers => this.container - see svnrev 4581)
 * 2) Fixing the javascript param problem outlined in JIRA - NEMO-1181
 */

Ajax.ProgressableUpdater = Class.create();

Object.extend(Object.extend(Ajax.ProgressableUpdater.prototype, Ajax.Updater.prototype), {

  initialize: function(container, url, options) {
    this.containers = {
      progress: container.progress ? $(container.progress) : null,
      success: container.success ? $(container.success) : $(container),
      failure: container.failure ? $(container.failure) :
        (container.success ? null : $(container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, object) {
      this.updateContent();
      this.stopProgress();
      onComplete(transport, object);
    }).bind(this);


    var onFailure = this.options.onFailure || Prototype.emptyFunction;
    this.options.onFailure = (function(request) {
      this.stopProgress();
      onFailure(request);
    }).bind(this);

  	if (this.containers.progress != undefined) {
  		this.containers.progress.style.display = 'block';
  	}
    this.request(url);
  },

  stopProgress: function() {
  	if (this.containers.progress != undefined) {
  		this.containers.progress.style.display = 'none';
  	}
  }
});


    function ajaxFormSubmit(formId, url, contentDivId, progressDivId) {
        var f = document.getElementById(formId);
		var method = f.method.toLowerCase();
		var pars = Form.serialize(formId);
		ajaxUpdateDiv(url, pars, method, contentDivId, progressDivId);
    }

    function ajaxFormSubmitCallback(formId, url, contentDivId, progressDivId, callback) {
        var f = document.getElementById(formId);
        var method = f.method.toLowerCase();
        var pars = Form.serialize(formId);
        ajaxLoad(url, pars, method, contentDivId, progressDivId, null, callback, null);
    }

    function ajaxFormSubmitSync(formId, url, contentDivId, progressDivId) {
        var f = document.getElementById(formId);
		var method = f.method.toLowerCase();
		var pars = Form.serialize(formId);
		ajaxUpdateDivSync(url, pars, method, contentDivId, progressDivId);
    }

    /* this version does not append a date string to keep browser cache */
    function ajaxUpdateDivDefault(url, pars, method, contentDivId, progressDivId) {
        var myAjax = new Ajax.ProgressableUpdater(
            { success: contentDivId,
              progress: progressDivId},
            url,
            { method: method,
              parameters: pars,
              evalScripts: true,
              onFailure: reportAjaxUpdateError
            } );

        // Other parameters:
        /// asynchronous: true,
        /// alert(myAjax.url);
        /// alert(myAjax.containers.success);
        /// alert(myAjax.containers.failure);
    }

    function appendDateToParams(pars, method, nowOverride) {
        if (method == 'get') {
            var now;
            if (nowOverride) {
                now = nowOverride;
            }
            else {    
                var currentDate = new Date();
                now = currentDate.getTime();
            }
            if (pars != null && pars != "") {
                pars += '&';
            }
            pars += 'now=' + now;
        }
        return pars;
    }

    /* This version will purposely append a current date string to trick IE into not caching the content */
    function ajaxUpdateDiv(url, pars, method, contentDivId, progressDivId) {
        pars = appendDateToParams(pars, method);
        ajaxUpdateDivDefault(url, pars, method, contentDivId, progressDivId);
    }

    /* this version hides and then shows the result div to eliminate jumpiness */
    function ajaxLoad(url, pars, method, contentDivId, progressDivId, now /* = null; for overriding date param re browser caching */, callback /* = null */, failureCallback /* = null */) {
        pars = appendDateToParams(pars, method, now);
        hide(contentDivId);
        if (!failureCallback) {
            failureCallback = reportAjaxUpdateError;
        }
        var myAjax = new Ajax.ProgressableUpdater(
            { success: contentDivId,
              progress: progressDivId
            },
            url,
            { method: method,
              parameters: pars,
              evalScripts: true,
              onFailure: failureCallback,
              onComplete: function () {
                showBlock(contentDivId);
                if (callback) {
                    callback();
                }
              }
            }
        );
    }
    
    function ajaxUpdateSuperPower (url, pars, method, contentDivId, progressDivId) {
        pars = appendDateToParams(pars, method);
		var myAjax = new Ajax.ProgressableUpdater(
			{ success: contentDivId,
			  progress: progressDivId},
			url,
			{ asynchronous: true,
			  method: method,
			  parameters: pars,
			  evalScripts: true,
			  onFailure: reportAjaxUpdateError,
              onComplete: showSuperPowers
			} );

        // Other parameters:
		///
		/// alert(myAjax.url);
		/// alert(myAjax.containers.success);
		/// alert(myAjax.containers.failure);
    }

    function ajaxCheckSuperPower (url, pars, method, contentDivId, progressDivId) {
        pars = appendDateToParams(pars, method);
		var myAjax = new Ajax.ProgressableUpdater(
			{ success: contentDivId,
			  progress: progressDivId},
			url,
			{ method: method,
			  parameters: pars,
			  evalScripts: true,
              asynchronous: false,
			  onFailure: reportAjaxUpdateError,
              onComplete: checkActivatedSuperpower
			} );
        // Other parameters:
		/// asynchronous: true,
		/// alert(myAjax.url);
		/// alert(myAjax.containers.success);
		/// alert(myAjax.containers.failure);
    }

    // warning currently not working - for some reason it won't complete!
    function ajaxUpdateDivSync(url, pars, method, contentDivId, progressDivId) {
		var myAjax = new Ajax.ProgressableUpdater(
			{ success: contentDivId,
			  progress: progressDivId},
			url,
			{ method: method,
			  parameters: pars,
			  evalScripts: true,
              asynchronous: false,
			  onFailure: reportAjaxUpdateError
			} );

    }

    function ajaxUpdateDivCallback(url, pars, method, contentDivId, progressDivId, callbackFunc) {
        pars = appendDateToParams(pars, method);
        var myAjax = new Ajax.ProgressableUpdater(
            { success: contentDivId,
              progress: progressDivId},
            url,
            { method: method,
              parameters: pars,
              evalScripts: true,
              onFailure: reportAjaxUpdateError,
              onComplete: callbackFunc
            } );
    }

    function ajaxPeriodicalUpdateDiv(url, pars, method, contentDivId, periodInSeconds) {
    	var myAjax = new Ajax.PeriodicalUpdater(
    		{ success: contentDivId},
    		url,
    		{ method: method,
    		  parameters: pars,
    		  evalScripts: true,
    		  frequency: periodInSeconds
    		} );
    	return myAjax;
    }


    function ajaxFormSubmitAndForget(formId, url) {
        var f = document.getElementById(formId);
        var method = f.method.toLowerCase();
        var pars = '';
        var postBody = '';
        if ("post" == method) {
            postBody = Form.serialize(formId);
        }
        else {
            pars = Form.serialize(formId);
        }
        var myAjax = new Ajax.Request(
                        url,
                        {method : method,
                         parameters : pars,
                         postBody: postBody
                        });
        return myAjax;
    }


    function ajaxFireAndForget(url,pars,method){
        pars = appendDateToParams(pars, method);
    	var myAjax = new Ajax.Request(
    					url,
    					{method : method,
    					 parameters : pars
    					});
    	return myAjax;
    }

    function reportAjaxUpdateError(transport, json)
    {
        alert('Sorry, there was an ajax error! status=['+transport.status+']');
    }

	/**
	 * Use the specified javascript function to submit the form in ajax
	 * if the function is specified.
	 * Commented out 'cuz it doesn't work when ajaxSubmitFunc is not defined.
	function ajaxFormSubmitIfNeeded(formId, ajaxSubmitFunc) {
		if (typeof ajaxSubmitFunc == "function") {
			ajaxSubmitFunc(formId);
		}
		else {
			document.getElementById(formId).submit();
		}
	}
	 */
