﻿$(function() {
	//Dynamically created content
	$("body")
		.prepend("<div id=\"ToastMsgWrapper\"><div id=\"ToastContent\"><span id=\"ToastMsg\"></span></div></div>" +
				 "<div id=\"ScreenOverlay\"></div><div id=\"PopupWin\"><a class=\"close\" onclick=\"return false\" href=\"javascript:void(0);\" title=\"Close Window\"></a></div>");
	$("#PopupWin .close, #PopupWin .closeLink").live("click",function() {closePopupWin();});

	//Programmatic Classes
	$(".GhostText").live("focus", function() {
	    $.data(this,"DefaultValue",this.value);
	    $(this).removeClass("GhostText").addClass("GhostTextFocused").val("");
	});
    $(".GhostTextFocused").live("blur", function() {
        if(this.value=="") {
            $(this).addClass("GhostText").removeClass("GhostTextFocused").val($.data(this,"DefaultValue"));
        }
    });
	$(".NumericOnly").live("keypress", function(event) {var keyCode=event.keyCode;if ((keyCode>31 && keyCode<48) || keyCode>57) {event.preventDefault();}});
	$(".AutoTab")
		.live("keyup", function(event) {
			if(this.form==null) {alert("Control must be inside a <form> for AutoTab");return;};
			var keyCode=event.keyCode, filter = [0,8,9,16,17,18,37,38,39,40,46];
			if(this.value.length==this.maxLength && !containsElement(filter,keyCode)) {
				for(i=0; i<this.form.length; i++) {if(this.form[i]==this) {this.form[i+1].focus();break;};};
			}
		});

	//General shortcut keys
	$("#PopupWin").keyup(function(e) {
		if(e.which==27) {closePopupWin();} //escape key
	});
});

/* .enable([selector]) & .disable([selector])
	if [selector] is provided, decendent elements matching that selector are also enabled/disabled
	if not, only the provided element is disabled/enabled */
jQuery.fn.disable = function(selector) {
	if( selector ) this.find(selector).attr("disabled", true);
	return this.attr("disabled", true);
};
jQuery.fn.enable = function(selector) {
	if( selector ) this.find(selector).attr("disabled", false);
	return this.attr("disabled", false);
};
jQuery.fn.isenabled = function() {
	return !this.first().attr("disabled");
}

function showPopupWin() {
	$("#PopupWin, #ScreenOverlay").fadeIn();
	setFocusPopupWin();
}

function setFocusPopupWin() {
	/*setFocusPopupWin() is seperate function so it may be called if the PopupWin is shown
	  then content loaded via AJAX, then focus needs set after content filled */
	var firstCtl = $("#PopupWin").find("button,input:text,textarea,select").first();
	if(firstCtl==null) {
		$("#PopupWin").focus();
	} else {
		firstCtl.focus();
	}	
}
function closePopupWin() {
	$("#PopupWin, #ScreenOverlay").fadeOut("fast");
}

function ToastMessage(msg, duration) {
	$("#ToastMsg").html(msg);
	if(duration==null || duration==0) {
		$("#ToastMsgWrapper").fadeIn()
	} else {
		$("#ToastMsgWrapper").fadeIn().delay(duration).fadeOut()
	};
}

function toggleCheck(id) {
	var chk = document.getElementById(id);
	chk.checked = !chk.checked;
}
