
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 = pieces[i].split("=");
        value = (nvp.length == 2)? nvp[1] : "";
        form.adopt(new Element('input',{'type':'hidden', 'name' : nvp[0] , 'value' : value }));
      } 
      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 = ids[i];
      query += item.name + "=" + item.value + "&";
   }
   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 = window.location.search.toLowerCase().indexOf("ns=true") >=0;
      var ajax = new Request.JSON({
         'url': '/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.send();
      return false;
   }
   
   this.confirmTos = function(message){
      return true;
   }
   
   this.handleReplace = function(response){
      this.mockAjaxResponse = response;
      if(this.mockAjaxResponse.ok){
         var element = $(this.replaceId);
         var ajax = this.mockAjaxResponse;
         var originalScripts = $(document).getElements('script').map(function(elem,idx) {
          if ( elem.src != null ){
            // strip out URL params from the script sources for cleaner comparisons
            var queryStringStartIndex = elem.src.indexOf("?");
            if( queryStringStartIndex > 0 ){
              return elem.src.substring(0,queryStringStartIndex);
            }
            return elem.src;
          } 
        });
      
      for(var i = 0; i < this.mockAjaxResponse.javascript.length; i++) {
        var include = this.mockAjaxResponse.javascript[i];

        // 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 = document.getElementsByTagName('head').item(0);
          var js = document.createElement('script');
          js.src = include;

          // need to replace "/" and "." from the dependency key name because IE wont accept those characters
          var dependencyKey = include.replace(/\//g,"_").replace(/\./g,"_");
          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 = e.srcElement.src.replace(/\//g,"_").replace(/\./g,"_");
                  dependencies[ scriptDependencyKey ] = true;
                }
              });
          } else {
            // FF and Safari uses onload to detect when script loading is complete
            js.setAttribute('onload','dependencies["' + dependencyKey +'"] = true');
            doc.appendChild(js);
          }
          
        }
      }
      
      // the following replace fixes a strange behavior in IE (imagine that!) where script tags
      // disappear when set as innerHTML. Placing a br tag before the script makes it work.
      // I really don't get paid enough to deal with IE --no one does.
      element.set('html', this.mockAjaxResponse.html.replace(/<script/,"<br/><script"));
      var timeoutFunction = function(){
        var shouldRun = true;
        for(key in dependencies){
          if (dependencies.hasOwnProperty(key)){
            if(!dependencies[key]){
              shouldRun = false;
            }
          }
        }
        if (shouldRun){
          SNML.onScriptLoad(element);
        } else {
          setTimeout(timeoutFunction,50);
        }
      }
      setTimeout(timeoutFunction, 50);
      } 
   }
 
   this.onScriptLoad = function(element) {
      var scripts = element.getElements('script');
      var script = "";
      scripts.each(function(e) {script += e.innerHTML;});
      window.setTimeout("eval(\"" + SNML.escapeJavascript(script) + "\");",0);
   } 

   this.escapeJavascript = function(script) {
     var escapedScript = script.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g,"\\n");
     var trimmedEscapedScript = escapedScript.replace(/^\s+|\s+$/g,"");
     return trimmedEscapedScript;
   }
   this.findForm = function(element){
     var elem = $(element);
     while (elem != null && "form" != elem.get('tag')){
      elem = elem.getParent();
     }
     return elem; 
   }
   
   this.sendRequest = function(form){
      var xhr = new Request.JSON({
    	  url: "/ajax/api?method=notifications.sendRequest&" + $(form).toQueryString(),
    	  async: false, 
          method: $(form).method,
          onComplete: function(rsp){
          				var response = rsp;
                        if(response.length > 0){
                        	// use getAttribute since it gives relative urls
                        	var old = form.getAttribute('action');
                            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.get();
   }
 

}
var SNML = new _SNML();


