Click here to Skip to main content
15,891,951 members
Articles / Programming Languages / Javascript

jQuery Based Ajax.Net library

Rate me:
Please Sign up or sign in to vote.
4.91/5 (72 votes)
25 Nov 2009CPOL19 min read 375K   2.4K   351  
jQuery Based Ajax.Net library
(function($) {
	$.popupLayer = null;
	var popMgr = new PopupManager();

	$.fn.Suggest = function(_opt) {
		return this.each(function() {
			var input = $(this).attr("autocomplete", "off");
			var options = $.extend( {
					source	: input.attr("src") || window.location.pathname,
					method	: input.attr("meth"),
					ctxKey  : input.attr("ctx") || "",
					delay	: 250,
					selectClass	: 'selected',
					minchars : 0,
					onSelect : function(inp, data) {
						var f = input.attr("sel");
						(typeof(f) == "undefined") 
							? $(input).val(data[0]) : eval(f+"(inp,data)");
					}
				}, _opt);
			var data	= [];
			var results = null;
			var timeout = 0;	// hold timeout ID for suggestion results to appear	

			// I really hate browser detection, but I don't see any other way
			if ($.browser.mozilla)
				input.keypress(processKey);	// onkeypress repeats arrow keys in Mozilla/Opera
			else
				input.keydown(processKey);		// onkeydown repeats arrow keys in IE/Safari
			
			function getChoices(el, fpDone) {
				timeout = 0;
				if (options.source == '#') {
					eval(options.method+"(el,fpDone)");
					return;
				}
				var ct = options.ctxKey.split(';');
				for (var i = 0; i < ct.length; i++) 
					if (ct[i].substr(0, 1) == "#")
						ct[i] = $get(NCID(input[0], ct[i].substr(1))).value;
				var prm = { prefixText : input.val(), contextKey : ct.join("\n") };
				Sys.Net.WebServiceProxy.invoke(options.source, options.method,
						false, prm, fpDone, null, "");
			}
					
			function processKey(e) {
				// handling up/down/escape requires results to be visible
				// handling enter/tab requires that AND a result to be selected
				if (/^13$|^9$|^27$|^38$|^40$/.test(e.keyCode)) {
					if (!results || results.length == 0)
						return true;
					if (e.preventDefault)	e.preventDefault();
					if (e.stopPropagation)	e.stopPropagation();
					e.cancelBubble = true;
					e.returnValue = false;
					switch(e.keyCode) {
						case 38:			prevRes();		break;	// up
						case 40:			nextRes();		break;	// down
						case 27:			Hide();			break;	//	escape
						case 9:	case 13:	selCurRes();	break;	// tab/enter
					}
					return false;
				}
				if (timeout) 
					clearTimeout(timeout);
				timeout = setTimeout(function() {
						if (input) getChoices(input[0], Show); 
					}, options.delay);
				return true;
			}
			
			function Hide() {
				if (results != null) {
					popMgr.clear();
					if (timeout) 
						clearTimeout(timeout);
					timeout = 0;
					results = null;
				}
			};

			function Show(txt) {
				Hide();
				data = txt.split("\n");
				if (!data || !data.length || !data[0].length) 
					return;
				var html = '<table cellpadding=0 cellspacing=0 border=0 style="font-size:12px;white-space:nowrap;'
						+ 'background: #F2F2F2;border:ridge 3px silver;z-index:99999;cursor:hand;">';
				for (var i = 0; i < data.length; i++) {
					data[i] = data[i].split("\t");
					var tmp = '<tr ix=' + i + '>';
					for (var j = 0; j < data[i].length; j++) 
						tmp += '<td>&nbsp;' + (data[i][j] = data[i][j].trim()) + '&nbsp;</td>';
					html += tmp + '</tr>';
				}
				results = document.createElement('div');
				results.innerHTML = html + '</table>';
				results = $(results).appendTo(popMgr.layer());
				$("td", results).css("white-space", "nowrap");
				popMgr.show(input, results, input, Hide);

				$('tr', results)
					.mouseover(function() {
						$('tr', results).removeClass(options.selectClass);
						$(this).addClass(options.selectClass);
					})
					.click(function(e) {
						selCurRes();
					});
			}
			
			function getCurSel() {
				if (!results || !results.is(':visible'))
					return null;
				var ret = $('tr.' + options.selectClass, results);
				return (ret.length > 0) ? ret : null;
			}
			
			function selCurRes() {
				var curRes = getCurSel();
				Hide();
				if (curRes) {
					var ix = parseInt(curRes.attr("ix"));
					if (ix >= 0 && ix < data.length) {
						options.onSelect(input[0], data[ix]);
						SendEvent('change', input[0]);
					}
				}
			}
			
			function nextRes() {
				var curRes = getCurSel();
				if (!curRes)
					$('tr:first-child', results).addClass(options.selectClass);
				else
					curRes.removeClass(options.selectClass)
						  .next().addClass(options.selectClass);
			}
			
			function prevRes() {
				var curRes = getCurSel();
				if (!curRes)
					$('tr:last-child', results).addClass(options.selectClass);
				else
					curRes.removeClass(options.selectClass)
						  .prev().addClass(options.selectClass);
			}
			this.popup = Show;
			input.Disposable(function() {
				Hide();
				if (input != null && input.length > 0)
					input[0].popup = null;
				data = input = null;
			});
		});
	};
	
	$.fn.Calendar = function(_frmt) {
		return this.each(function(){		
			var input = $(this).attr("autocomplete", "off");
			var MonthNames = Sys.CultureInfo.InvariantCulture.dateTimeFormat.MonthNames;
			var DayNames = Sys.CultureInfo.InvariantCulture.dateTimeFormat.AbbreviatedDayNames;
			var WeekStart = 0;
			var frmt = input.attr("frmt") || _frmt || "MM/dd/yyyy";
			var selectedDate = new Date();
			var clndrHtml = null;
			
			function Date2Str(yy, mm, dd) {
				var d = (typeof yy == "number") ? new Date(yy, mm, dd) : new Date(yy);
				return d.format(frmt);
			};
			
			function Show() {
				if (clndrHtml == null) {
					Draw(input.val());
					input.unbind("mouseup", Show);
					input.bind("keydown", Hide);
				}
			};
			
			function Hide() {
				if (clndrHtml != null) {
					popMgr.clear();
					input.bind("mouseup", Show);
					input.unbind("keydown", Hide);
					clndrHtml = null;
				}
			};
			
			function LostFocus() {
				Hide();
				SendEvent('blur', input[0]);
			}
			function Draw(dd) {
				selectedDate = (typeof(dd) == "string") ? Date.parseLocale(dd, frmt) : dd;
				if (!selectedDate || isNaN(selectedDate))
					selectedDate = new Date();
				dd = selectedDate;
				var curMon = dd.getMonth();
				var curYr  = dd.getFullYear();
				var curDy  = dd.getDate();
				var cmFirst = new Date(curYr, curMon, 1);
				var cmLast  = (new Date(curYr, curMon+1, 0)).getDate();
				var lmLast  = (new Date(curYr, curMon, 0)).getDate();
				popMgr.clear();
				var buf = '<table style="font-size:12px;'
						+ 'background:#F2F2F2;cursor:arrow;white-space:nowrap;'
						+ 'border:ridge 3px silver;z-index:99998;text-align:center;"><thead>'
					+ '<tr><td>&laquo;</td><td colspan=5><select></select><select></select><td>&raquo;</td></tr>'
					+ '<tr><th>' + DayNames.join("</th><th>") + '</th></tr>'
					+ '</thead><tbody><tr>'
				var cn = 0
				for (var i = 0; i < cmFirst.getDay(); i++, cn++)
					buf += "<td style='color:#888888'>" + (lmLast - cmFirst.getDay()+i+1) + "</td>";
				for (var i = 1; i <= cmLast; i++, cn++) {
					if ((cn % 7) == 0)
						buf += "</tr><tr>";
					buf += '<td style="font-weight:bold;';
					if (i == dd.getDate())
						buf += "background-color:#9999ff;"
					buf += '" dd="' + Date2Str(curYr, curMon, i) + '">' + i + '</td>';
				}
				for (i = 1; (cn % 7) != 0; i++, cn++)
					buf += "<td style='color:#888888'>"  + i + "</td>";
				buf += "</tr><tr><td colspan='7' dd='" 
					+ Date2Str(new Date()) + "'>Today</td></tr>";
				buf += '</tbody></table>';
				clndrHtml = document.createElement("div");
				clndrHtml.innerHTML = buf;
				clndrHtml = $(clndrHtml);
				$('thead tr:eq(0) td:eq(0)', clndrHtml).attr("dd", "X").bind("click", function() {
					Draw(new Date(curYr, curMon-1, curDy));
				});
				$('thead tr:eq(0) td:eq(2)', clndrHtml).attr("dd", "X").bind("click", function() {
					Draw(new Date(curYr, curMon+1, curDy));
				});
				var sel = $('select', clndrHtml).bind("change", function() {
						Draw(this.value);
					});
				for (var i = 0; i < MonthNames.length - 1; i++)
					sel[0].options[i] = new Option(MonthNames[i], Date2Str(curYr, i, curDy));
				for (var i = dd.getFullYear() - 5; i < dd.getFullYear() + 5; i++)
					sel[1].options[sel[1].options.length] = new Option(i, Date2Str(i, curMon, curDy));
				sel.val(Date2Str(dd));
				$("td[dd]", clndrHtml)
						.css("cursor", "hand")
						.hover(function() { $(this).addClass("selected"); },
							   function() { $(this).removeClass("selected"); } )
				$("td[dd]", clndrHtml).bind("click", function(event) {
					Hide();
					var stringDate = $(event.target).attr("dd");
					if (input.val() != stringDate) 
						SendEvent('change', input.val(stringDate)[0]);
					input.focus();
					return false;
				});
				
				clndrHtml.appendTo(popMgr.layer());
				popMgr.show(input, clndrHtml, input, LostFocus);
			};
			input.bind("click", Show);
			input.Disposable(function() {
				Hide();
				data = input = null;
			});
		});
	};
	
	$.fn.MultiCheck = function() {
		return this.each(function() {
			var results = null;
			var self = $(this);
			var input = $("input", this);
			var text = $("span:eq(0)", this);
			var chkVal = self.attr('ChkVal').split(';');
			if (!chkVal || !chkVal.length || !chkVal[0].length) 
				return;
			var opts = [], data = [];
			for (var i = 0; i < chkVal.length; i++) {
				if (!chkVal[i].length)
					continue;
				var nv = (chkVal[i] + "=" + chkVal[i]).split('=');
				nv[0] = nv[0].trim().toUpperCase(); nv[1] = nv[1].trim(); 
				data[data.length] = nv;
				opts[nv[0]] = nv[1];
			}
			var rows = parseInt(self.attr('Rows')) 
					|| Math.ceil(data.length / (parseInt(self.attr('Cols') || 99999)) )
					|| 1;
			var chkType = self.attr('radio') ? 'radio' : 'checkbox';
			
			input.val($.map(input.val().toUpperCase().split(','), 
							function(a) { return opts[a] ? a : null }
				).join(','));
			
			function Hide() {
				if (results != null) {
					popMgr.clear();
					results = null;
				}
			};

			function Show() {
				Hide();
				var html = '<table cellpadding=0 cellspacing=0 border=0 style="font-size:12px;white-space:nowrap;'
						+ 'background: #F2F2F2;border:ridge 3px silver;z-index:99999;"><tr><td valign=top>';
				for (var i = 0; i < data.length; i++) {
					var nv = data[i];
					if (i > 0) {
						if (rows == 1) 
							html += '&nbsp;';
						else if (rows > 1 && (i % rows) == 0)
							html += "</td><td valign=top>";
						else 
							html += "<br/>";
					}
					if (nv[0].startsWith('-') && nv[0].endsWith('-') 
					&& nv[0].length > 1 && nv[0] == nv[1].toUpperCase()) {
						var b = nv[1].substr(1, nv[1].length - 2);
						html += (b == "") ? "<hr/>" : b.bold();
					}
					else 
						html += '<input type='+chkType +' name='+self[0].id+'_mc'
							 +' value="'+nv[0]+'"/>'+nv[1];
				}
				results = document.createElement('div');
				results.innerHTML = html + '</td></tr></table>';
				results = $(results).appendTo(popMgr.layer());
				
				var sel  = ',' + input.val() + ',';
				var jqe = $("input[type=" + chkType + "]", results);
				jqe.each(function() {
					if (this.value.length > 0 && sel.indexOf(this.value) >= 0)
						this.checked = true;
				}).click(function() {
					input.val($.map(jqe, function(o, i) { 
							return o.checked ? o.value : null; 
						}).join(','));
					text.text($.map(jqe, function(o, i) { 
							return o.checked ? opts[o.value] : null; 
						}).join(';') || self.attr('mark') || '...')
					if (self.attr('onchange'))
						eval(self.attr('onchange'));
					if (chkType == 'radio')
						Hide();
				});
				popMgr.show(self, results, self, Hide);
			}
			
			self.bind("click", Show).Disposable(function() {
				Hide();
				data = self = text = input = null;
			});
		});
	};
})(jQuery);

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
http://www.GaspMobileGames.com
United States United States
Writing code since 1987 using whatever language/environment you can imagine. Recently got into the mobile games. Feel free to check them out at http://www.GaspMobileGames.com

Comments and Discussions