function paramsToFormVariables(url, form) {
    var fixedUrl = url;
    if (url.indexOf('?') > 0){
      var pieces = url.substring(url.indexOf('?') + 1).split("&");
      for(var i = 0; i < pieces.length; i++) {
        var nvp =  _proxy_jslib_handle(pieces, (i), 0, 0).split("=");
         value= _proxy_jslib_assign_rval('', 'value', '=', ( (nvp.length == 2)? nvp[1] : ""), value);
        form.adopt(new (Element)('input',{'type':'hidden', 'name' : nvp[0] , 'value' :  _proxy_jslib_handle(null, 'value', value, 0, 0) }));
      } 
      fixedUrl = url.substring(0,url.indexOf('?'));
    }
    return fixedUrl;
}

function retrieveIds(form) {
   var ids = $(form).getElements('input[name^=ids]');
   var query = "";
   for(var i = 0; i < ids.length; i++){
      var item =  _proxy_jslib_handle(ids, (i), 0, 0);
      query += item.name + "=" +  _proxy_jslib_handle(item, 'value', '', 0, 0) + "&";
   }
   return query;
}
var dependencies = new (Object)();

function _SNML() {
	this.clickRewriteAJAX = function(appId, replaceDivId, url, context, txId, element) {	
		var form = this.findForm(element);
		form.onSubmit = function() {return false;}	
	   queryString = $(form).toQueryString();	
		SNML.clickRewriteAJAXNoForm(appId, replaceDivId, url, context, txId, queryString);
	}
	
	this.clickRewriteAJAXNoForm = function(appId, replaceDivId, url, context, txId, queryString) {
	   this.replaceId = replaceDivId;
      var namespace =  _proxy_jslib_handle( _proxy_jslib_handle(window, 'location', '', 0, 0), 'search', '', 0, 0).toLowerCase().indexOf("ns=true") >=0;
      var ajax = new (Ajax)('/mock-ajax?', 
      { method : 'post', 
        onComplete: this.handleReplace.bind(this),
          evalScripts: true,
        data: {'ns':namespace,'appId': appId,'url': url,'query': queryString, method: 'post','context' : context,'txId': txId}
      });
      ajax.request();
      return false;
	}
	
	this.confirmTos = function(message) {
		return true;
	}
	
	this.handleReplace = function(response) {

		this.mockAjaxResponse = Json.evaluate(response);
		if(this.mockAjaxResponse.ok){
			var element = $(this.replaceId);
      var ajax = this.mockAjaxResponse;
      var originalScripts = $ES('script').map(function(elem,idx) {
          if (  _proxy_jslib_handle(elem, 'src', '', 0, 0) != null ){
            // strip out URL params from the script sources for cleaner comparisons
            var queryStringStartIndex =  _proxy_jslib_handle(elem, 'src', '', 0, 0).indexOf("?");
            if( queryStringStartIndex > 0 ){
              return  _proxy_jslib_handle(elem, 'src', '', 0, 0).substring(0,queryStringStartIndex);
            }
            return  _proxy_jslib_handle(elem, 'src', '', 0, 0);
          } 
        });
      
      for(var i = 0; i < this.mockAjaxResponse.javascript.length; i++) {
        var include =  _proxy_jslib_handle(this.mockAjaxResponse.javascript, (i), 0, 0);

        // strip off the query string so we can cleanly compare the url with scripts already in the page
        var queryStringStartIndex = include.indexOf("?");
        if( queryStringStartIndex > 0 ){
          include = include.substring(0,queryStringStartIndex);
        }

        if (!originalScripts.contains(include)){
          var doc =  _proxy_jslib_handle(document, 'getElementsByTagName', '', 1, 0)('head').item(0);
          var js = document.createElement('script');
           _proxy_jslib_assign('', js, 'src', '=', ( include));

          // need to replace "/" and "." from the dependency key name because IE wont accept those characters
          var dependencyKey =  _proxy_jslib_handle( _proxy_jslib_handle(include, 'replace', '', 1, 0)(/\//g,"_"), 'replace', '', 1, 0)(/\./g,"_");
           _proxy_jslib_assign('', dependencies, (dependencyKey), '=', ( false));  // just to be safe, put this before the code that can possibly set it to true
          
          if( document.all ){
            doc.appendChild(js);
            
            // Using IE propritary event registration because it's the only thing that seems to work here
            js.attachEvent("onreadystatechange", function(e) {
                if( e.srcElement.readyState == "loaded" || e.srcElement.readyState == "complete") {
                  var scriptDependencyKey =  _proxy_jslib_handle( _proxy_jslib_handle( _proxy_jslib_handle(e.srcElement, 'src', '', 0, 0), 'replace', '', 1, 0)(/\//g,"_"), 'replace', '', 1, 0)(/\./g,"_");
                   _proxy_jslib_assign('', dependencies, ( scriptDependencyKey ), '=', ( true));
                }
              });
          } else {
            // FF and Safari uses onload to detect when script loading is complete
             _proxy_jslib_handle(js, 'setAttribute', '', 1, 0)('onload','dependencies["' + dependencyKey +'"] = true');
            doc.appendChild(js);
          }
          
        }
      }

      element.setHTML(this.mockAjaxResponse.html);
      
      var timeoutFunction = function() {
        var shouldRun = true;
        for(key in dependencies){
          if (dependencies.hasOwnProperty(key)){
            if(! _proxy_jslib_handle(dependencies, (key), 0, 0)){
              shouldRun = false;
            }
          }
        }
        if (shouldRun){
          SNML.onScriptLoad(element);
        } else {
           _proxy_jslib_handle(null, 'setTimeout', setTimeout, 1, 0)(timeoutFunction,50);
        }
      }
       _proxy_jslib_handle(null, 'setTimeout', setTimeout, 1, 0)(timeoutFunction, 50);
		} 
	}
 
   this.onScriptLoad = function(element) {
      var scripts = $ES('script',element);
      var script = "";
      scripts.each(function(e) {script +=  _proxy_jslib_handle(e, 'innerHTML', '', 0, 0);});

       _proxy_jslib_handle(window, 'setTimeout', '', 1, 0)("eval(\"" + SNML.escapeJavascript(script) + "\");",0);
   } 

   this.escapeJavascript = function(script) {
     var escapedScript =  _proxy_jslib_handle( _proxy_jslib_handle( _proxy_jslib_handle(script, 'replace', '', 1, 0)(/\\/g, "\\\\"), 'replace', '', 1, 0)(/"/g, "\\\""), 'replace', '', 1, 0)(/\n/g,"\\n");
     var trimmedEscapedScript =  _proxy_jslib_handle(escapedScript, 'replace', '', 1, 0)(/^\s+|\s+$/g,"");
     return trimmedEscapedScript;
   }
	this.findForm = function(element) {
	  var elem = $(element);
	  while (elem != null && "form" != elem.getTag()){
	  	elem = elem.getParent();
	  }
	  return elem; 
	}
	
	this.sendRequest = function(form) {
		var xhr = new (XHR)({async: false, 
								   method: $(form).method,
								   onSuccess: function(rsp) {
								   			var response = Json.evaluate(rsp);
								   			if(response.length > 0){
                                                // use getAttribute since it gives relative urls
								   				var old = form.getAttribute('action');
                                                 _proxy_jslib_assign('', form, 'action', '=', ( paramsToFormVariables(response,form)));
                                                form.adopt(new (Element)('input',{'type':'hidden', 'name' : 'nextMethod', 'value' : form.method}));
								   				form.adopt(new (Element)('input', {'type': 'hidden','name':'next','value':old}));
								   			}
								   		},
								   onFailure: function(response) {
								   			alert("failure");
								   		}
								   });
		xhr.send("/ajax/api?method=notifications.sendRequest&" + $(form).toQueryString(), "");
	}
 

}
var SNML = new (_SNML)();

 ;
_proxy_jslib_flush_write_buffers() ;