
(function($) {
		  
	var kjmodal;
	
	$.openModal = function(settings) {
		settings = jQuery.extend({
			width: "auto",					// width of the modal
			height: "auto",					// height of the modal
			opacity: "0.8",					// opacity of the overlay layer
			overlayImage: "",				// background image of the overlay
			overlayColor: "#000",			// background color of the overlay
			modalColor: "#fff",				// background color of the modal
			overlayShowSpeed: 500,			// fade in speed of the overlay layer / modal
			modalShowSpeed: 400,			// fade in speed of the modal object / modal
			target: "",						// target html element identifier to be used for the modal's content
			url: "",						// target url to be loaded using ajax for the modal's content
			parameters: {},					// any parameters to be passed for ajax loads
			cache: false,					// ajax content cache
			onShow: function() {},			// function to be executed when a modal is to be displayed
			onComplete: function() {},		// function to be executed when modal is fully displayed 
			onSuccess: function() {},		// function to be executed upon AJAX data loaded completely
			onError: function() {}			// function to be executed upon ajax failure
		}, settings);
		// execute code when a modal is to be displayed
		settings.onShow();
		// assign the settings for the modal; to be used in the sizing of the overlay
		kjmodal = settings;
		// verify a valid data source for the modal
		if (validateData(settings)) {
			// hack: hide the select boxes from ie6 users
			hideSelects();
			// load the modal's content 
			loadModalContent(settings);
		}
		return this;
	}	// $.openModal()
	
	$.closeModal = function(settings) {
		settings = jQuery.extend({
			overlayHideSpeed: 500,		// fade out speed of the ovelay layer / modal
			modalHideSpeed: 400,		// fade out speed of the modal object / modal
			onClose: function() {},		// function to be executed before the modal is closed EX. function() { alert("It is loaded"); }
			onHide: function() {}		// function to be executed after the modal has been closed
		}, settings);

		// execute code before the modal is closed
		settings.onClose();
		// fade out the modal box
		$("#kjModal").fadeOut(settings.modalHideSpeed, function(){
			// remove the modal from the page's html												   
			$("#kjModal").remove();
			// fade out the overlay layer
			$("#kjOverlay").fadeOut(settings.overlayHideSpeed, function(){
				// remove the overlay from the page's html
				$("#kjOverlay").remove();
				// hack: show the select boxes for ie6 users
				showSelects();
				// execute code after the modal is removed from the html
				settings.onHide();
			});
	   	});
		return this;
	}	// $.closeModal()
	
	function validateData(modalObject) {
		var returnValue = false;
		// if there is valid data to populate the modal, return true
		if ((modalObject.target != "" && $(modalObject.target).length) || (modalObject.url != "")){
			returnValue = true;
		}
		return returnValue;
	}	//validateData()

	function setOverlayLayerSize() {
		var scrollTop, overlayHeight, overlayWidth;
		// get the scroll top for the current page position
		scrollTop = (document.documentElement.scrollTop || document.body.scrollTop);
		// get the width of the viewport
		//overlayWidth = $(document.body).outerWidth(true)
		overlayWidth = $(document).width();
		// determine if the height + top padding is greater then the document's height + scroll top, assign the overlay's height to the summation
		if ((kjmodal != null && kjmodal.height != null) && (parseInt(kjmodal.height)+20) > ($(document).height()+scrollTop)) {
			overlayHeight = parseInt(kjmodal.height) + 40 + scrollTop;
		// business as usual, assign the height of the ovelay layer to the height of the document
		} else {
			overlayHeight = $(document).height();
		}
		// set the new height of the overlay layer
		$('#kjOverlay').height(overlayHeight + "px");
		// set the new width of the overlay layer
		$('#kjOverlay').width(overlayWidth + "px");
	}	// setOverlayLayerSize()
	
	function showOverlayLayer(modalObject, modalContent) {
		// make sure that an overlay layer does not already exist in the html
		if (!($("#kjOverlay").length)) {
			// inject the overlay layer into the html
			$("body").append("<div id='kjOverlay' style='z-index: 9998;' ><!-- --></div>");
			// set the attributes of the new overlay layer
			$("#kjOverlay").css({
				position: "absolute",
				zIndex:"9998",
				left: "0",
				top: "0",
				opacity: modalObject.opacity,
				display: "none"
			});
			// set the proper display mode of the overlay layer
			if (modalObject.overlayImage != "") {
				// set the backgroun image of the overlay layer
				$("#kjOverlay").css({ backgroundImage: "url(" + modalObject.overlayImage + ")" });
			} else {
				// set the background color of the overlay layer
				$("#kjOverlay").css({ backgroundColor: modalObject.overlayColor });
			}
			// set the size of the overlay layer
			setOverlayLayerSize();
			// fade in the overlay layer 
			$("#kjOverlay").fadeIn(modalObject.overlayShowSpeed, function(){
				showModal(modalObject, modalContent)
			});
			// assign a click event to the overlay layer, allowing the user to exit the layer with a click
			//$("#kjOverlay").click(function() {
			//	$.closeModal();
			//});
		}
		// set the position of the modal
		setModalPosition(modalObject);
	}	// showOverlayLayer()
	
	function setModalPosition() {
		var leftPosition, topPosition;
		// find the left position of the modal
		if ($("#kjModal").width() < $(window).width()) {
		// if the modal's width is less than the viewport, calculate the left position attribute
			leftPosition = (document.documentElement.offsetWidth - $("#kjModal").width()) / 2;
		} else {
		// if the modal's width is greater than or equal to the viewport, calculate the left position attribute
			leftPosition = document.documentElement.scrollLeft + 20;
		}
		// find the top position of the modal
		if ($("#kjModal").height() < $(window).height()) {
		// if the modal's height is less than the viewport, calculate the top position attribute
			topPosition = (document.documentElement.scrollTop || document.body.scrollTop) + ($(window).height() - $("#kjModal").height()) / 2;
		} else {
		// if the modal's height is greater than or equal to the viewport, calculate the top position attribute
			topPosition = (document.documentElement.scrollTop || document.body.scrollTop) + 20;
		}
		// assign the calculated values to an array
		var positions = {
			left: leftPosition + "px",
			top: topPosition + "px"
		};
		// aniimate the modal to this position
		$("#kjModal").stop().animate(positions, 200);
	}	// setModalPosition()
	
	function loadModalContent(modalObject) {
		// load the content for the modal
		if (modalObject.target != "") {
			// show the overlay layer
            showOverlayLayer(modalObject, $(modalObject.target).html());
        } else {
			// show the modal with content loaded from a url using ajax
			// execute the error code upon ajax failure
            $.ajax({
                url: modalObject.url,
                data: modalObject.parameters,
				cache: modalObject.cache,
                dataType: "html",
                method: "GET",
                success: function(data) {
					modalObject.onSuccess();
                    showOverlayLayer(modalObject, data);
                }
				//,error: modalObject.onError()
            });
		}
	}	// loadModalContent(object)

    function showModal(modalObject, modalContent) {
		// inject the modal html into the html body
		$("body").append("<div id='kjModal' style='z-index: 9998;'><!-- --></div>");
		// set the attributes of the new modal element
		$("#kjModal").css({
			position: "absolute",
			zIndex: "9999",
			left: "0",
			top: "0",
			width: modalObject.width,
			height: modalObject.height,
			backgroundColor: modalObject.modalColor,
			display: "none"
		});
		// populate the html of the modal element
		$("#kjModal").html(modalContent);
		// set the position of the modal element
		setModalPosition();
		// fade in the modal element
		$("#kjModal").fadeIn(modalObject.modalShowSpeed, function(){
			// execute the code for the overlay/modal display
			modalObject.onComplete();
		});
	}	// showModal(object,string)

	function hideSelects() {
		// convert all drop downs of the page to a span
		// neglect any drop downs with the ".no-replace" class
		$("select").not(".no-replace").each(function() {
			$(this)
				.after("<span class='replacement'></span>").next()
				.addClass($(this).attr('class'))
				.attr('id', $(this).attr('id'))
				.html($(this).html())
				.width($(this).width())
				.height($(this).height())
				.prev().addClass("hidden-dropdown").css("display","none");
		});
	}	// HideDropDowns()

	function showSelects() {
		// remove all replacement drop downs from the html
		$(".replacement").each(function() {
			$(this).remove();
		});
		// convert all drop downs back to normal
		$(".hidden-dropdown").each(function() {
			$(this).removeClass("hidden-dropdown").css("display", "block");
		});
	}	// ShowDropDowns()

	$(window).resize(function(){
		// set the height and width of the overlay layer
		setOverlayLayerSize();
		// set the top and left position of the modal element
		setModalPosition();
	});
	
})(jQuery);

