//google.load("jquery", "1.3.2");
//google.load("swfobject", "2.2");

//google.setOnLoadCallback(initializeSmartLinks);

// if you load jquery and swfobject manually, then change beginning of file from this:
// google.load("jquery", "1.3.2");
// google.load("swfobject", "2.2");
//
// google.setOnLoadCallback(initializeSmartLinks);
//
// to this:
//
$(document).ready(function() {
             
//var $SMARTLINK_SERVER;

if (! $SMARTLINK_SERVER) {
    $SMARTLINK_SERVER = 'http://smartlinks.mediresource.com';
}

var $M = {
  util: {
    templateToStr: function(template, values) {
      var retVal = template;
      for (var value in values) {
        retVal = retVal.replace(new RegExp('\#\{' + value + '\}', "gi"), values[value]);
      }
      return retVal;
    },
    queryString: function(variable, qs) {
      var query;
      if (qs && qs.match) {
        query = String(qs.match(/\?.*/)).substring(1);
      } else {
        query = window.location.search.substring(1);
      }
      var vars = query.split("&"); 
      for (var i=0;i<vars.length;i++) { 
          var pair = vars[i].split("="); 
    
          if (pair[0] == variable) { 
              return pair[1]; 
          }
      }
    },
    cookie: {
      set: function(name, value, path, daysToExpire) {
        var expire = '';
        var path = '';
        if (daysToExpire != undefined) {
          var d = new Date();
          d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
          expire = '; expires=' + d.toGMTString();
        }
        if (path != undefined) {
          path = '; path=/' + path.substr(1, path.length - 1);
        }
        return (document.cookie = escape(name) + '=' + escape(value || '') + expire + path);
      },
      get: function(name) {
        var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
        return (cookie ? unescape(cookie[2]) : null);
      },
      erase: function(name) {
        var cookie = $M.util.cookie.get(name) || true;
        $M.util.cookie.set(name, '', -1);
        return cookie;
      },
      accept: function() {
        if (typeof navigator.cookieEnabled == 'boolean') {
          return navigator.cookieEnabled;
        }
        $M.util.cookie.set('_test', '1');
        return ($M.util.cookie.erase('_test') === '1');
      }
    }    
  },
  smartLink: {    
    consts: {
      popup: {
        simpleText: 1,
        simpleHtml: 2,
        flash: 3
      },
      action: {
        instanceCount: 1,
        smartLinkHover: 2,
        smartLinkClick: 3
      }
    },
    context: {
      portalId: 707,
      sourceTypeId: 0,
      channelId: 0,
      sourceId: 0,
      sessionId: 0
    },
    click: function(smartLinkId, event) {
      $M.smartLink.recordAction(smartLinkId,                    
                                $M.smartLink.consts.action.smartLinkClick,
                                $M.smartLink.context.portalId,
                                $M.smartLink.context.channelId,
                                $M.smartLink.context.sourceTypeId,
                                $M.smartLink.context.sourceId,
                                0);
    },
		popup: {
	    lastLinkTypeId: 0,
	    trigger: function(smartLink, event) {
	      var linkTypeId = parseInt(smartLink.linkType.id);
	      
	      switch (linkTypeId) {
	        case $M.smartLink.consts.popup.simpleHtml:
	          $M.smartLink.popup.simpleHtmlPopup(smartLink, event);
	          break;
	        case $M.smartLink.consts.popup.flash:
	          $M.smartLink.popup.flashPopup(smartLink, event);
	          break;
	      }
//        if ($M.smartLink.popup.lastLinkTypeId != linkTypeId ) {
//	        $.getScript('http://smartlinks/LinkTypes/' + linkTypeId + '/behaviour.js', function() { $M.smartLink.popup.behaviour(smartLink, event) });
//        }
//        else {
//          $M.smartLink.popup.behaviour(smartLink, event);
//        }
//        
//        $M.smartLink.popup.lastLinkTypeId = linkTypeId;

        if (linkTypeId == $M.smartLink.consts.popup.simpleHtml) {
          $M.smartLink.recordAction(smartLink.id,
                                    $M.smartLink.consts.action.smartLinkHover,
                                    $M.smartLink.context.portalId,
                                    $M.smartLink.context.channelId,
                                    $M.smartLink.context.sourceTypeId,
                                    $M.smartLink.context.sourceId,
                                    0);
        }
	    },
	    simpleHtmlPopup: function(smartLink, event) {
        var smartLinkId = smartLink.id;
        var linkTypeId = smartLink.linkType.id;
        var keyword = smartLink.keyword;
        var targetUrl = smartLink.targetUrl;
        
        // Default HTML with image on the left
        /*html: '<div id="POPUP" class="smartLink-simpleHtmlPopup"><div class="description"><img src="http://www.medbroadcast.com/nav_images/medbroadcast_logo.gif" align="left"/>To find out more about #{keyword}, <a href="#{targetUrl}" title="more information">click here</a>.</div></div>'*/

        smartLink.vars = jQuery.extend({
          html: '<div id="POPUP" class="smartLink-simpleHtmlPopup"><div class="description"><img src="http://www.medbroadcast.com/nav_images/SmartLinksLogo.gif" align="left"/>To find out more about #{keyword}, <a href="#{targetUrl}" title="more information">click here</a>.</div></div>'
//          css: {
//          		  ".smartLink-simpleHtmlPopup": {
//          		    "padding": "0 0 40px 0",
//          		    "position": "absolute",
//          		    "width": "242px",
//          		    "background": "url(http://smartlinks/LinkTypes/2/bottom.gif) no-repeat bottom",
//          		    "top": "0",
//          		    "left": "0",
//          		    "z-index": "1000",
//          		    "font-family": "Arial"
//          		  },
//          		  ".smartLink-simpleHtmlPopup div.keyword": {
//          		    "background": "url(http://smartlinks/LinkTypes/2/top.png) no-repeat transparent",
//          		    "line-height": "17px",
//          		    "height": "17px",
//          		    "width": "242px",
//          		    "padding": "3px",
//          		    "color": "#efefef",
//          		    "font-weight": "bold",
//          		    "font-size": "16px"
//          		  },
//          		  ".smartLink-simpleHtmlPopup div.description": {
//          		    "background": "url(http://smartlinks/LinkTypes/2/middle.png) no-repeat transparent",
//          		    "min-height": "110px",
//          		    "height": "110px",
//          		    "padding": "10px",
//          		    "font-size": "14px"
//          		  },
//          		  ".smartLink-simpleHtmlPopup div.description a": {
//          		    "font-size": "14px",
//          		    "font-weight": "bold"
//          		  }
//          		}
        }, smartLink.vars);

        // Remove a popup that is already showing to make way for this new popup
        $('#POPUP').remove();

        $M.smartLink.popup.cursorIsHoveringOver = true;

        // Populate our HTML template with values. Here the event handler has access the vars.html property
        // which can be set in the database in SmartLinks.dbo.LinkTypeJavascriptVariables
        // A default value is also set at the beginning of this file.
        $('body').append($M.util.templateToStr(smartLink.vars.html, {
    	    keyword: keyword,
    	    targetUrl: targetUrl
        }));
        $('#POPUP a').bind('mousedown', function(event) { $M.smartLink.click(smartLinkId, event); });
        
        // BEGIN: style the html popup we have created. Here the event handler has access to the vars.css propert
        // which can be set in the database in SmartLinks.dbo.LinkTypeJavascriptVariables.
        // A default value is also set at the beginning of this file.
        if (smartLink.vars.css) {
      		$.each(smartLink.vars.css, function(selector, styles) {
      		  $(selector).css(styles);
      		});
        }
//    		for (selector in obj) {
//    		  $(selector).css(obj[selector]);
//    		}

        // Position the popup just around the mouse cursor
        var leftAnchor = 45;
        $('#POPUP').css('left', (event.pageX - leftAnchor) + 'px');
        $('#POPUP').css('top', (event.pageY - 60 - $('#POPUP').height()) + 'px'); // 60 is the bottom padding of the popup element + 20

        // Bind an event handler that removes the popup if we have the mouse cursor over it and move it outside
        $('#POPUP').bind('mouseleave', function() {
          $('#POPUP').remove();
        });

        // Remove the popup after 3 seconds. - changed by AG 20080904
        // Cache this instance of the popup so we do not remove
        // another instance of the popup after a time delay.
        var popup = $('#POPUP');				
        var removeOnInterval = window.setInterval( function() {
            if ( popup && !($M.smartLink.popup.cursorIsHoveringOver) ) {
              window.clearInterval(removeOnInterval);
    	        popup.remove();
            }
        }, 3000);

        // We don't want to remove the popup after 3 seconds if the user moves the mouse cursor over the popup
        // within that time.
        $('#POPUP').bind('mouseenter', function() {
          window.clearInterval(removeOnInterval);
        });
        $(event.target).bind('mouseout', function() { $M.smartLink.popup.cursorIsHoveringOver = false });
	    },	    
      flashPopup: function(smartLink, event) {
        var smartLinkId = smartLink.id;
        var linkTypeId = smartLink.linkType.id;
        var keyword = smartLink.keyword;
        var targetUrl = smartLink.targetUrl;

        smartLink.vars = jQuery.extend({
          html: '<div id="POPUP" class="smartLink-flashPopup"></div>',
          css: {
          		  "#POPUP": {
          		    "background": "transparent",
          		    "position": "absolute",
          		    "z-index": "1000"
          		  }
          		}
        }, smartLink.vars);
        
        // Remove a popup that is already showing to make way for this new popup
        $('#POPUP').remove();

        $M.smartLink.popup.cursorIsHoveringOver = true;

        // Populate our HTML template with values. Here the event handler has access the vars.html property
        // which can be set in the database in SmartLinks.dbo.LinkTypeJavascriptVariables
        // A default value is also set at the beginning of this file.
        $('body').append($M.util.templateToStr(smartLink.vars.html, {
    	    keyword: keyword,
    	    targetUrl: targetUrl
        }));

        var o = smartLink.vars.swf;
        swfobject.embedSWF(o.url, o.id, o.width, o.height, o.flashVersion);

        // BEGIN: style the html popup we have created. Here the event handler has access to the vars.css propert
        // which can be set in the database in SmartLinks.dbo.LinkTypeJavascriptVariables.
        // A default value is also set at the beginning of this file.
        if (smartLink.vars.css) {
      		$.each(smartLink.vars.css, function(selector, styles) {
      		  $(selector).css(styles);
      		});
        }

        // Position the popup just around the mouse cursor
        var leftAnchor = 45;
        $('#POPUP').css('left', (event.pageX - leftAnchor) + 'px');
        $('#POPUP').css('top', (event.pageY - 60 - $('#POPUP').height()) + 'px'); // 60 is the bottom padding of the popup element + 20

        // Bind an event handler that removes the popup if we have the mouse cursor over it and move it outside
        $('#POPUP').bind('mouseleave', function() {
          $('#POPUP').remove();
        });

        // Remove the popup after 3 seconds. - changed by AG 20080904
        // Cache this instance of the popup so we do not remove
        // another instance of the popup after a time delay.
        var popup = $('#POPUP');				
        var removeOnInterval = window.setInterval( function() {
            if ( popup && !($M.smartLink.popup.cursorIsHoveringOver) ) {
              window.clearInterval(removeOnInterval);
    	        popup.remove();
            }
        }, 3000);

        // We don't want to remove the popup after 3 seconds if the user moves the mouse cursor over the popup
        // within that time.
        $('#POPUP').bind('mouseenter', function() {
          window.clearInterval(removeOnInterval);
        });
        $(event.target).bind('mouseout', function() { $M.smartLink.popup.cursorIsHoveringOver = false });
      }
    },
		recordAction: function(smartLinkId, actionTypeId, param1, param2, param3, param4, param5) {		  
      $.getJSON($SMARTLINK_SERVER + '/actions.ashx?SmartLinkId=' + smartLinkId + '&SessionId=' + $M.smartLink.context.sessionId + '&ActionTypeId=' + actionTypeId + '&Param1=' + param1 + '&Param2=' + param2 + '&Param3=' + param3 + '&Param4=' + param4 + '&Param5=' + param5 + '&jsonpcallback=?', function(json) {});
		}
	}	
};

initializeSmartLinks();

function initializeSmartLinks() {
    
	// Customize the portal id, source type id, and source id for each page load instance
	$M.smartLink.context.channelId = $M.util.queryString("channel_id") || 0;
	
	if ( location.href.toLowerCase().indexOf('condition_info_details.asp') > -1 ) {
		$M.smartLink.context.sourceTypeId = 1;
		$M.smartLink.context.sourceId = $M.util.queryString('disease_id');
	}
	else if ( location.href.toLowerCase().indexOf('drug_info_details.asp') > -1 ) {
		if ($M.util.queryString("brand_name_id") != 1815) //suppress smart links for crestor
	    	{
		    $M.smartLink.context.sourceTypeId = 2;
		    $M.smartLink.context.sourceId = $M.util.queryString('brand_name_id') || 0;
		}
	}
	else if ( location.href.toLowerCase().indexOf('section_details.asp') > -1 ) {
	    $M.smartLink.context.sourceTypeId = 3;
	    $M.smartLink.context.sourceId = $M.util.queryString('text_id') || 0;
	}
	else if ( location.href.toLowerCase().indexOf('test_and_procedure_info_details.asp') > -1) {
    $M.smartLink.context.sourceTypeId = 89;
	    $M.smartLink.context.sourceId = $M.util.queryString('TPid') || 0;
	}
	else if ( location.href.toLowerCase().indexOf('natural_products_info_details.asp') > -1) {
	  $M.smartLink.context.sourceTypeId = 90;
	  $M.smartLink.context.sourceId = $M.util.queryString('nhp_id') || 0;
	}
	else if ( location.href.toLowerCase().indexOf('health_features_details.asp') > -1) {
	  $M.smartLink.context.sourceTypeId = 10;
	  $M.smartLink.context.sourceId = $M.util.queryString('article_id');
	}
	else if ( location.href.toLowerCase().indexOf('health_news_details.asp') > -1) {
	  if ($M.util.queryString('news_src') == 0) {
	    $M.smartLink.context.sourceTypeId = 999;
	  }
	  else {
	    $M.smartLink.context.sourceTypeId = 888;
	  }
	  $M.smartLink.context.sourceId = $M.util.queryString('news_id') || 0;
	}
  	
  $M.smartLink.context.sessionId = $M.util.cookie.get("SessionId") || 9999;
  
  if (! $M.smartLink.context.sessionId) {
    $.getJSON($SMARTLINK_SERVER + "/Sessions.ashx?jsonpcallback=?",
        function(json) {
          $M.smartLink.context.sessionId = json.sessionId;
          $M.util.cookie.set("SessionId", json.sessionId);
        }
     );
  }
  
  function is_a_link_to_current_page(url) {
    var _portalId;
    var _sourceTypeId;
    var _sourceId;
    var _channelId = $M.util.queryString("channel_id", url) || 0;
    
  	if ( url.toLowerCase().indexOf('condition_info_details.asp') > -1 ) {
  		_sourceTypeId = 1;
  		_sourceId = $M.util.queryString('disease_id', url);
  	}
  	else if ( url.toLowerCase().indexOf('drug_info_details.asp') > -1 ) {
  	  _sourceTypeId = 2;
  	  _sourceId = $M.util.queryString('brand_name_id', url) || 0;
  	}
  	else if ( url.toLowerCase().indexOf('section_details.asp') > -1 ) {
  	  _sourceTypeId = 3;
  	  _sourceId = $M.util.queryString('text_id', url) || 0;
  	}
  	else if ( url.toLowerCase().indexOf('test_and_procedure_info_details.asp') > -1) {
	    _sourceTypeId = 89;
  	  _sourceId = $M.util.queryString('TPid', url) || 0;
  	}
  	else if ( url.toLowerCase().indexOf('natural_products_info_details.asp') > -1) {
  	  _sourceTypeId = 90;
  	  _sourceId = $M.util.queryString('nhp_id', url) || 0;
  	}
  	else if ( url.toLowerCase().indexOf('health_features_details.asp') > -1) {
  	  _sourceTypeId = 10;
  	  _sourceId = $M.util.queryString('article_id', url);
  	}
  	else if ( url.toLowerCase().indexOf('health_news_details.asp') > -1) {
  	  if ($M.util.queryString('news_src', url) == 0) {
  	    _sourceTypeId = 999;
  	  }
  	  else {
  	    _sourceTypeId = 888;
  	  }
  	  _sourceId = $M.util.queryString('news_id', url) || 0;
  	}

  	
  	return ((_sourceTypeId == $M.smartLink.context.sourceTypeId) &&
  	      (_sourceId == $M.smartLink.context.sourceId) &&
  	      (_channelId == $M.smartLink.context.channelId));
  }
  
  function instances_of(subject) {
		var re = new RegExp("\\b" + subject + "[,]*\\b", "gi");
		return re;
  }
  
	function in_content_area_for_portal_id(portal_id) {
	    switch ($M.smartLink.context.sourceTypeId) {
	        case 1:
        		return $('#DetailContentBox');
            break;
	        case 2:
            		return $('#DetailContentBox');
            break;
	        case 3:
            return $('#ArticleContainer');
            break;
	        case 89:
	          return $('#TestsAndProceduresContentContainer');
	          break;
	        case 90:
	          return $('#ContentContainer');
	          break;
	        case 888:
	          return $('#ContentContainer');
	          break;
	        case 999:
	          return $('#ContentContainer');
	          break;
          case 10:
            return $('#HealthFeatureContainer');
            break;
	        default:
            return $('#ContentContainer');
            break;
	    }
	}

	function createTextLink(smartLinkId, keyword, url) {
		// Don't link to the same page
		if ( is_a_link_to_current_page(url) ) {
			return keyword;
		}
		else {
			return "<a href=\"" + url + "\" class=\"mediresource-link mediresource-smartLink\" smartLinkId=\"" + smartLinkId + "\">" + keyword + "</a>";
		}
	}

  function createPopupLink(i, smartLink, keyword) {    
		// Don't link to the same page
		if ( is_a_link_to_current_page(smartLink.targetUrl) ) {
			return smartLink.keyword;
		}
		else {
			return "<a href=\"" + smartLink.targetUrl + "\" class=\"mediresource-link mediresource-smartLink-popUp\" smartLinkIndex=\"" + i + "\">" + keyword + "</a>";
		}
  }
  
  function createFlashLink(i, smartLink, keyword) {
    // Don't link to the same page
    if ( is_a_link_to_current_page(smartLink.targetUrl) ) {
      return smartLink.keyword;
    }
    else {
      return "<a href=\"" + smartLink.targetUrl + "\" class=\"mediresource-link mediresource-smartLink-flash\" smartLinkIndex=\"" + i + "\" swf=\"" + smartLink.swfUrl + "\">" + keyword + "</a>";
    }
  }
  
	var exceptions = [
          /<a[^>]*><img[^>]*><\/a>/gi,
	  /<img[^>]*>/gi,
	  /<h[^>]*>[\S\s]*?<\/h[^>]*>/gi,
	  /<a[^>]*>[\S\s]*?<\/a>/gi,
	  /<table[^>]*>[\S\s]*?<\/table>/gi,
	  /<script[^>]*>[\S\s]*?<\/script>/gi,
	  /<span class=["]?bigredtext["]?>[\S\s]*?<\/span>/gi
	];
	var workingHtml;
	var savedExceptions = new Array();

	function handle_exceptions_after_smartlinking() {
		$.each(savedExceptions, function(i) {
			workingHtml = workingHtml.replace("<!--SmartLinkException" + i + "-->", savedExceptions[i]);
		});
	}

	function handle_exceptions_before_smartlinking() {
	  var tmpHtml = workingHtml;
		var i = 0;
		$.each(exceptions, function() {
			var matches;
			while ( matches = this.exec(workingHtml) ) {
				tmpHtml = tmpHtml.replace(matches[0], "<!--SmartLinkException" + i + "-->");
				savedExceptions.push(matches[0]);
				i++;
			}
		});
		workingHtml = tmpHtml;
	}

	function convert_up_to(maximum_number_of_instances, search_term, context) {
  	var numMatches = 0;
  	var counter = 0;
  	var upper = context.smartLink.keyword.substr(0, 1).toUpperCase() + context.smartLink.keyword.substr(1, context.smartLink.keyword.length - 1);
  	var startIndex = 0;
  	var htmlCopy = workingHtml;
  	var match;
  	
  	var matches = workingHtml.match(search_term);
  	var allMatches = (matches) ? matches.length : 0;

    search_term.lastIndex = 0; // IE bug fix, go figure
    
  	while ( (match = search_term.exec(htmlCopy)) != null ) {
	    var replace;
	    var re;
      if (maximum_number_of_instances == 0 || numMatches < maximum_number_of_instances) {        
        if (counter == 0 || counter == (allMatches - 1) || (counter == (Math.round(allMatches / 2)) && (maximum_number_of_instances > 2 || maximum_number_of_instances == 0) ) ) {
      		if ( match[0] == upper ) {
      		  switch (parseInt(context.smartLink.linkType.id)) {
    		      case $M.smartLink.consts.popup.simpleText:
    		        replace = createTextLink(context.smartLink.id, upper, context.smartLink.targetUrl);
    		        break;
      		    case $M.smartLink.consts.popup.flash:
      		      replace = createFlashLink(context.index, context.smartLink, upper);
      		      break;
    		      default:
    		        replace = createPopupLink(context.index, context.smartLink, upper);
    		        break;
      		  }
      		  re = new RegExp("\\b" + upper + "\\b");          
  	        workingHtml = workingHtml.substr(0, startIndex) + workingHtml.substr(startIndex).replace(re, replace);

      			numMatches++;
      		}
      		else {
      			if ( match[0] == context.smartLink.keyword ) {
        		  switch (parseInt(context.smartLink.linkType.id)) {
      		      case $M.smartLink.consts.popup.simpleText:
      		        replace = createTextLink(context.smartLink.id, context.smartLink.keyword, context.smartLink.targetUrl);
      		        break;
        		    case $M.smartLink.consts.popup.flash:
        		      replace = createFlashLink(context.index, context.smartLink, context.smartLink.keyword);
        		      break;
      		      default:
      		        replace = createPopupLink(context.index, context.smartLink, context.smartLink.keyword);
      		        break;
        		  }
        		  re = new RegExp("\\b" + context.smartLink.keyword + "\\b");          
        		  workingHtml = workingHtml.substr(0, startIndex) + workingHtml.substr(startIndex).replace(re, replace);      		  

      				numMatches++;
      			}
      	  }
        }
    	  startIndex = search_term.lastIndex + (workingHtml.length - htmlCopy.length);
    	  counter++;            	  
      }
      else {
        return numMatches;
      }
  	}
  	
    return numMatches;
	}

	if ($M.smartLink.context.sourceTypeId > 0) {
	  var allSmartLinks = [];
    
    $.getJSON($SMARTLINK_SERVER + "/SmartLinks.ashx?portalId=" + $M.smartLink.context.portalId
        + "&channelId=" + $M.smartLink.context.channelId
        + "&sourceTypeId=" + $M.smartLink.context.sourceTypeId
        + "&sourceId=" + $M.smartLink.context.sourceId
        + "&sessionId=" + $M.smartLink.context.sessionId
        + "&jsonpcallback=?",
  
        function(json) {
          workingHtml = $(in_content_area_for_portal_id($M.smartLink.context.portalId)).html();

          handle_exceptions_before_smartlinking();

  				var i = 0;

          $.each(json.smartLinkCampaigns, function() {
              var numSmartLinksLeftInCampaign = this.maximumSmartLinksPerPage;
                            
              allSmartLinks = $.merge(allSmartLinks, this.smartLinks);

              $.each(this.smartLinks, function() {
                // Skip processing if we have reached our maximum per-campaign limit
                if (numSmartLinksLeftInCampaign <= 0) {
                  return;
                }
                
                var max;
                
                if (this.maximumAppearances < numSmartLinksLeftInCampaign) {
                  max = this.maximumAppearances;
                }
                else {
                  max = numSmartLinksLeftInCampaign;
                }

                var into_smart_link = {
                  smartLink: this,
                  index: i
                };
                
        		    var numSmartLinks = 0;
                numSmartLinks = convert_up_to( max, instances_of(this.keyword), into_smart_link );
                if (numSmartLinks > 0) {
                  $M.smartLink.recordAction(this.id,                    
                                            $M.smartLink.consts.action.instanceCount,
                                            $M.smartLink.context.portalId,
                                            $M.smartLink.context.channelId,
                                            $M.smartLink.context.sourceTypeId,
                                            $M.smartLink.context.sourceId,
                                            numSmartLinks);
                }
                
                //alert("Num left: " + numSmartLinksLeftInCampaign);
                numSmartLinksLeftInCampaign -= numSmartLinks;
                i++;
              });
          });
          
          handle_exceptions_after_smartlinking();

          $(in_content_area_for_portal_id($M.smartLink.context.portalId)).html(workingHtml);

          $('.mediresource-smartLink').each(function() {
            $(this).bind('mousedown', function(event) { $M.smartLink.click(parseInt($(this).attr("smartLinkId")), event); });
          });

          $('.mediresource-smartLink-popUp').each(function() {
              $(this).bind('mouseover', function(event) {
                $M.smartLink.popup.trigger(allSmartLinks[parseInt($(this).attr("smartLinkIndex"))], event);
              });
              $(this).bind('mousedown', function(event) { $M.smartLink.click(allSmartLinks[parseInt($(this).attr("smartLinkIndex"))].id, event); });
          });
          
          $('.mediresource-smartLink-flash').each(function() {
             $(this).bind('mouseover', function(event) {
                $M.smartLink.popup.trigger(allSmartLinks[parseInt($(this).attr("smartLinkIndex"))], event);
             });
             $(this).bind('mousedown', function(event) { $M.smartLink.click(allSmartLinks[parseInt($(this).attr("smartLinkIndex"))].id, event); });
          });
        });
  }
}
});