/*
 * Written by Are Nybakk
 *
 * Version 1.3
 * 
 * 
 * Changes in this version:
 * 
 * - Corrected errors in Internet Explorer due to different function-to-string handling.
 * - Added functionality for multiple selected elements to be individually set
 * - Added support for discarding jQuery anti-caching parameters
 * 
 * Known issues:
 *
 * - Excess parameter delimiters in rewritten urls
 * 
 * Example of use:
 * 
 * $(".my_container").load(
 *      "/ikbViewer/page/my-ajax-page", 
 *      {"optional_parameter" : "parameter_value"}, 
 *      function(response, status, request) {
 *        if(status == "success") {
 *          var link_selectors = [
 *            ".my_content_item .editDelete > a", 
 *            ".my_content_item .addLink > a"
 *          ];
 *          rewrite_links(link_selectors, "my_new_path");
 *        }
 *      }
 *    );
 *
 */



/**
 * Rewrites a set of links' p_form_back_url to a new url. 
 * Useful for content included by ajax calls.
 *
 * @param  selectors  an array of jQuery selectors.
 * @param  url        the new URL.
 * @param  remove_caching_param    if true, discards any jQuery anti-caching parameters
 */
function rewrite_links(selectors, url, remove_caching_param) {
  
  remove_caching_param = remove_caching_param == null ? "" : remove_caching_param;

  /* Repeat for all selectors */
  for(var i=0; i<selectors.length; i=i+1) {
  
    var selected_elements = $(selectors[i]);
    
    /* Repeat for any matched elements */
    selected_elements.each(function() {
      var selected_element = $(this);
      var link_onclick_attribute = selected_element.attr("onclick");
      
      /* Only if the attribute is set */
      if(link_onclick_attribute != null 
          && link_onclick_attribute != "") {
      
        /* Copy the content of the assigned onclick function */
        var link_onclick = "" + link_onclick_attribute;
        var new_link_onclick = link_onclick
            .replace(/\n/g,"")
            .replace(/\t/g,"")
            .replace(/\}/g,"");
        
        /* IE does not include "javascript:" so a check has to be done */
        var isIE = false;
        if(new_link_onclick.indexOf("javascript:") == -1) {
          isIE = true;
          new_link_onclick = new_link_onclick.split("{")[1];
        } else {
          new_link_onclick = new_link_onclick.split("javascript:")[1];
        }
            
        /* Get the parameter part of the url */
        var link_url = "";
        
        if(isIE) { /* IE special treatment */
          link_url = new_link_onclick.split("','")[0].split("window.open('")[1];
        }
		else if (jQuery.browser.opera) {
			link_url = new_link_onclick.split("','")[0].split("window.open('")[1].split('"')[0];
		}
		else {
          link_url = new_link_onclick.split('", "')[0].split('window.open("')[1].split('"')[0];
        }
		if (link_url == undefined || link_url == null) {
			// will skip to the next element in the iteration
			return true;
		}
        var link_params = link_url.split("?")[1];
        
        /* Replace any p_form_back_url content */
        var link_back_urls = link_params.split("p_form_back_url=");
        for(var j=1; j<link_back_urls.length; j=j+1){
        
          var current_url = link_back_urls[j];
          var current_params = "";
          
          /* Get parameters (Delimiter may vary between '?' and '&' for some unknown reason) */
          if(current_url.indexOf("?") != -1) {
            current_params = current_url.split("?")[1];
          } else if(current_url.indexOf("&") != -1) {
            current_params = current_url.split("&")[1];
          }
          
          if(typeof(current_params) == 'undefined') {
            current_params = "";
          } else {
          
            /* Discard anti-caching parameter */
            if(remove_caching_param) {
              var params_to_check = current_params.split("&");
              for(var t=0; t<params_to_check.length; t=t+1) {
                if(params_to_check[t].charAt(0) == "_") {
                  /* Replace the preceding sign also */
                  /* var sign = current_params.charAt(current_params.indexOf(params_to_check[t])-1);*/
                  current_params.replace(params_to_check[t],"");
                }
              }
            }
            
          }
          
          /* Make sure there is only one first parameter */
          if(url.indexOf("?") == -1) {
            url = url + "?" + current_params.replace("?","&");
          } else {
            url = url + "&" + current_params.replace("?","&");
          }
          
          /* If there are more p_form_back_urls, end with '&'. Typically quick links. */
          if(j+1 < link_back_urls.length) {
            url = url + "&";
          }
			
          new_link_onclick = new_link_onclick.replace(current_url, url);
          
        }
        
        /* Reset onclick handler */
        selected_element.removeAttr("onclick");
        selected_element.click(new Function(new_link_onclick));
        
      }
      
    });
    
  }
  
}

