    
	$(document).ready(function() {
		
	   // loop through all nonmodal forms on the page
	   
	   $('.nonmodalform').each(function() {
	   	    
			var formId = $(this).attr('id');
			
			originalForm = $('#wrapper_'+formId).html();
           $('#'+formId).css({zIndex:'4'});
           
           if($('#'+formId).hasClass('nmf_pos')) {
              if($('#'+formId).hasClass('nmfpos_below')) {               
                  // position form inside button
                 $('#'+formId).wrap('<div id="formwrapper_'+formId+'"></div>');
                 var formHTML = $('#formwrapper_'+formId).html();
                 $('.'+formId).wrap('<div id="wrapper_'+formId+'" class="nmf_form_button_wrapper"></div>');
                 $('#wrapper_'+formId).append(formHTML)
                 $('#'+formId).css({position:'absolute',top:'0px',left:'0px'});
                 $('#formwrapper_'+formId).remove();
              } else {
                $('#'+formId).centerInClient();
              }
           } else {
               $('#'+formId).centerInClient();
           }
			
	        if($('#'+formId).hasClass('nmf_draggable')) {
                $('#'+formId).draggable({ containment: 'body' }).css({'cursor':'move'});
            }
            var closeMsgLeft = $('.nonmodalform').width()-46;
	        if($('#'+formId).hasClass('nmf_click')) {
			   $('#'+formId).prepend("<small style='font-size:11px;position:absolute;top:4px;left:"+closeMsgLeft+"px'>Close</small><div class='nmf_close' style='float:right;cursor:pointer'>Close</div>");
	           $('#'+formId).hide();
	           // use form id as class name for click event
			   $('.'+formId).click(function() {
			   	     
					 if($('#'+formId).hasClass('nmf_effect')) {
					 	if($('#'+formId).hasClass('nmf_slideDown')) {
							$('.nmf_form_button_wrapper').css({zIndex:'1'});
							$('.nonmodalform').css({display:'none'});
							$('#wrapper_'+formId).css({'z-index':10})
							
							$('#'+formId).slideDown(500);
						} else if($('#'+formId).hasClass('nmf_overlay')) {
							$('#nmf_overlay').remove();
							$('body').prepend('<div id="nmf_overlay"></div>');
							$('#nmf_overlay').css({
                                    position:'absolute',
									top:'0',
									left:'0',
									height:$(document).height(),
									width:$(document).width(),
									opacity:'0.6',
									//background:'#4F4F4F',
									background: '#444444',
									zIndex:'3'});
							$('#'+formId).centerInClient();
							//$('#'+formId).css({position:'fixed'})
							$('#'+formId).fadeIn(500);
							positionOpaqueBox($('#'+formId));
						} else {
							$('#wrapper_'+formId).css({'z-index':10})
							$('#'+formId).show().css({'z-index':10});
							positionOpaqueBox($('#'+formId));
						}
					 } else {
						$('#wrapper_'+formId).css({'z-index':10})
						 positionOpaqueBox($('#'+formId));
			   	         $('#'+formId).show();
				     }
					 
					 return false;
			   })	            
	        }
	        // hover
	        if($('#'+formId).hasClass('nmf_onhover')) {
	            $('#'+formId).hide();
	            $('#'+formId).prepend("<div class='nmf_close' style='float:right;cursor:pointer'>Close</div>");

	
	            $('.'+formId).hover(
	                 function() {
	                    $('#'+formId).show();
	                 },
	                 function() {
	                    //$('.nonmodalform').hide();
	                 }
	            )  
	        }

		    // close button
	        $('.nmf_close').click(function() {
	          $('#'+formId).hide();
			  if($('#nmf_overlay').length) {
			  	$('#nmf_overlay').remove();
			  }
			  removeOpaqueBox('#'+formId)
			  $('#wrapper_'+formId).css({'z-index':0})
	          resetErrors($('#'+formId));
	       }); 
	       
		   attachFormValidator($('#'+formId));
		   
	   });
    });
	
	function removeOpaqueBox(element) {
        var box = $(element).prev('.opaqueBox');
		$(box).hide();
	}
	
	function positionOpaqueBox(element){
	   var height = $(element).height();
	   var width = $(element).width();
	   var offset = $(element).offset();
	   var box = $(element).prev('.opaqueBox');
	   
	   $(box).css({
	   	   position:'absolute',
		   width:width,
		   height:height,
		   top:offset.top-10 +'px',
		   left:offset.left-10 +'px',
		   background:'#474747',
		   opacity:0.2,
		   padding:'10px'
	   });
	   
	   $(box).show();
	}
	
    jQuery.fn.center = function () {
        this.css("position","absolute");
        this.css("top", ( $(window).height() - this.height()+10 ) / 2+$(window).scrollTop() + "px");
        this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
        return this;
    }
	
	$.fn.centerInClient = function(options) {
    /// <summary>Centers the selected items in the browser window. Takes into account scroll position.
    /// Ideally the selected set should only match a single element.
    /// </summary>    
    /// <param name="fn" type="Function">Optional function called when centering is complete. Passed DOM element as parameter</param>    
    /// <param name="forceAbsolute" type="Boolean">if true forces the element to be removed from the document flow 
    ///  and attached to the body element to ensure proper absolute positioning. 
    /// Be aware that this may cause ID hierachy for CSS styles to be affected.
    /// </param>
    /// <returns type="jQuery" />
    var opt = { forceAbsolute: false,
                container: window,    // selector of element to center in
                completeHandler: null
              };
    $.extend(opt, options);
   
    return this.each(function(i) {
        var el = $(this);
        var jWin = $(opt.container);
        var isWin = opt.container == window;

        // force to the top of document to ENSURE that 
        // document absolute positioning is available
        if (opt.forceAbsolute) {
            if (isWin)
                el.remove().appendTo("body");
            else
                el.remove().appendTo(jWin.get(0));
        }

        // have to make absolute
        el.css("position", "absolute");

        // height is off a bit so fudge it
        var heightFudge = isWin ? 2.0 : 1.8;

        var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2;
        var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2;

        el.css("left", x + jWin.scrollLeft());
        el.css("top", y + jWin.scrollTop());

        // if specified make callback and pass element
        if (opt.completeHandler)
            opt.completeHandler(this);
    });
}

/**
 *  Javascript Form Validator
 *  
 *  This script does an ajax post to the forms action script
 *  and uses the server side validation as client side validation.
 *  This allows greater flexibility on the front end for presenting
 *  errors to the end user.
 *
 *  Requirements:
 *  The form that require this type of validation must have a class of ajaxValidator.
 *  The PHP script must expect a $_POST variable called "ajaxRequest". It must
 *  also do all of its form validation at the top of the script and must not
 *  send any data to the browser, during the validation section. The script
 *  must send back a json encoded object, which should either contain a success
 *  response or the error messages and the corresponding fields that have errored
 *
 * If javascript has been disabled by the browser or is not available then the
 * server side validation will take place as normal.
 *
 *  Author: Dave Clarke <dave@djcnet.co.uk>
 *  Date:   22nd February 2009
 *  
 *  Amended on 23/11/2009
 *  Added specific code for Staiflift Suppliers Ltd
 *
 */

    var originalForm;
    /**
     *  Reset Errors
     *
     *  This function removes any errors already presented to the user
     *
     */
    function resetErrors(form) {
        $('p.nmf_errormsg',form).remove();
        $('.nmf_globalerror',form).remove();
        $('li',form).each(function() {
            $(this).removeClass('ajaxFormError');
        });
    }

 /**
     *  Parse Response
     *
     *  This function checks the json response, and if it finds a successfull
     *  repsone it returns true, otherwise it loops over the response, and adds
     *  the frontend presentation to highlight the errors to the end user
     */
    function parseResponse(response,form) {

        var valid = 1;
        if(!response.success) {
            for(field in response) {
                var element = $('[name="'+field+'"]:input',form).parents('li:nth(0)');
                $('.nmf_globalerror',form).remove();
                $('.nmf_formheader',form).after("<div class='nmf_globalerror'><p>You have one or more errors. Please see below.</p></div>")
                $(element,form).addClass('ajaxFormError')
                if(typeof response[field] == "object") {
                    //$(element).append("<p class='nmf_errormsg'>"+response[field].msg+"</p>");
                } else {
                    //$(element).append("<p class='nmf_errormsg'>"+response[field]+"</p>");
                }
                valid = 0;
            }
        }

        return valid;
    }

 /**
     *  Validate
     *
     *  This function calls resetErrors and removes any errors that were
     *  previously shown. It then does a synchronous AJAX post, and blocks the
     *  browser which waits for a response before continuing.
     *
     *  It then sends the received response to parseResponse and based on the
     *  return injects a class onto the form.
     */
    function validate(querydata,form) {

        resetErrors(form);
        $.ajax({
            async:      false,
            type:       "POST",
            url:        $('form.ajaxValidator',form).attr('action'), //"/diary/add-letview-appointment.php",
            cache:      false,
            data:       querydata+"isAjaxRequest=1",
            dataType:   "json",
            success:    function(response) {
                            //eval("var response="+r);
                            if(parseResponse(response,form) == 1) {
                                $(form).addClass("valid");
								$('fieldset',form).fadeOut(500, function() {
									$('fieldset',form).html(response.content);
									$(this).fadeIn(500);
								});
								
                            } else {
                                $(form).removeClass("valid");
                            }
            }
        });
    }

    /**
     *  Attach Form Validator
     *
     *  This function attaches the click event listener to the submit button
     *  of the form. Once clicked it gathers the data from the form and passes
     *  it to validate. It then waits for validate to finish, and listen on the
     *  form for a class called valid.
     */
    function attachFormValidator(form) {
        $('.nmf_submit',form).click(function(){
			var loadingHtml = '<div class="loading" style="position:absolute;left:55px;top:100px;border:1px solid #8F8F8F;padding:20px;background:#CFCFCF;color:#6F6F6F"><p>Processing form. Please wait...</p><img src="images/loading.gif" /></div>';
			$(form).prepend(loadingHtml);
            var querydata = "";
            // get all form input fields and values
            $(':input',form).each(function(i) {
                querydata = querydata + $(this).attr("name") + "=" + $(this).val() + "&";
            });
            validate(querydata,form);
			$('.loading',form).fadeOut(1500);
			$('.loading',form).remove();
            if(!$(form).hasClass('valid')) {
               
            }
			
			return false;
        });
    }
