function loadfunction(){

    var modalWindowHeight = 385;
    
    // Resize modal window
    // Normally set as querystring parameters
    $('#TB_ajaxContent').css("height", modalWindowHeight + "px");
	
    // Form validation rules
    $("#emailForm").validate(
    {
        rules :{
            
             recipientName: {
                
                required: function(element) {
                    
                    // Only required if no recipients have been added already
                    if($("#emailList").size() > 0)
                       return ($("#emailList")[0].childElementCount <= 0 ? true : false);
                    else
                        return true;

                }

            },
            
            toEmail: {
                
                required: function(element) {

                    // Only required if the recipient name has been populated
                        return jQuery.trim($("input#recipientName").val()).length > 0;
                }

      
            }
        }
    
    });
    
     // global variables doclink and header set from function emailAFriend
	 var refInput = document.getElementById("referrer");
	 //var url = (window.opener) ? window.opener.doclink : "http://www.newton.co.uk" ;
	 var url;
	 url = doclink;
	 refInput.value=url;
	 
	 $("#emailafriend .headingTitle").text(header);
	 $('#emailForm #referrer').val(url);
    // $('#toEmail').attr("disabled", true); 
     
     // Attach events
     
     // Submit click
	 $("#submitEAF").click(function(event){
         
         $("p.errorMessage").hide();
         $(".fieldError").removeClass("fieldError");
         if ($("#emailForm").valid()) {
	   $("input#toEmail").rules("add", {email:true});
	   $("input#ccEmail").rules("add", {email:true});
	   if ($("#emailForm").valid()) {
         	callEmailService();
           }
	   $("input#toEmail").rules("remove", "email");
	   $("input#ccEmail").rules("remove", "email");
         }
         
         return false;
	 });
	 
     // Reset click
	 $("#resetEAF").click(function(event){
         event.preventDefault();
         $("#emailForm .fieldError").removeClass('fieldError').empty();
         document.getElementById('emailForm').reset();
         $("#emailList > LI").each(function() {
             $(this).remove();
         });
         $('.errorMessage').hide();
         $('#emailForm #referrer').val(url);
        // Refresh the wrapper and status text
        $("#recipientsWrapper").trigger('refresh');
        $("#numOfEmailsText").trigger('refresh');
         $('#TB_ajaxContent').css("height", modalWindowHeight + "px");
	 });
	 
    
     
     // Re-validate toEmail field

//     $("input#toEmail").keyup(function() {
//     	$(this).rules("remove", "email");
//	if (jQuery.trim($("input#recipientName").val()).length > 0) {
//	    $(this).rules("add", {email:true});
//            $(this).valid();
//         }
//
//     });
//
//   $("input#recipientName").keyup(function() {
//         var emailEl = $("input#toEmail");
//         emailEl.rules("remove", "email");
//	if (jQuery.trim($("input#recipientName").val()).length > 0) {
//	    emailEl.rules("add", {email:true});
//          }
//
//     });
     
     // Re-validate and prevent propagation of event if validation fails
     // This must be the first event handler on the chain
     $("#addRecipient").click(function(event) {
         $("input#recipientName").valid();
         if ($("input#toEmail").valid()) {
             $("input#toEmail").rules("add", {email:true});
             if (!$("input#toEmail").valid()) {
               event.stopImmediatePropagation();
              }
             $("input#toEmail").rules("remove", "email");
         } else {
         	event.stopImmediatePropagation();
         }
         
     });
     
     // Hide recipient lists if it is empty when refreshed
     $("#recipientsWrapper").bind('refresh', function(event) {
        
        var recipientCount = $("#emailList > LI").size();

        if(recipientCount == 0)
            $(this).hide();
        else
             $(this).show();

     });
     

     // Add Recipient click
     $("#addRecipient").click(function() {
         
         var totalNoOfRecipients = $(".recipient").size();
         var recipients = null;
         
         // If no recipients container exists proceed to setup
         if($("#recipients").size() == 0) {
             
             	$("<ul id='recipients' class='treeview'><li><span id='numOfEmailsText'>Emails</span><ul id='emailList'></ul></li></ul>").appendTo("#recipientListContainer");

                // Initialise treeview, collapsed by default
                $("#recipients").treeview({collapsed: true});
                
                // Events
                // Collapse tree by simulating a click on hitarea
                // Ideally this should a 'controller' for the treeview
                $("#recipientsWrapper").mouseleave( function(event) {
                    
                    $("DIV.collapsable-hitarea").click();
                });

                // Change the status of the recipient count
                $("#numOfEmailsText").bind('refresh', function(event) {
                    
                    var emailCount = $("#emailList > LI").size();

                    var status = "";

                    if(emailCount == 0) {
                        status = "No email added.";
                    } else
                         status = emailCount + " email(s) added.";

                     $(this).text(status).fadeIn(30).fadeOut(1000).fadeIn(30);

                });
                
                // Capture a click event within the list container and if the event source originates
                // from an A link with class recipientNameEmail remove it from the list of recipients
                $("#emailList").click(function(event) {
                   
                    if(event.type == "click") {
                        
                        // Confirm that it is a valid link from class name
                        if($(event.target.parentNode).hasClass('recipientNameEmail')) {
                            
                            // Do not follow the link
                            event.preventDefault();
                            $(event.target.parentNode).remove();
                            
                            // Refresh the wrapper and status text
                            $("#recipientsWrapper").trigger('refresh');
                            $("#numOfEmailsText").trigger('refresh');
                        }
                    }
                    
                });
                        
         }

        // An email recipient
        var branches = $("<li class='recipientNameEmail'><span>" + $("#recipientName").val() + " (" + $("#toEmail").val()  +")</span> [<a href=''>remove</a>]</li>").appendTo("#emailList");

        // Add it to the list
        $("#recipients").treeview({
            add: branches
        });

        // Reset the fields
         $("input#recipientName").val('');
         $("input#toEmail").val('');
        
         // Refresh the wrapper and status text
        $("#recipientsWrapper").trigger('refresh');
        $("#numOfEmailsText").trigger('refresh');
        $("#recipientsWrapper").trigger('mouseleave');
 
     });
     
	 } // End function loadfunction
     
     
     // Build all the necessary hidden fields from container.
     // But, remove old ones first
     var buildFields = function () {

         var recipientListContainer = $("#recipientListContainer");
         var recipientCounter = 1;
         
         // Remove all hidden fields
         $("#recipientListContainer > INPUT").each(function() {
             
             $(this).remove();
             
         });
         
         // Iterate recipient list and create corresponding hidden fields and append to the container
         $("#emailList > LI > SPAN").each(function() {
             
            var recipient = $(this).text();

            var re = /(.[^(]*)\((.[^)]*)\).*/;
            
            var recipientParts = recipient.match(re);
            
            var recipientName = $("<input/>");
            recipientName.attr("type", "hidden");
            recipientName.attr("id", 'recipientName' + recipientCounter);
            recipientName.attr("value", jQuery.trim(recipientParts[1]));

            var recipientEmail = $("<input/>");
            recipientEmail.attr("type", "hidden");
            recipientEmail.attr("id", 'toEmail' + recipientCounter);
            recipientEmail.attr("value", jQuery.trim(recipientParts[2]));


             recipientName.appendTo(recipientListContainer);
             recipientEmail.appendTo(recipientListContainer);
         
             recipientCounter++;
             
         });

     }
     
     
	 function failureAlert(jsondata){
         alert("An error occurred, the server may be down. Please try again later.");
	 }
     
	 var callEmailService = function(){
     
     // Rebuild hidden fields
     buildFields();
     
     // Collect all input fields
     var parameters = $('input').clone();

	var getEmailService = function() {

        var host = "";
        var path = "/ses/email.do";
        
		var hostname = window.location.hostname;
		if (hostname.indexOf("localhost") > -1  ) {
			host = "http://localhost:9080";
		} else if (hostname.indexOf("ebd01") > -1) {
			host = "http://ebd02.lon.mellonbank.com:9082";
		} else if (hostname.indexOf("test.mellon") > -1 ) {
			host = "http://mebss.test.mellon.com";
		} else if (hostname.indexOf("sn84") > -1 || hostname.indexOf("qa.mellon") > -1 ) {
			host = "http://mebss.qa.mellon.com";
		} else if (hostname.indexOf("sn83") > -1 || hostname.indexOf(".co.uk") > -1 ) {
			host = "http://ebusiness.melloninstitutional.com";
		} else {
			host = "http://ebusiness.melloninstitutional.com";
		}
        
       
		return host + path;
		
	};
    
     //new JSONP("http://mebss.test.mellon.com/ses/email.do"
	// new JSONP("http://localhost:9080/ses/email.do", //"http://ebd02.lon.mellonbank.com:9082/ses/email.do",  // "http://ebusiness.melloninstitutional.com/ses/email.do",//"http://mebss.qa.mellon.com/ses/email.do",//"http://localhost:9080/ses/email.do",//"http://mi0-mebss-tpc.bnymellon.com/ses/email.do",
	 new JSONP(getEmailService(),
     {
	 callbackParamName: 'jsoncallback',
	 onSuccess: processJson,
	 onFailure: failureAlert,
	 timeout: 5000,
	 dataType: "json",
	 paramsIsArray: true,
	 params: parameters
	 });

	 };
	 
	 function processJson(data){
	 var jsonObj = data;
	 var errors = jsonObj.errorMap;
	 var errorsMessage = jsonObj.errorStr;
	 $.each(errors, function(errField, errMessage){
	 $("#" + errField).addClass("fieldError");
	 $("#" + errField + " + p").text(errMessage).show();
	 $('#TB_ajaxContent').css("height", modalWindowHeight + "px");
	 });
	 if (errorsMessage == "No errors") {
	 $('#emailafriend > p').hide();
	 $('#emailForm').hide();
	 $('.headingTitle').hide();
	 $('#confirmationMessage').show();
	 }
	 }
	



