
/* ------ start - document.ready ------ */
$(document).ready(function() {
	// force vertical scroll-bar
	$("html").css("overflow-y","scroll");
	
	var ieVersion = getInternetExplorerVersion();
	var isIE = true;
	if(ieVersion === -1) {
		isIE = false;	
	}
	// call for tooltip function
	tooltip("tooltip");
	tooltip("tooltip-todo");
	
	if(typeof (lang) == "undefined") {
		lang = "en";	
	}
	
	// call fancybox function
	openFull();
	
	if ($("#systemMessages.fadeIn li").length > 0) {
		var elem = $("#systemMessages.fadeIn");
		fadeNotice(elem);	
	}
	
	
	//if first time help is needed:
	/*
	if (typeof (help) != "undefined" && lang != 'en' && lang != 'fi') {
	
		if (help == "first_time") {
			$("a#autoHelp").fancybox({
				'showNavArrows' : true,
				'showCloseButton' : true,
				'overlayOpacity' : 0.8,
				'titleShow' : true,
				'titleFormat' : formatTitle,
				'titlePosition' : 'inside'
			});
			$("a#autoHelp").trigger('click');
		}
	};
	*/
	// Help video
	//if(lang == 'en' || lang == 'fi') {
		$("#continueToFeed [name='continueToFeed'], #firstSignup").click(function() {
			
			window.open(base_url+'home/quickhelp', 'quickhelp', 'width=860, height=760, scrollbars=1');
			var data = {
				continueToFeed : true	
			};
			//post('dashboard/addmoremembers', data);
			window.opener.location = base_url+'home/';
			return false;
		});
	
	
		$("#autoHelp").click(function() {
			window.open(base_url+'home/quickhelp', 'quickhelp', 'width=860, height=760, scrollbars=1');	
			return false;
		});
	/*}
	else {
		//call helpwindow function
		helpWindow();	
	}*/
	
	
	
	$("#lastReadHolder").val('0');
	commentOpen = false; //so that we can stop feed refreshing when comment typebox is open
	
	
	
	// close system-message
	$("ul#systemMessages li a").live("click", function() {
		fadeOutRemove("ul#systemMessages");
		return false;
	});	

	
	// Kidfinder map zooming
	$("a.zoomMap").fancybox({
		"transitionIn" : "none",
		"transitionOut" : "none",
		"hideOnContentClick" : false,
		"autoScale" : false,
		"showNavArrows" : false,
		"height" : 520,
		"width" :  520,
		"overlayShow"	: false,
		"overlayOpacity" : 0
		});
	

	// Past month arrow
	$("#past-month").live("click", function() {
		if(typeof(daysback) == "undefined") {
			daysback = 31;	
		}
		jQthis = $(this);
		jQthis.addClass('hidden');
		jQthis.prev().removeClass('hidden');
		var pastOffset = $("#past-offset").text();
		post("ajax/stream_get", {
			offset	: pastOffset,
			daysback: daysback
		}, function(data) {
			jQthis.prev().addClass('hidden');
			jQthis.removeClass('hidden');
			if(data.result == 1) {
				$("#past-offset").text(parseInt(pastOffset, 10) + parseInt(data.additional, 10));
				$(".list.present").append(data.output);
				daysback = daysback + 31;
			}  
		});
		return false;
	});
	
	// Past year arrow
	$("#past-year").live("click", function() {
		jQthis = $(this);
		jQthis.addClass('hidden');
		jQthis.prev().removeClass('hidden');
		var pastOffset = $("#past-offset").text();
		post("ajax/stream_get", {
			offset	: pastOffset,
			daysback: "365"
		}, function(data) {
			jQthis.prev().addClass('hidden');
			jQthis.removeClass('hidden');
			if(data.result == 1) {
				$("#past-offset").text(parseInt(pastOffset, 10) + parseInt(data.additional, 10));
				$(".list.present").append(data.output);
			}  
		});
		return false;
	});

	var infoTxt = $("#infoTxt").text();
	
	//Set Input bar default txt
	$("#note-textField").val(infoTxt);
	//Clear the default txt
	$("#note-textField").live("focusin", function() {
		if($(this).val() == infoTxt) {
			$(this).val("");
		}
	});
	$("#note-textField").live("focusout", function() {
		if($(this).val() == "") {
			
			$(this).val(infoTxt);
			$(this).height(28);
			$(this).updateHeight('destroy');
		}
	});
	var commentTxt = $("#commentTxt").text();
	
	if (typeof(area) != "undefined" && area != "calendar") {
		
		
		$(".commentField").live("focusin", function() { //Show big comment bubble on focus
			if($(this).val() == commentTxt) {
				$(this).val("");
			
			}
			commentOpen = true;
			jQthis = $(this);
			jQthis.next().removeClass('hidden');
			jQthis.parent().prev().removeClass('hidden');
			commentBox = jQthis.parents("div.addComment:first");
			commentBox.removeClass('smallComment');
			commentBox.addClass('bubble');
			if(jQthis.val() == "") {
				jQthis.height(70);
			}
		});
		
		$(".commentField").live("focusout", function() { //Hide big comment bubble on focus
				if($(this).val() === "") {
					commentOpen = false;
					jQthis = $(this);
					jQthis.next().addClass('hidden');
					jQthis.parent().prev().addClass('hidden');
					commentBox = jQthis.parents("div.addComment:first");
					commentBox.addClass('smallComment');
					commentBox.removeClass('bubble');
					$(this).val(commentTxt);
					jQthis.height(14);
					$(this).updateHeight('destroy');
			}
			
	
		});
	}
	else {
		$(".commentField").live("focusin", function() {
			if($(this).val() == commentTxt) {
				$(this).val("");
			
			}
		});
	}
	
	$(".commentField").live('keyup', function() {
		$(this).updateHeight();
		return false;
	});
	
	$("#note-textField").live('keyup', function() {
		$(this).updateHeight('init', {"lines" : 4});
		return false;
	});

	
	
	$("#modalWindow .cancelButton").click(function() {
		hideModal();
		return false;
	});
	
	$("#addEventPopupView .cancelButton").click(function() {
		hidePopup();
		resetPopup();
		hideModal();
		return false;
	});
	$("#addEventPopupLoader .cancelButton").click(function() {
		$("#addEventPopupLoader").addClass("hidden");
		$(".eventPopupHolder").removeClass("hidden");
		$(".calAjaxLoader").addClass("hidden");
		hidePopup();
		resetPopup();
		hideModal();
		return false;	
	});
	
	$("#addTodoPopupView .cancelButton").click(function() {
		hidePopup();
		resetFeedPosting();
		hideModal();
		
		
		return false;
	});
	
	$(".popupClose").click(function() {
		hidePopup();
		resetPopup();
		hideModal();
		return false;
	});
	
	//Prepare Axupload image
	if(area === "home") {
		if(!isIE || ieVersion > 7) {
			try {
				var axSettings = {
				    url:site_url+'ajax/axupload',
				    maxFiles:25,
				    allowExt:['jpg','gif', 'png', 'jpeg'],
				    showHeaders: false,
				    showSize: 'none',
				    language: lang,
				    uploadAllButton : false,
				    finish:function(txt,files,check){
				        alert(JSON.stringify(files));
				    },
				    fileAdded : function(fileCount) {
				    	$('#axUploader .ax-file-list').removeClass('hidden');
				    	$('#axUploader .ax-progress-div').addClass('hidden');
				    },
				    fileRemoved : function(fileCount) {
				    	if(fileCount == 0) {
				    		$('#axUploader .ax-file-list').addClass('hidden');	
				    	}
				    }
				};
				
				$('#axUploader').axuploader(axSettings);
				
				$('#axUploader .ax-file-list').addClass('hidden');
				if(isIE) {
					$(".imgFields").addClass('hidden');
					$(".addPostImages").click(function() {
					//$(".imgFields").toggleClass("hidden");
						$(".imgFields").toggleClass('hidden');
					});	
				}
				else {
					$(".addPostImages").click(function() {
						//$(".imgFields").toggleClass("hidden");
						$('#axUploader input[name="ax-files[]"]').trigger('click');
					});
				}
			}
			catch(e) {
			}
		} 
		else { //ie <8
			
			$(".addPostImages").click(function() {
				//$(".imgFields").toggleClass("hidden");
				$('#imageForm').toggleClass('hidden');
			});
		}
		
	}
	// feed-post click-handler
	$(".masterPostButton").click(function() {
		var jQthis  = $(this);
		var feedType = $("#postTypeHolder").val();
		var textVal = $("#"+feedType+"-textField").val();
		hasImages = $("#imageUpload_wrap_list").html();
		var hasAxImages = $("#axUploader .ax-file-list tr").length > 1;
		
		// don't post empty message or the info text
		if(!(textVal === "")) {
			$(jQthis).addClass("hidden");
			$(jQthis).prev().removeClass("hidden");
			
			var sd = null;
			var st = null;
			var ed = null;
			var et = null;
			var ft = null;
			var mp = null;
			var rp = null;
			

			var data = {
					content		: textVal,
					type		: feedType,
					startDate	: sd,
					startTime	: st,
					endDate		: ed,
					endTime		: et,
					forTime		: ft,
					repeat		: rp,
					eventId		: null,
					entryId		: null,
					eventStart	: null,
					doneable 	: 1
			};
			
			if(feedType == "todo") {
				var mpArr = new Array();
				// event targets
				$(".todoMemberSelection input:checked").each(function(idx) {
					mpArr[idx] = $(this).val();
				});
				
				if ($(".doneable").is(':checked')) {
					data.doneable = 0;	
				}
				
				if ($('[name="hide_in_feed"]').is(':checked')) {
					data.hide_in_feed = 1;	
				}
				
				
				if(mpArr === null || mpArr === 0) {
					data.multiple = 0;
				}
				else {
					data.multiple = mpArr.join("#!");
				}
				
				if($("#todo-entryId").val().length>0) {
					data.entryId = $("#todo-entryId").val();
				}	
				
				if($(".trophyForTodo").is(':checked')) {
					data.trophy = 1;
					data.trophyTitle = $('[name="trophyTitle"]').val();
					data.bronzeLimit = $('[name="bronzeLimit"]').val();
					data.silverLimit = $('[name="silverLimit"]').val();
					data.goldLimit = $('[name="goldLimit"]').val();
					data.trophyTimeHolder = $('[name="trophyTimeHolder"]').val();
					data.trophyIconHolder = $('#trophyIconList').find('.current').html().replace(/ /gi, '');
				}				
							
			}
			if(hasAxImages) {
				commentOpen = true; //No refreshing pls
				$('#axUploader .ax-progress-div').removeClass('hidden');
				data.type = "axImage";
				var axcallback = function(txt,files) {
					data.images = files;
					var uploadedMsg = $("#axWaitMsg").text();
					//Show a msg here so the user doesn't get too frustrated with delays.
					addMessage("ack", uploadedMsg, 0, '#systemMessageContainer');
					post('ajax/stream_modify/entry/axImage', data, function(data) {
						//console.log(data);
						commentOpen = false;
						refreshFeed(0, false, true);
						setClassFirst();
						$(jQthis).removeClass("hidden");
						$(jQthis).prev().addClass("hidden");
						$('#axUploader .ax-clear').trigger('click');
						$('#axUploader .ax-progress-div').addClass('hidden');
						if(isIE) {
							$(".imgFields").addClass('hidden');
						}
						resetFeedPosting(feedType);
					});	
				};
				$("#axUploader").axuploader('setCallback', axcallback);
				$("#axUploader").axuploader('start');
				return false;
			}
			// if feedtype is image -> do some serious hacks
			if(hasImages.length > 0) {
				
				$("#imgTitle").val(textVal);
				$.fn.MultiFile.disableEmpty(); 
				$("#imageForm").ajaxSubmit({
					dataType: null,
					beforeSubmit: function(a, f, o) {
					
					},
					success: function(data) {
					 
				
						if(data.length < 100) {
						
							addMessage("notify", data, 0, "#systemMessageContainer");
							return false;
						}
						var len = data.length - 11;
						var encoded = data.substring(10, len);
						var decoded = Encoder.htmlDecode(encoded);
						
						// insert the user post to top of the list
						postToTop(decoded, 1);
		
						$(".list.present").find(".ttl:first").next().find(".actions a").each(function() {
							$(this).removeClass("hidden");
						});
						
						openFull();
						setClassFirst();
						var textField = $("#note-textField");
						textField.val("");
						
						textField.height(28);
						textField.updateHeight('destroy');
		
						$(jQthis).removeClass("hidden");
						$(jQthis).prev().addClass("hidden");
						$.fn.MultiFile.reEnableEmpty();
						$('#imageForm').addClass('hidden');
						resetImagePosting();
						updateFacebookCounter();
					}
				});
			}
			// if not image -> do regular ajax hacks
			else {
				var sendData = data;
				post("ajax/stream_modify/entry/" + feedType, data, function(data) {
					if(data.result == 1) {
						// update future bar
						if(feedType == "todo") {
							var newId = data.additional;
							var oldEntry = $("#todo-"+newId);
							if(oldEntry.length > 0) {
								oldEntry.replaceWith(data.output);	
								$("#todo-"+newId).css('display', 'none').fadeIn(500);
							}
							else {
								$("#todoFirst").after(data.output);
								$("#todo-"+newId).css('display', 'none').fadeIn(500);
							}
							
							refreshFeed(0, false, true);
							setClassFirst();
							$(jQthis).removeClass("hidden");
							$(jQthis).prev().addClass("hidden");
							setFeedFilterAll();
						}
												
						else {
							refreshFeed(0, false, true);
							setClassFirst();
							$(jQthis).removeClass("hidden");
							$(jQthis).prev().addClass("hidden");
						}
						resetFeedPosting(feedType);
						updateFacebookCounter();
					}
					else {
						addMessage("notify", data.errorMessage, 0, ".list-gutter.upper");
						$(jQthis).removeClass("hidden");
						$(jQthis).prev().addClass("hidden");
					}
					
				});
				hideModal();
				return false;
			}
			
		} // end if
		else {
			$("#"+feedType+"-textField").val(infoTxt);
		}
		
		return false;
	});
	
	
	//New Event posting
	
	$("#postButton").click(function() {
		var jQthis  = $(this);
		$(".eventPopupHolder").addClass("hidden");
		$("#addEventPopupLoader").removeClass("hidden");
		var textVal = $("#event-textField").val();
		
		// don't post empty message or the info text
		
		
			var sd = null;
			var st = null;
			var ed = null;
			var et = null;
			var ft = null;
			var mp = null;
			var rp = null;
			var fullday = null;
						
			var eventBadge = $(".eventIcons a.active").attr('rel');
			
				sd = $("[name='startDate']").val();
				st = $("[name='startTime']").val();
				ed = $("[name='endDate']").val();
				et = $("[name='endTime']").val();
				ft = $("[name='forTime']").val();
				rp = $("[name='repeat']").val();
			
			if ($(".fullDay").is(":checked")) {
				fullday = 1;	
			}
			
			if ($(".fullDay").is(":checked")) {
				st = "00:00";
				et = "00:00";
				
				
			}
			
			if(rp !== 'none' && ft === "") {
				$("[name='forTime']").addClass('errorBorder');	
				$(".eventPopupHolder").removeClass("hidden");
				$("#addEventPopupLoader").addClass("hidden");
				return false;
			}
			if(ft !== "") {
				ft = validateDate(ft);	
			}
			sd = validateDate(sd);
			ed = validateDate(ed);
			/* Check whether time input is correct */
			if(fullday === null) {
				var toCheck = /^[0-9]{1,2}:[0-9]{1,2}$/ig
				st = validateTime(st)
				if(!st) {
					$("[name='startTime']").addClass('errorBorder');
					$(".eventPopupHolder").removeClass("hidden");
					$("#addEventPopupLoader").addClass("hidden");
					return false;
				}
				et = validateTime(et)			
				if(!et) {
					$(".eventPopupHolder").removeClass("hidden");
					$("#addEventPopupLoader").addClass("hidden");
					$("[name='endTime']").addClass('error');
					return false;
				}
			
			}	
			
			var data = {
					content		: textVal,
					type		: 'calendarEvent',
					startDate	: sd,
					startTime	: st,
					endDate		: ed,
					endTime		: et,
					forTime		: ft,
					repeat		: rp,
					eventId		: null,
					entryId		: null,
					eventStart	: null,
					event_badge : eventBadge,
					fullday 	: fullday,
					location	: location
			};
			
			
			var mpArr = new Array();
				// event targets
				$(".eventMemberSelection input.memberId:checked").each(function(idx) {
					mpArr[idx] = $(this).val();
				});
				
				
				if(mpArr === null || mpArr === 0) {
					data.multiple = 0;
				}
				else {
					data.multiple = mpArr.join("#!");
				}
				
				
				var	mobmArr = new Array();
				// people added to mobile reminders
				$(".eventMobileSelection input:checked").each(function(idx) {
					mobmArr[idx] = $(this).val();
				});
				if(mobmArr === null || mobmArr === 0) {
					data.mobileMultiple = 0;
				}
				else {
					data.mobileMultiple = mobmArr.join("#!");
				}
				
				data.reminderSendTime = $("[name='mobile-sendTime']").val();
				data.reminderSendBefore = $("[name='mobile-sendBefore']").val();
			
			
				data.eventId	= $('#eventId').val();
				data.entryId 	= $('#entryId').val();
				data.eventStart	= $('#eventStart').val();
				data.showDate = $("#dateHolder").val();
				data.location = $("[name='location']").val();
				
				//Alarms
				var alarmBefore = $('#addEventPopupView [name="alarmBefore"]').val();
				if(alarmBefore !== "none") {
					var alarmOffset = $('#addEventPopupView #alarmSelectTime').val()*60;
					data.alarm = 1;
					data.alarm_before = alarmBefore;
					switch(alarmBefore) {
						case "start": 
							data.alarm_offset_start = alarmOffset;	
						break;	
						case "end": 
							data.alarm_offset_end = alarmOffset;
						break;
						case "both":
							data.alarm_offset_start = alarmOffset;
							data.alarm_offset_end = alarmOffset;
						break;
					}
					
				}
				
			
			
				$(".calAjaxLoader").removeClass("hidden");
		
				var sendData = data;
				post("ajax/stream_modify/entry/calendarEvent/", data, function(data) {
					if(data.result == 1) {
						// update future bar
						
						$(".calendarStreamUl").empty();
						$(".calAjaxLoader").addClass("hidden");
						$(".calendarStreamUl").append(data.output);
						$(".eventPopupHolder").removeClass("hidden");
						$("#addEventPopupLoader").addClass("hidden");	
						hidePopup();
						$("input[type=file].multi").MultiFile();
						updateFacebookCounter();
						
							
						// if mobile reminder sending fails
						if(data.errorMessage) {
														
							$("#addEventPopupLoader span").addClass("hidden");	
							$("#addEventPopupLoader .cancelButton").removeClass("hidden");
							addMessage("notify", data.errorMessage, 0, ".list-gutter.calendarView");
						}
						
					}
					else {
						$(".eventPopupHolder").removeClass("hidden");
						$(".calAjaxLoader").addClass("hidden");
						$("#addEventPopupLoader span").addClass("hidden");	
						hidePopup();
						addMessage("notify", data.errorMessage, 0, "#systemMessageContainer");
						
						
					}
				});
			
			
		hideModal();
		return false;
	});
	
		
	/*Mobile Reminder Send Button*/
	$(".sendMobileReminderButton").click(function() {
		var data = {
					content		: null,
					mobileMultiple : null
			};

		var mpArr = new Array();
				// reminder targets
				$(".reminderMemberSelection input:checked").each(function(idx) {
					mpArr[idx] = $(this).val();
				});
								
				if(mpArr === null || mpArr === 0) {
					data.mobileMultiple = 0;
				}
				else {
					data.mobileMultiple = mpArr.join("#!");
				}
				
				if($("#reminder-textfield").val().length>0) {
					$("#reminder-content").val($("#reminder-textfield").val());
				}
				
				if($("#reminder-content").val().length>0) {
					data.content =  $("#reminder-content").val();
				}	
				post("ajax/sendMobileReminders/" , data, function(data) {
					
					if (data.result == 1) {
						addMessage("ack", data.output, 0, "#systemMessageContainer");
					}
					
					else {
						addMessage("error", data.output, 0, "#systemMessageContainer");
					}

				});
			
		hidePopup();
		return false;
		
	});


	if($(".smileyList").length > 0) {
		var sl = $(".smileyList");	
		var start = null;
		
		$(".smiley").click(function(e) {
			$(sl).toggleClass("hidden");
			smileyType = $(this).attr("id");
			smileyType = smileyType.split("-");
						
		});
		
		$(sl).find("div.smileyIcon").click(function() {
			var start = $('#'+smileyType[0]+'-textField').caret().start;
			var thisId  = $(this).attr("class");
			var thisAlt = $(this).attr("alt");
			var textVal = $('#'+smileyType[0]+'-textField').val();
			if(start == textVal.length) { // if the caret is at the end
				$('#'+smileyType[0]+'-textField').val(textVal + " " + thisAlt + " ");
			}
			else {	
				$('#'+smileyType[0]+'-textField').val(textVal.substr(0, start) + " " + thisAlt + " " + textVal.substr(start, textVal.length));			
			}
			
			$('#'+smileyType[0]+'-textField').focus();
			var caretStart = start + thisAlt.length+1;
			$('#'+smileyType[0]+'-textField').caret(caretStart, caretStart);
			$(sl).toggleClass("hidden");
			return false;
		});
	}
		
		
	$("#repeatSelect").bind("change", function() {
		if($(this).val() != "none" && $(this).val() != "yearly") {
			$(".untilSelect").removeClass("hidden");
		}
		else {
			$(".untilSelect").addClass("hidden");
		}
	});
	
	/** 
	* Bind scrolling hides - the triggering element needs to have the target selector and single element type as it's rel attributes, for example <a class="scrollHideForward" href="#" rel="#myList-li">
	**/
	$(".scrollHideForward").live('click', function() {
		var params = $(this).attr('rel');
		var params = params.split('-');
		
		scrollHideForward(params[0], params[1]);
		return false;
	});
	
	
	$(".scrollHideBackward").live('click', function() {
		var params = $(this).attr('rel');
		var params = params.split('-');
		
		scrollHideBackward(params[0], params[1]);
		return false;
	});
	
	// actions event-handler
	$(".actions a").live("click", function(e) {

		var jQthis = null;
		var eventId = null;
		var entryId = null;
		var eventDate = null;
		var type = null;
		thisMsg = $(this).attr("rel").split("-");
		var thisMsgComments = $(this).parent().parent().parent().find(".entryComments");
	
		//Thumb up
		if($(this).hasClass("thumbUp")) {
		
			var jQthis = $(this);
			if(thisMsg[1] == "0") {
				// this is needed if we try to send an event with no instance
				eventStart = jQthis.parent().find('.entryDate').html();	
				eventId = thisMsg[3];
			}
				
				post("ajax/cheer", {
					entryId		: thisMsg[1],
					eventId 	: eventId,
					type 		: "thumb"

				}, function(data) {
					
					$(jQthis).parents("li:first").after(data.output);
					//$(jQthis).parents("li:first").after(data.output);
					$(jQthis).parents("li:first").remove();
					setClassFirst();
					openFull();
	
				});
			
		}
		
		//Cheering
		if($(this).hasClass("feel")) {
			if(!$("#entryCheers").hasClass('hidden')) {
				$("#entryCheers").addClass('hidden');
				return false;	
			}
			jQthis = $(this);
			
			if(thisMsg[1] == "0") {
				// this is needed if we try to send an event with no instance
				eventStart = jQthis.parent().find('.entryDate').html();	
				eventId = thisMsg[3];
			}


			$("#entryCheers").css('left', (e.pageX-100)+'px').css('top', (e.pageY+10)+'px');
			$("#entryCheers").removeClass('hidden');
			
			$("#entryCheers li").click(function(e) {
				var cheerInfo = $(this).attr('rel').split('-');
				post("ajax/cheer", {
					entryId		: thisMsg[1],
					eventId 	: eventId,
					type 		: cheerInfo[0],
					name		: cheerInfo[1]

				}, function(data) {
					
					$(jQthis).parents("li:first").after(data.output);
					//$(jQthis).parents("li:first").after(data.output);
					$(jQthis).parents("li:first").remove();
					setClassFirst();
					openFull();
	
				});
				
				$("#entryCheers").addClass('hidden');
				$("#entryCheers li").unbind('click');
				return false;
			});	
			
		}
	
		if($(this).hasClass("comment")) {
			
			// if previous comments are hidden we need to show them
			if(thisMsgComments.html()) {
				thisMsgComments.removeClass('hidden');
			}
			
			var addComment = $(this).parents("li:first").find(".addComment").clone().removeClass("hidden addComment").addClass("commentCloned last");
			// hidden
			if($(this).parents("li:first").find(".commentCloned").css("display") != "block") {
				$(this).parents("li:first").append(addComment);
				$(this).parents("li:first").find(".commentCloned .commentField").focus();
				$(this).parents("li:first").find(".bubble").not(":last").removeClass("last");
				zebra($(this));
				commentOpen = true;
			}
			// visible
			else {
				$(this).parents("li:first").find(".commentCloned").remove();
				$(this).parents("li:first").find(".bubble").removeClass("last");
				$(this).parents("li:first").find(".bubble:visible:last").addClass("last");
				commentOpen = false;
			}
		}
	
		
		if($(this).hasClass("send")) {
			jQthis = $(this);
			
			var eventStart 	= null;
			var eventId		= null;
			
			//Reset fb
			$("#trophyToFacebook [name='publishToFacebook']").val('');
			$("#trophyToFacebook").addClass('hidden');
			$("#fbImageContainer").addClass('hidden');
			$("#fbImages").empty();
			
			var entryTodo 	= jQthis.parent().find('.entryTodo').html();	
			
			//Check if this originates from a todo
			if(entryTodo != '') {
				//We need to check if this has a trophy
				post('ajax/getTrophy', {
					entryId	:	entryTodo,
					checkExport	: 1	//also check if export is ordered	
				}, function(data) {
					if(data.result == 1) {
						if(data.additional == 1) {
							$("#trophyToFacebook [name='publishToFacebook']").attr('checked', true);
						}
						else {
							$("#trophyToFacebook [name='publishToFacebook']").attr('checked', false);
						}
						$("#trophyToFacebook [name='publishToFacebook']").val(data.output);	
						$("#trophyToFacebook").removeClass('hidden');
					}
					
					modalWindow($(this), "send");
				});
			}
			
			else { 
				var entry = jQthis.parents("li:first");
				
				if(entry.hasClass('image')) { //Check if image
					var images = new Array();
					entry.find('span.entryContent .openFull').each(function() {
						images.push($(this).attr('href'));
					});
					if(images.length > 1) { //check if there are MANY images
						modalWindow($(this), "send");
						var imageList = '';
						for(var i in images) {
							var newclass = '';
							if (i == 0) {
								newclass = 'current first';	
							}
							else if(i == (images.length)-1) {
								newclass = 'last';	
							}
							imageList = imageList+'<li class="'+newclass+'">'+images[i]+'</li>';								
						}
						
						//Prepare the imagescroll html
						$("#fbImageContainer").empty();
						$("#fbImageContainer").append('<ul id="fbImages" class="hidden"></ul><div id="fbImageScroll" class="clearFix"></div>');
						
						$("#fbImages").append(imageList);
						
						$("#fbImageContainer").removeClass('hidden');
						
						
						$("#fbImageScroll").html('<img src="'+images[0]+'" />');
						
						$("#fbImageScroll").imageScroll('destroy'); //Unbind old
						$("#fbImageScroll").imageScroll('', {name : 'fb', list : '#fbImages', imgPath	: '', suffix : ''});
					}
					else { // just continue
						modalWindow($(this), "send");
					}
				}
				else { // just continue
					modalWindow($(this), "send");	
				}
			}
			
			if(thisMsg[1] == "0") {
				// this is needed if we try to send an event with no instance
				eventStart = jQthis.parent().find('.entryTimeDate').html();	
				eventId = thisMsg[3];
			}
			
			//Unbind previous
			$("#trophyToFacebook [name='publishToFacebook']").die('click');
			
			//Trophy to facebook check
			$("#trophyToFacebook [name='publishToFacebook']").live('click', function() {
				autoShare = $(this).val();
				
				if($(this).is(":checked")) {
					
					
					post("ajax/toggleFacebookPublish", {
							autoShare	: autoShare
							
						},  function(data) {
							
						});	
				}
				
				else {
					post("ajax/toggleFacebookPublish", {
							removeAutoShare	: autoShare
						},  function(data) {
							
						});	
				}
				
			});
			$(".fbShare").die('click'); //Unbind previous
			$(".fbShare").live("click",
					
					function() {
						
						var autoShare = null;
						var autoSelection = $(this).next().find('[name="publishToFacebook"]');
						var image = $("#fbImages").find('.current').html();
						
						var trophyDefinition = autoSelection.val();
						
						post("home/send/" + thisMsg[1], {
							email_to 	: "facebook",
							eventStart	: eventStart,
							eventId		: eventId,
							trophyId	: trophyDefinition,
							image		: image
						}, function(data) {
							if(data.result == 1) {
								addMessage("ack", data.systemMessages.ack, 0, "#systemMessageContainer");
								
								// Old 
								/*var link = data.output;
								window.open(link,'sharer','toolbar=0,status=0,width=626,height=436');*/
								
							}
							else {
								
								//addMessage("notify", data.systemMessages.error, 0, ".upperPart");
							}
							$(".entryTo").val("");
							$(jQthis).removeClass("hidden");
							$(jQthis).prev().addClass("hidden");
						}
					);
					
					hideModal();
					return false;
				});
				
			$("[name='sendEntry']").die('click'); //unbind previous
			$("[name='sendEntry']").live("click",
				function() {
					$(jQthis).addClass("hidden");
					$(jQthis).prev().removeClass("hidden");
					
					post("ajax/sendEmail/email_send_entry", {
						email_to 	: $(".entryTo:last").val(),
						eventStart	: eventStart,
						eventId		: eventId,
						entryId 	: thisMsg[1],
						freeText	: $("#sendView .shareFree").val()
						
						}, function(data) {
							if(data.result == 1) {
								addMessage("ack", data.systemMessages.ack, 0, "#systemMessageContainer");
							}
							else {
								addMessage("notify", data.systemMessages.error, 0, "#systemMessageContainer");
							}
						$(".entryTo").val("");
						$(jQthis).removeClass("hidden");
						$(jQthis).prev().addClass("hidden");
						}
					);

					
						
					
				
				hideModal();
				return false;
			});

		}
		if($(this).hasClass("edit")) {
			$("#postType-note").trigger('click'); // hide previous panels
			//hideConfirms(); // hide previous confirm dialogs
			// if event_id is spesified we're dealing with an event
	

			
			if(thisMsg[3]) {	
			
				entryId = thisMsg[1];
				eventId = thisMsg[3];		
				eventStart = $(this).parent().find(".entryTimeDate").html();
				repeat	   = $(this).parent().find('.entryRepeat').html();
				
				// if we click on the event below the input bar
				if($(this).parent().parent().parent().hasClass('past')) {
					// if no repeat, go straight to edit window
					if($(this).parent().find('.eventRepeat').html() == "none") {
						editEvent(eventId, null, null);
						return false;
					}
					else {
						modalWindow($(this), "editAllEvent");
					}
				}
				else if(repeat != "none" && repeat != "yearly") {
					$(".untilSelect").removeClass('hidden');
					modalWindow($(this), "editWhichEvent");
				}
				else { 
					editEvent(eventId, null, null);
					return false;
				}
				
				//modalWindow($(this), "editThisEvent");
				$('#eventId').val(eventId);
				$('#entryId').val(entryId);
				$('#eventStart').val(eventStart);
			
				
				$("input[name='all']").unbind('click');
				$("input[name='all']").bind('click',function() {
	
						//alert($(this).data('events'));
						editEvent(eventId, null, null, 'all');	
						return false;
				});
				
				$("input[name='this']").unbind('click');
				$("input[name='this']").bind('click', function() {	
					
						editEvent(eventId, entryId, eventStart, 'this');	
						
						return false;
				});
				
				return false;
				
			}
			else { // were dealing with a todo
				post("ajax/get/entry", {
					msgId	: thisMsg[1]
				},  function(data) {
						var objects = data.additional; // list of id's of users who are objects of the event
						var reminderObjects = data.reminderObjects;
						var content = data.output.content; // todo content
						var entryId		= data.output.entryId; // id of the todo we're editing
						
						// populate event  objects
						for(var i = 0; i < objects.length; i++) {		
							var user = objects[i];
							$("#add-todo-" + user).trigger('click');
						
						} 
						// populate event reminder objects
						for(var i = 0; i < reminderObjects.length; i++) {		
							var user = reminderObjects[i];
							$("#add-mobile_todo-" + user).trigger('click');
						} 
						
						$('#entryId').val(entryId);
						
						$("#postType-todo").trigger('click'); // open the panel
						$("#textField").val(content);
						
						$.scrollTo("#post-panel", 500);
				});
			}
			
		}
		if($(this).hasClass("delete")) {
			//hideConfirms();
			$("#postType-note").trigger('click'); // hide panels
			
			jQthis 		= $(this);
			entryId		= thisMsg[1];
			eventId 	= false;
			eventDate 	= null;
			var toDelete	= null;
			repeat		= null;
			type		= null;
			
			var clickedElement = jQthis.parent().parent().parent();
			var delimBefore = jQthis.parent().parent().parent().prev();
			var delimAfter = jQthis.parent().parent().parent().next();
			
			if(thisMsg[3]) { // if were deleting an event
				type = "event";
				repeat = jQthis.parent().find('.entryRepeat').html();
				eventDate = jQthis.parent().find('.entryDate').html();	
				eventId = thisMsg[3];
				if($(this).parent().parent().parent().hasClass('past')) {
					if($(this).parent().find('.eventRepeat').html() == "none") {
						modalWindow($(this), "deleteThisEvent");
					}
					else {
						modalWindow($(this), "deleteAllEvent");			
					}
					toDelete = "all";
				}
				else if(repeat != "none") {
					modalWindow($(this), "deleteWhichEvent");
					//$("#modalWindow .event.delete.which").removeClass('hidden');
				
				} 
				else {
					modalWindow($(this), "deleteThisEvent");
					//$("#modalWindow .event.delete.this").removeClass('hidden');
				}
				
				
			}
			else {
				type = "entry";
				//$("#modalWindow .entry.delete.this").removeClass('hidden');
				modalWindow($(this), "deleteThisEntry");
			}
			
			$("input[name='deleteall']").bind('click',
				function() {
					toDelete = "all";
					deleteEntry(entryId, eventId, eventDate, toDelete, clickedElement);
					return false;
			});
			
			$("input[name='deletethis']").bind('click',
				function() {
					
					if(toDelete !== "all") {
						toDelete = "this";
					}
					
					deleteEntry(entryId, eventId, eventDate, toDelete, clickedElement);
					return false;
			});
		}
		return false;
	});
	
	$("#entryCheerClose").live('click', function() {
		$("#entryCheers").addClass('hidden');
		return false;
	});

	// send comment
	$(".sendComment").live("click", function() {
		var jQthis = $(this);
					
			var comVal = $(this).prev().val();
			if(!(comVal === "" || comVal == infoTxt)) {
				$(jQthis).addClass("hidden");
				$(jQthis).next().css("display","inline");
				// check if a entry exists for the item want to comment on (looping event?)
				var thisMsg	= $(this).prev().attr("class").split("-");
				var noInstance = 0;
				var instanceDate = null;
				var eventStart = null;
				var eventEnd = null;				
				if(thisMsg[2]) {
					noInstance = 1;
					instanceDate = thisMsg[3];
					eventStart = thisMsg[4];
					eventEnd = thisMsg[5];
				}
	
				var thisClass = null;
				if($(this).parents(".bubble").hasClass("even")) {
					thisClass = "even";
				}
				else {
					thisClass = "odd";
				}
				post("ajax/stream_modify/comment", {
					msgComment	: comVal,
					msgId		: thisMsg[1],
					noInstance	: noInstance,
					instanceDate: instanceDate,
					zebra		: thisClass,
					eventStart 	: eventStart,
					eventEnd 	: eventEnd
				}, function(data) {
				
					if((typeof(area) != "undefined") && (area == "calendar" || area == "search")) {  //the DOM is a little bit different in calendar (and search)
						jQthis.next().addClass("hidden");
						jQthis.removeClass("hidden");
						jQthis.prev().val("");
						var lastComment = $(".commentsForItem-"+thisMsg[1]+".last");
						
						if(lastComment.length > 0) {
							
							lastComment.after(data.output);
							lastComment.next().addClass('last');
							lastComment.removeClass('last');
						}
						else {
							theParent = $(jQthis).parents("li:first");
							theParent.find(".row").after(data.output);
							if(noInstance == 1) {
								theParent.find(".eventActions a").each(function() {
									
									var rel = $(this).attr('rel');
									rel = rel.split('-');
									rel[1] = data.additional;
									rel = rel.join('-');
									$(this).attr('rel', rel);
								});
								theParent.find(".eventAttachments [name='entryId']").val(data.additional);
								theParent.removeClass('entry-0');
								theParent.addClass("entry-"+data.additional);	
							}	
						}
					}
					else {
						
						commentOpen = false;
						refreshFeed(0, true, true);
					}
					resetCommentHeight(); //Reset the comment expanding function
					updateFacebookCounter();
					openFull();
				});
			}
			else {
				$(this).prev().val(infoTxt);
			}
		
		return false;
	});

	if($(".dummy").length) {
		$(".dummy").each(function() {
			$(this).remove();
		});
	}
	
	// Birthday Reminders
	$("input[name='calendarSettingsSubmit']").click(function() {
		var data = {};
		data.daysBefore = $("#daysBefore").val();
		var	mobmArr = new Array();
		$(".reminderSubjects input:checked").each(function(idx) {
			mobmArr[idx] = $(this).val();
		});
		
		if(mobmArr === null || mobmArr === 0) {
			data.mobileMultiple = 0;
		}
		else {
			data.mobileMultiple = mobmArr.join("#!");
		}
		
		
		post("ajax/addCalendarReminder", data, function(data) {
			if(data.result == 1) {
				$("#calendarForm").submit();
			}
		});

		return false;
	});
	
	$("#icalUrl").bind('keyup focusout', function() {
		if($(this).val() !== "") {
			$("#nimenhuuto").attr('disabled', 'true').prev().addClass('grey');
		}
		else {
			$("#nimenhuuto").removeAttr('disabled').prev().removeClass('grey');
		}
	});
	
	$("#nimenhuuto").bind('keyup focusout', function() {
		if($(this).val() !== "") {
			$("#icalUrl").attr('disabled', 'true').prev().addClass('grey');
		}
		else {
			$("#icalUrl").removeAttr('disabled').prev().removeClass('grey');
		}
	});
	
	$("a.plus-panels, .hasOrder").live("click", function() {
		if($(this).hasClass("hasOrder")) {
			$(this).next().toggleClass("open");
		}
		else {
			$(this).toggleClass("open");
		}
		
		if($(this).parents(".subscription")){
			$(this).parents(".subscription").find(".reminder-container").slideToggle("fast");
		}
		
		$(this).parents(".mobile-panels").find(".mobile-body").slideToggle("fast");
		return false;
	});

	
	//Same for mobile setup page
	$("input[name='birthDayReminders']").click(function() {
		var data = {};
		data.daysBefore = $("#daysBefore").val();
		var	mobmArr = new Array();
		$(".reminderSubjects input:checked").each(function(idx) {
			mobmArr[idx] = $(this).val();
		});
		
		if(mobmArr === null || mobmArr === 0) {
			data.mobileMultiple = 0;
		}
		else {
			data.mobileMultiple = mobmArr.join("#!");
		}
		
		
		post("ajax/addCalendarReminder", data, function(data) {
			if(data.result == 1) {
				addMessage("ack", data.output, 0, ".list-gutter.upper");
			}
		});

		return false;
	});
/*
	$(".active, .dynamicAvatar").live("click", function() {
		if(!$(this).parents(".sidenav")) {
			return false;
		}
	});
*/	
	// datepicker (calendar)
	if($(".datepicker").length > 0) {
		// call datepicker function (plugin)
		if (typeof(lang) == 'undefined') {
			lang = "en";	
		}
		if (lang == 'fi')
		
				var first_day = "1";	
			
		}
		else {
			var first_day = "0";	
		}
		$(".datepicker").datepicker({
			constrainInput: false,
			changeMonth: true,
			changeYear: true,
			dateFormat: "dd/mm/yy",
			firstDay: first_day,
			dayNames: $.datepicker.regional[lang].dayNames,
			dayNamesShort: $.datepicker.regional[lang].dayNamesShort,
			dayNamesMin: $.datepicker.regional[lang].dayNamesMin,
			closeText: $.datepicker.regional[lang].closeText,
			prevText: $.datepicker.regional[lang].prevText,
			nextText: $.datepicker.regional[lang].nextText,
			currentText: $.datepicker.regional[lang].currentText,
	        monthNames: $.datepicker.regional[lang].monthNames,
	        monthNamesShort: $.datepicker.regional[lang].monthNamesShort,
			weekHeader: $.datepicker.regional[lang].weekHeader,
			minDate: 0,
			maxDate: "+12m",
			yearRange: "-50:+50",
			showButtonPanel: true,
			onClose: function(text) {
				var sd = $("[name='startDate']").val().split("/");
				var ed = $("[name='endDate']").val().split("/");
				var ft = $("[name='forTime']").val().split("/");
				
				var startDate 	= sd[2]+sd[1]+sd[0];
				var endDate 	= ed[2]+ed[1]+ed[0];
				var forTime 	= ft[2]+ft[1]+ft[0];
				
				
				
			
				if(endDate < startDate) {
			
					$("[name='endDate']").val($("[name='startDate']").val());
				}
				if(forTime < endDate) {
					$("[name='forTime']").val($("[name='endDate']").val());
				}
				
			}
		});
	
		

		// datepicker click-handler
/*
		$("#datepicker-icon").click(function () {
			$("#datepicker").datepicker("show");
		});
*/
	
	
	
	//set default times
	var currentTime = new Date();
	var checkHours = currentTime.getHours();
	var checkMinutes = currentTime.getMinutes();
	var hours = currentTime.getHours()+1;
	var endHours = currentTime.getHours()+2;
	var minutes = "00";
	var day = currentTime.getDate();
	var month = currentTime.getMonth()+1; //Javascript month starts from 0
	var year = currentTime.getFullYear();
	
	var hourStr = "0";
	if (hours < 10){
		hours = hourStr.concat(hours);
	}
	if (endHours < 10) {
		endHours = hourStr.concat(endHours);	
	}
	
	
	if (checkHours < 10){
		checkHours = hourStr.concat(checkHours);
	}
	
	if (hours > 24) {
		var diff = hours - 24;
		hours = hourStr.concat(diff);
	}
	
	if (endHours > 24) {
		var diff = endHours - 24;
		endHours = hourStr.concat(diff);
	}

	$("#postStartTime").val(hours+':'+minutes);
	$("#postEndTime").val(endHours+':'+minutes);	
			
	$("[name='startTime']").bind('blur', function() {
		if($("[name='startTime']").val() < (checkHours+":"+checkMinutes) && $("[name='startDate']").val() == (day+"/"+month+"/"+year)) {
			$("[name='startTime']").val((hours+":"+minutes));
		}
	});
		
	$("[name='endTime']").bind('change', function() {
		if($("[name='endDate']").val() == $("[name='startDate']").val()) {
			if($("[name='endTime']").val() < $("[name='startTime']").val()) {
				 $("[name='endTime']").val($("[name='startTime']").val());
			}
		}
		if(!validateTime($("[name='endTime']").val())) {
			$(this).addClass('errorBorder');
				
		}
		else {
			$(this).removeClass('errorBorder');	
		}
	});
	$("[name='startTime']").bind('change', function() {
		startTime = validateTime($("[name='startTime']").val());
		if(!startTime) {
			$(this).addClass('errorBorder');
			return false;
		}
		if($("[name='endDate']").val() == $("[name='startDate']").val()) {
						
			endSplit = startTime;
			endSplit = endSplit.split(":");
			
			endSplit[0] = parseInt(endSplit[0], 10)+1;
			
			if(endSplit[0] == "24" && endSplit[1] != "00") {
				
				endSplit[0] = "23";
				endSplit[1] = "59";	
			}
			if(endSplit[0] < 10) {
				var hourStr = "0";
				newEnd = hourStr.concat(endSplit[0]);
			}
			else {
				var newEnd = endSplit[0];	
			}
			$("[name='endTime']").val(newEnd+":"+endSplit[1]);
			
		}
		
		
		
		$(this).removeClass('errorBorder');
		
		
		if(!validateTime(newEnd+":"+endSplit[1])) {
			$("[name='endTime']").addClass('errorBorder');
				
		}
		
		else {
			$("[name='endTime']").removeClass('errorBorder');
		}

	});


	
	$("#postStartTime").AnyTime_picker({ 
		format: "%H:%i", labelTitle: "",
        labelHour: "h", labelMinute: "min" 
    });
	
	$("#postEndTime").AnyTime_picker({ 
		format: "%H:%i", labelTitle: "",
        labelHour: "h", labelMinute: "min" 
    });
    
    $("#postStartTime").val(hours+':'+minutes);
	$("#postEndTime").val(hours+':'+minutes);
	
	/*Form login allow */
	setupAllowLogin();

	/* Call form checker function */
	if (typeof(area) != "undefined") {
		checkForm("#memberForm.ajaxForm");
		
	}
	else {
		checkForm("#registrationForm");	
	}
	
			
	/* ------- Add member gender selection -------*/
	$(".genderContainer input").live('click', function() {
		// remove old styles
		if($(this).val() != "pet") {
		$(".genderContainer label").removeClass("selected");	
			// add new selected style
		
			$(this).parent().addClass("selected");
			
			$(".genderContainerCopy").remove();
			$("#memberForm").removeClass('hidden');
			$("#petForm").addClass('hidden');
			
			var val = $(this).val();
			
			$("#gender-"+val).attr("checked", "checked");
			$("#gender-"+val).parent().addClass('selected');
		}
	});
	
	/* add member pet form hide */
	$(".genderContainer input[name='gender']").click(function() {
		if($(this).val() == "pet") {
			$("#memberForm").addClass('hidden');
			$(".genderContainer label").removeClass('selected');
			$(this).parent().addClass('selected');
			$(".genderContainer").clone().insertAfter("#addPetLegend").addClass('genderContainerCopy');
	
			$("#petForm").removeClass('hidden');
		}
	});
	
	$("#petForm input[name='gender']").click(function() {
		if($(this).val() != "pet") {
			$("#memberForm").removeClass('hidden');
			$("#petForm").addClass('hidden');
		}
	});
	
	/* Admin panel */
	$("#adminTrophyType").change(function() {
		if($(this).val() == "New Type...") {
			$("#adminNewType").removeClass('hidden');	
		}
		else {
			$("#adminNewType").val('');
			$("#adminNewType").addClass('hidden');
		}
	});
	
	/* New hotswap */
	$("#hotswapToggle").click(function() {
		$("#hotswapField").toggleClass("hidden");
	});
	
	$(".hotswapLink").click(function() {
		jQthis = $(this);
		var info = $(this).attr('type');
		var info = info.split('-');
		$("#hotswapUidHolder").val(info[2]);
		if(info[1] == "1") {
			$("#hotswapForm").submit();	
		}
		
		else {
			modalWindow(jQthis, "hotswap");	
		}
	});

	$("#hotSwap").change(function() {
		var getVal = $(this).val().split("-");
		if(getVal[1] === "0") {
			$("#hotSwapPassword").removeClass("hidden");
		}
		else {
			$("#hotSwapForm").submit();
		}		
	});
	
	/* add flickr feed for member */
	$("#addFlickrFeed").bind('click', function() {
		
		var memberId = $("input[name='memberId']").val();
		
		$("#ajax-loader").attr("style", "display: block");	
				
		post("ajax/addflickr/" + memberId, {
			username	:	$("#flickrUsername").val()
		}, function(data) {
			/*
			console.log(data.result);
			console.log(data.output);
			*/	
			if(data.result == 1) {
				$("#flickrAccountsWrapper").append(data.output);
				$("#ajax-loader").attr("style", "display: none");
			}
			else if(data.result == -1) {
				addMessage("error", data.output, 0, ".list-gutter.upper");
				$("#ajax-loader").attr("style", "display: none");
			}
			else if(data.result == -2) {
				addMessage("notify", data.output, 0, ".list-gutter.upper");
				$("#ajax-loader").attr("style", "display: none");
			}
		});
		return false;
	});
	
	/* remove phone number from member */
	$("#remove_phone").bind('click', function() {
		var memberId = $("input[name='memberId']").val();
		post("ajax/removephone/" + memberId, {
		}, function(data) {
			if(data.result == 1) {
				addMessage("notify", data.output, 0, ".list-gutter.upper");
				$("#phoneNumber").val("");
				$("#remove_phone").prev().remove();
				$("#remove_phone").remove();
			}
			else if(data.result == -1) {
				addMessage("error", data.output, 0, ".list-gutter.upper");	
			}
		});
		return false;
	});
	
	/* Calendar navigation */
	
		if (typeof (area) != "undefined" && area == "calendar") {
			var currentDate = calDate.split('-');
			currentDate[1] = currentDate[1]-1;
			var thedate = new Date(currentDate[0], currentDate[1],currentDate[2], 12);
			$("#cal-navigation").calendar({ naviUrl: '#', year:thedate.getFullYear(), month:thedate.getMonth(), current: new Date(currentDate[0], currentDate[1],currentDate[2], 12), templateUrl: 'year/month/day' });
			$("#dateHolder").val(calDate);

		}
		else if(typeof (area) != "undefined" && area == "weekly_agenda") {
			$("#cal-navigation").calendar({ naviUrl: 'http://'+host_url+'calendar/index/' });
		}
	
	/* New todolist */
	$(".markAsDone").live("click", function() {
		jQthis = $(this);
		id = $(this).attr("rel");
		id = id.split("-");
		jQthis.addClass('hidden');
		jQthis.prev().removeClass('hidden');
			post("ajax/stream_modify/markasdone", {
				msgId	: id[0],
				doneable : id[1]
			}, function(data) {
				//if we returned multiple subjects to choose from, we need to use modal window
				if(data.additional == "subs") {
					$("#todoDoneView").empty();
					$("#todoDoneView").append(data.output);
					
					modalWindow(jQthis, "todoDone");
					
					
					
					$("[name='todoSubjectSelect']").click(function() {
						todoSubject = $(this);
						todoSubject.prev().removeClass('hidden');
						todoSubject.addClass('hidden');
						var chosen = $("#whoDidForm input:radio:checked").val();
					
						post("ajax/stream_modify/markasdone", {
							msgId	: id[0],
							doneable : id[1],
							clicker : chosen
						}, function(data) {
							hideModal();
							if(area == "home") {
								
								// insert the user post to top of the list		
								postToTop(data.output);				
								setClassFirst();
								toAnimate = $("ul.present").find(".entry-"+data.additional+" .trophyPercent");
								animateProgress(toAnimate);
	
								if(id[1] == 1) {
									$("#todo-"+id[0]).fadeOut(500, function() { $(this).remove()});
								}
								setFeedFilterAll();
								jQthis.removeClass('hidden');
								jQthis.prev().addClass('hidden');
								todoSubject.prev().addClass('hidden');
								todoSubject.removeClass('hidden');

							}
							else {
								location.reload();
							}
						});
						return false;
					});
							
				}
				else {
					if(area == "home") {
						// insert the user post to top of the list		
						postToTop(data.output);				
						setClassFirst();
						toAnimate = $("ul.present").find(".entry-"+data.additional+" .trophyPercent");
						animateProgress(toAnimate);
						jQthis.removeClass('hidden');
						jQthis.prev().addClass('hidden');

						if(id[1] == 1) {
							$("#todo-"+id[0]).fadeOut(500, function() { $(this).remove()});
						}
						setFeedFilterAll();
					}
					else {
						location.reload();
					}
				}
			});
			return false;
	});
	
	$("#todoDoneView .cancelButton").click(function(){
		hideModal();
		return false;
	});
	// Deleting a Todo
	$("#addTodoPopupView .deleteButton").live("click", function() {
		jQthis 		= $(this);
		entryId		= $("#todo-entryId").val();
		eventId = null;
		eventDate = null;
		toDelete = "this";
		clickedElement = entryId;
		
		deleteEntry(entryId, eventId, eventDate, toDelete, clickedElement);
		resetFeedPosting("todo");
		hidePopup();
		return false;
	});
	
	//Editing a Todo
	$(".editTodo").live("click", function() {
		id = $(this).attr("rel");
		id = id.split("-");
		$("#addTodoPopupView .deleteButton").removeClass('hidden');
		$("#todo-entryId").val(id[0]);
		$(".doneable").attr('checked', false);
				
		resetTodoTrophy();
		
		if (id[1] == "0") {
			$("#todo-doneable").val(id[1]);
			$(".doneable").trigger('click');
		}
		
		post("ajax/get/entry", {
					msgId	: id[0]
				},  function(data) {
						var objects = data.additional; // list of id's of users who are objects of the event
						var reminderObjects = data.reminderObjects;
						var content = data.output.content; // todo content
						var entryId		= data.output.entryId; // id of the todo we're editing
						var trophy = data.trophy;
						
						if(typeof(trophy) != "undefined") {
							$(".trophyForTodo").trigger('click');
							$('[name="trophyTitle"]').val(trophy.name);
							$('[name="bronzeLimit"]').val(trophy.level_1);
							$('[name="silverLimit"]').val(trophy.level_2);
							$('[name="goldLimit"]').val(trophy.level_3);
							
							$('#trophyIconList').find('.current').removeClass('current');
							$('#trophyIconList :contains('+trophy.icon+')').addClass('current');
							
							$('[name="trophyTimeHolder"]').find("option[value='"+trophy.type+"']").attr("selected","selected");
							var where = $("#trophyInfo .trophyIconBig");
							changeTrophyImg(trophy.icon, 3, where);
	
						}
						
						$(".todoMemberSelection .memberId").each(function() {
							$(this).attr('checked', false);
						});
			
						
						// populate event objects
						for(var i = 0; i < objects.length; i++) {		
							var user = objects[i];
							$(".todoMemberSelection .memberId[value=\'"+user+"\']").attr('checked', true);
							
						}

						$("#todo-textField").val(content);
						popupWindow($(this), "addTodoPopup");
						$("#postTypeHolder").val("todo");
					});
					return false;
	});
	
	/* Todo All Selection */
	
	$(".todoForAll").click(function() {
		if ($(this).is(":checked")) {
			$(".todoMemberSelection .memberId").each(function() {
				$(this).attr('checked', true);
			});
		}
		else {
			$(".todoMemberSelection .memberId").each(function() {
				$(this).attr('checked', false);
			});
		}
			
	});
	
	
		
	/* Todo adding popup */
	$(".addTodoPop").live('click', function() {
		jQthis = $(this);
		$("#addTodoPopupView .deleteButton").addClass("hidden");
		resetFeedPosting("todo");
		resetTodoTrophy();
		$("#todo-entryId").val("");
		
		var quickText = $("#newTodoText").val();
		if(quickText != '' && quickText != $("#todoAddText").text()) {
			$("#todo-textField").val(quickText);
		}
		
		popupWindow($(this), "addTodoPopup");
		$("#postTypeHolder").val("todo");
		$("#todoPopupTable input").each(function() {
			$(this).attr('checked', false);
		});
		
		return false;
	});
	
	/* Todo hover */
	$("#content .todoList li").live({
		"mouseover" : function() {
			var thisElem = $(this);
			thisElem.find('.todoHide').removeClass('hidden');
			
		},
		"touchend" : function() {
			var thisElem = $(this);
			var theFunction = function(thisElem) { thisElem.find('.todoHide').removeClass('hidden'); };
			window.setTimeout(theFunction(thisElem), 500);
			//thisElem.find('.todoHide').removeClass('hidden');
		},
		"mouseout" : function() {
			var thisElem = $(this);
			thisElem.find('.todoHide').addClass('hidden');
		}
	});
	
	/* Todo content quick edit */
	$(".todoList .contentEdit").live('click', function() {
		
		var thisElem = $(this);
		var text = thisElem.text();
		
		//Separate usernames and the rest of the text (editing is only allowed for the rest-part)
		var i = text.indexOf(':');
		var textSplit = [text.slice(0,i), text.slice(i+3)];

		var editText = textSplit[1];
		
		var todoId = thisElem.attr('rel');
		
		//Get the height of the elem, so that we can match it on the textarea
		var textHeight = parseInt(thisElem.height());
		//Save the current li element to variable since we are going to use it later
		var todoLi = $("#todo-"+todoId);
		
		//Hide action buttons while editing
		todoLi.find(".todoHide a").each(function() {
			$(this).addClass('hidden');
		});
		
		todoLi.find(".saveInstruction").removeClass('hidden');
		
		//Replace the text with subjects and textarea with the editable content
		thisElem.replaceWith('<div class="todoSubjects">'+textSplit[0]+':</div><textarea id="todoEditField" style="height:'+textHeight+'px; width:197px; font-size:12px; line-height:14px; margin-bottom:20px; margin-top:8px;"></textarea>');
		var editField = $("#todoEditField");
		
		//Put content into the textarea and focus
		editField.val(editText);
		editField.focus();
		
		// Unbind old 
		editField.die('focusout.todoEdit');
		editField.die('keyup.todoEdit');
		
		editField.live('keyup.todoEdit', function() {
			editField.updateHeight();
		});
		// On focusout, save the todo
		editField.live('focusout.todoEdit', function() {
			var newVal = editField.val();
			editField.updateHeight('destroy');
			
			//Save the subjects part and remove it since we have to combine it with the edited text after saving
			var subs = todoLi.find(".todoSubjects");
			var subSave = subs.text();
			subs.remove();
			
			//Prepare the final element and replace the textarea with it
			var textData = editField.val();
			var textData = strip_html_tags(textData);
		
			var newText = '<div rel="'+todoId+'" class="contentEdit"><div class="todoSubjects">'+subSave+'</div>\n<br /> '+textData+'</div>';
			
			editField.replaceWith(newText);
						
			//If the content was changed, save the changes via ajax post
			if(newVal != editText) {
				post('ajax/quickedit/todo/'+todoId, {"params" : {"content" : newVal}}, function(data) {
					if(data.result == 1) {
						var msg = $("#todoEditMsg").html();
						addMessage("ack", msg, 0, "#systemMessageContainer");
					}	
				});
			}
			
			//Show the action buttons again
			todoLi.find(".todoHide a").each(function() {
				$(this).removeClass('hidden');
			});
			todoLi.find(".saveInstruction").addClass('hidden');

		});
		
	});
	
	/* Todo quick new */
	$("#newTodoText").bind({
		
		'focusin' : function() {
			var thisElem = $(this);
			thisElem.keyup(function() {
				thisElem.updateHeight();
			});	
			var todoAddText = $("#todoAddText").html();

			if(thisElem.val() == todoAddText) {
				thisElem.val('');
			}
			$("#quickTodo").removeClass('hidden');
		},
		'focusout' : function() {
			var thisElem = $(this);
			thisElem.updateHeight('destroy');
			if(thisElem.val() == '') {
				var text = $("#todoAddText").html();
				thisElem.val(text);
				thisElem.height(28);
				$("#quickTodo").addClass('hidden');
			}	
		}
		
	});
	
	$("#quickTodo").click(function() {
			var thisBtn = $(this);
			thisBtn.addClass('hidden');
			thisBtn.prev().removeClass('hidden');
			var uid = $(this).attr('rel');
			var content = $("#newTodoText").val();
			post('ajax/stream_modify/entry/todo', {"multiple" : uid, "content" : content}, function(data) {
				if(data.result == 1) {
					$("#todoFirst").after(data.output);
					$("#todo-"+data.additional).css('display', 'none').fadeIn(500);
					refreshFeed(0, false, true);
				}
				var todoVal = $("#todoAddText").val();
				$("#newTodoText").val(todoVal).height(28).updateHeight('destroy');

				thisBtn.addClass('hidden');
				thisBtn.prev().addClass('hidden');
			});
			return false;	
	});
	
	/* Todo reminder sending */
	$(".sendTodoMob").live('click', function() {
		jQthis = $(this);
		info = $(this).attr('rel');
		$("#reminder-textfield").addClass('hidden');
		$(".reminderMemberSelection .memberId").each(function() {
			$(this).attr('checked', false);
		});
		$("#reminder-textfield").val("")
		$("#reminder-content").val(info);
		popupWindow($(this), "addReminderPopup");
		return false;
	});
	
	/* SMS sending */
	$(".sendSms").live('click', function() {
		jQthis = $(this);
		info = $(this).attr('rel');
		
		$(".reminderMemberSelection .memberId").each(function() {
			if($(this).val() == info) {
				$(this).attr('checked', true);
			}
			else {
				$(this).attr('checked', false);
			}
		});
		
		$("#reminder-textfield").removeClass('hidden');
		$("#reminder-textfield").val("");
		popupWindow($(this), "addReminderPopup");
		return false;
	});
	
	/* Send vcard */
	$("#sendVcard").click(function() {
		
		var data = {
			content		: $("#vcardInfo").html(),
			to : $(this).attr('rel')
		};

		post("ajax/sendSmsMessage/" , data, function(data) {
			
			if (data.result == 1) {
				addMessage("ack", data.output, 0, "#systemMessageContainer");
			}
			
			else {
				addMessage("error", data.output, 0, "#systemMessageContainer");
			}

		});
	
		
		return false;
		

		
	});
	
	/* Send mms contact */
	$("#sendMmscard").click(function() {
		
		var data = {
			content		: $("#mmsCardInfo").html(),
			to : $(this).attr('rel')
		};

		post("ajax/sendSmsMessage/" , data, function(data) {
			
			if (data.result == 1) {
				addMessage("ack", data.output, 0, "#systemMessageContainer");
			}
			
			else {
				addMessage("error", data.output, 0, "#systemMessageContainer");
			}

		});
	
		
		return false;
		

		
	});


	
	/* IcalExport popup */
	
	$("#addReminderPopupView .cancelButton").click(function() {
		hidePopup();
		return false;
	});
	//Event adding popup
	
	$(".addEventPop").live('click', function() {
		resetPopup();
		jQthis = $(this);
		$("#entryId").val("");
		$("#eventId").val("");
		/*$(".mobileTime :input").attr("disabled", "disabled");	
		$(".mobileTime span").addClass("grey");*/
		
		popupWindow($(this), "addEventPopup");
		var eventDate = $(this).attr('rel');
					
		$("[name='startDate']").val(eventDate);
		$("[name='endDate']").val(eventDate);
		$("#postTypeHolder").val("event");

		return false;
	});
	
	$("#addEventPopupView .tabs a").live('click', function() {
		var toTab = $(this).attr('rel');
		$(this).addClass('active');
		$(this).siblings().removeClass('active');
		
		var toSwitch = $("#"+toTab);
		toSwitch.removeClass('hidden');
		toSwitch.siblings().addClass('hidden');
		return false;
	});
	
	$(".eventForAll").click(function() {
		if ($(this).is(":checked")) {
			$(".eventMemberSelection .memberId").each(function() {
				$(this).attr('checked', true);
			});
		}
		else {
			$(".eventMemberSelection .memberId").each(function() {
				$(this).attr('checked', false);
			});
		}
			
	});
	
	/* Event Editing */
	
	$(".editEvent").live('click', function() { 
		jQthis = $(this);
	
		var Ids = $(this).attr('rel').split('-'); //get the event data 
			$("#eventId").val(Ids[3]);
			$("#entryId").val(Ids[1]);
			repeat = $(this).parent().find('.eventRepeat').html();
			//popupWindow($(this), "addEventPopup");
			var eventStart = Ids[5];
		
			if(repeat != "none" && repeat != "yearly") { //Repeating events, ask which to edit
					$(".untilSelect").removeClass('hidden');
					modalWindow($(this), "editWhichEvent");
			}
			else { 
					editCalendarEvent(Ids[3], Ids[1], eventStart, 'this');
					return false;
			}
				
			$("input[name='this']").unbind('click'); //Handles Modal box "This"
			$("input[name='this']").bind('click', function() {	
					
				editCalendarEvent(Ids[3], Ids[1], eventStart, "this");	
						
				return false;
			});
			
			$("input[name='all']").unbind('click'); //Handles Modal box "All"
				$("input[name='all']").bind('click',function() {
	
						//alert($(this).data('events'));
						editCalendarEvent(Ids[3], null, null, 'all');	
						return false;
			});


			 
			return false;
	});
	
	/* Event Deletion */
	$(".deleteEvent").live('click', function() {
		jQthis 		= $(this);
		thisMsg = jQthis.attr('rel');
		thisMsg = thisMsg.split('-');
		
			entryId		= thisMsg[1];
			eventId 	= null;
			eventDate 	= null;
			var toDelete	= null;
			repeat		= null;
			type		= null;
			clickedElement = null;
						
			if(thisMsg[4]) { // if were deleting an event
				type = "event";
				repeat = jQthis.parent().find(".eventRepeat").text();
				uniqueId = $(this).parent().find('.eventUniqueId').html();
				

				eventDate = thisMsg[5];	
				eventId = thisMsg[3];
				
				 if(repeat != "none" && uniqueId == "") {
					modalWindow($(this), "deleteWhichEvent");
					//$("#modalWindow .event.delete.which").removeClass('hidden');
				
				} 
				else {
					modalWindow($(this), "deleteThisEvent");
					//$("#modalWindow .event.delete.this").removeClass('hidden');
				}
				
				
			}
			$("input[name='deleteall']").unbind('click.deleteAll');
			$("input[name='deletethis']").unbind('click.deleteThis');
		
			$("input[name='deleteall']").bind('click.deleteAll',
				function() {
					toDelete = "all";
					deleteEntry(entryId, eventId, eventDate, toDelete, clickedElement);
					return false;
			});
			
			$("input[name='deletethis']").bind('click.deleteThis',
				function() {
					
					if(toDelete !== "all") {
						toDelete = "this";
					}
					
					deleteEntry(entryId, eventId, eventDate, toDelete, clickedElement);
					return false;
			});
		
		return false;
	});

	
	/* Event Icon selection */
	$("#eventIconSelector").live('click', function() {
		
		if(! $(".eventIcons").hasClass('hidden')) {
			$(".eventIcons").addClass('hidden');
			return false;
		}
		$(".eventIcons").removeClass('hidden');	
		$(".eventIcons a").click(function() {
			jQthis = $(this);
			$(".eventIcons a.active").each(		
				function(e) {
					$(this).removeClass('active');
				}
			); 
			var thisClass = $(jQthis).attr('class');		
			$(jQthis).addClass('active')
			$("#eventIconSelector").removeAttr('class');
			
			$("#eventIconSelector").attr('class', thisClass);
			$(".eventIcons").addClass('hidden');	
			return false;
		});
		return false;
	});
	
	$(".mobileReminderBox").live('click', function() {
		
		if($(this).is(":checked")) {
			
			$(".mobileTime :input").removeAttr("disabled");
			$(".mobileTime span").removeClass("grey");
		}
		
		else {
			if (countChecked() == "0") {
				$(".mobileTime :input").attr("disabled", "disabled");	
				$(".mobileTime span").addClass("grey");
			}	
		}
		
					
	});
	/* Fullday event selection */
	$(".fullDay").live('click', function() {
		
		if($(this).is(":checked")) {
			$("#postStartTime").addClass("hidden");
			$("#postEndTime").addClass("hidden");
			$("[name='endDate']").addClass("hidden");
		}
		
		else {
			
				$("#postStartTime").removeClass("hidden");
				$("#postEndTime").removeClass("hidden");
				$("[name='endDate']").removeClass("hidden");
				
		}

					
	});
	
	/* Ordering weekly calendar email */
	$("[name='calendarMailExport']").live('click', function(){
		if($(this).is(":checked")) {
			post("ajax/addExport", {
					type	: 'calendar',
					method	: 'email'
				},  function(data) {
					
				});	
		}
		
		else {
			post("ajax/removeExport", {
					type	: 'calendar',
					method	: 'email'
				},  function(data) {
					
				});	
		}
	
	});
	
	/* Ordering calendar change mail */
	$("[name='calendarChangeExport']").live('click', function(){
		if($(this).is(":checked")) {
			post("ajax/addExport", {
					type	: 'calendar_change',
					method	: 'email'
				},  function(data) {
					
				});	
		}
		
		else {
			post("ajax/removeExport", {
					type	: 'calendar_change',
					method	: 'email'
				},  function(data) {
					
				});	
		}
	
	});

	
	/* Show Calendar page Comments */
	$("#showCalendarComments").click(function() {
		if($(this).is(":checked")) {
			$(".calendarStreamUl .comment").each(function() {
				$(this).removeClass('hidden');
			});
		}
		else {
			$(".calendarStreamUl .comment").each(function() {
				$(this).addClass('hidden');
			});
		}
	});
	
	/* Event attachment ui */
	$("#calendarStream .addEventAttachment").live('click', function() {
		jQthis = $(this);
		var attachDiv = jQthis.parent().parent().parent().find('.eventAttachments');
		attachDiv.toggleClass('hidden');
		return false;	
	});
	
	/* Event file uploader */
	$("#calendarStream .attachmentPostButton").live('click', function() {
		jQthis = $(this);
		var form = jQthis.parent().parent();
		var eventAttachments = form.find('.MultiFile-wrap').html(); 
		var showDate = $("#dateHolder").val().replace(/-/gi, '/');
		//console.log(showDate); 
		form.find('[name="showDate"]').val(showDate);
		if(eventAttachments.length > 0) {
			
			$.fn.MultiFile.disableEmpty(); 
			form.ajaxSubmit({
				dataType: null,
				beforeSubmit: function(a, f, o) {
					
				},
				success: function(data) {
				//	console.log('success');
					
					$(".calendarStreamUl").empty().append(data);
					$("input[type=file].multi").MultiFile();
					openFull();					
					$.fn.MultiFile.reEnableEmpty();
					/*
					$.fn.MultiFile.reset(); 	*/
				}
			});
		}
		return false;
	});
	
	/* Weekly Agenda */
	if(typeof(area) != "undefined" && area == 'weekly_agenda') {
			dayNames = $.datepicker.regional[lang].dayNames;
			dayNamesShort = $.datepicker.regional[lang].dayNamesShort;
			dayNamesMin = $.datepicker.regional[lang].dayNamesMin;
			monthNames = $.datepicker.regional[lang].monthNames;
	        monthNamesShort = $.datepicker.regional[lang].monthNamesShort;
	        todayText = $.datepicker.regional[lang].currentText;
	        allDayText = $.datepicker.regional[lang].allDay;
	     if(typeof(weekly_print) != 'undefined') {
	     	firstHour = 7;	
	     	minTime = 7;
	     } 
	     else {
	     	minTime = 0;
	     	firstHour = 8;	
	     }
		$("#calendar").fullCalendar({
			header: {
				left: 'title',
				
				right: 'prev, today, next'
			},
			firstHour : firstHour,
			minTime : minTime,
			firstDay : 1,
			defaultView: 'agendaWeek',
			editable: false,
			timeFormat: 'H:mm{ - H:mm}',
			dayNamesShort : dayNamesShort,
			dayNames : dayNames,
			monthNamesShort : monthNamesShort,
			monthNames : monthNames,
			columnFormat : {
				 week: 'ddd d/M' //Mon 21/12	
			},
			buttonText : {
				today : todayText	
			},
			allDayText	:	allDayText,
			axisFormat : 'H:mm',
			allDaySlot : true,
			eventMouseover : function( event, jsEvent, view ) { 
				var mouseX = parseFloat(jsEvent.clientX);
				var mouseY = parseFloat(jsEvent.clientY);
				var hours = event.start.getHours();
				if(hours < 10) {
					hours = "0"+hours;	
				}
				var minutes = event.start.getMinutes();
				if(minutes < 10) {
					minutes = "0"+minutes;	
				}
				
				var endHours = event.end.getHours();
				if(endHours < 10) {
					endHours = "0"+endHours;	
				}
				var endMinutes = event.end.getMinutes();
				if(endMinutes < 10) {
					endMinutes = "0"+endMinutes;	
				}
				$("#fullCalTip").removeClass("hidden").html("<p>" + hours +':' + minutes + ' - ' + endHours +':' + endMinutes + ' ' + event.title + "</p>").css("top", (mouseY+10) + "px").css("left", (mouseX+10) + "px");
				
			},
			
			eventMouseout : function( event, jsEvent, view ) { 
				$("#fullCalTip").addClass("hidden");
			},
			events: base_url+'ajax/getfullcalendar/'
		});
		
		if(typeof(weekly_print) != 'undefined') {
        	year = print_year;
        	month = print_month;
        	day = print_day;	
        	$('#calendar').fullCalendar('gotoDate', year, month, day);
	    }
	    
	  	$('#calendar .fc-button-prev a, #calendar .fc-button-next a').live('click', function() {
			var calDate = $('#calendar').fullCalendar('getDate');
			var dayofWeek = calDate.getDay()-1;
			var tzOffset = calDate.getTimezoneOffset()*60;
			var dayDiff = (86400*dayofWeek)+tzOffset;
		
			var unixtime = Math.round(Date.parse(calDate)/1000);
			
			var startOfCal = unixtime-dayDiff;
			
			var linkTarget = site_url+'calendar/weeklyprint/'+startOfCal;
		
			$("#printWeek").attr('href', linkTarget);
			
		});
	 
	
		
	}	
	
	
	
	
	
	/* Rewards configuration */
	
	$("[name='trophyTimeHolder']").live('change', function() {
		var jQthis = $(this);
		var time = jQthis.val();
		
					
		post("ajax/copytext/trophy_"+time+"_times", {
					
			},  function(data) {
				$(".trophyTime").each(function() {
					$(this).empty();
					$(this).append(data.output);
				});
			});
		return false;
	});
	
	/* Trophy collection */
	$("#trophyTimelineNav a").live('click', function() {
		jQthis = $(this);
		increment = parseFloat(jQthis.attr('rel'));
		var forward = true;	
		if(jQthis.hasClass('backward')) {
			increment = increment + 1;
			forward = false;
		}	
		else {
			increment = increment - 1;
		}

		if(increment < 0) {
			return false;	
		}
		
		var forwardTime = $("#trophyTimelineNav .forwardTime").html();
		var backTime = $("#trophyTimelineNav .backTime").html();
		
		var backTime = backTime.split('-');
		var forwardTime = forwardTime.split('-');
		
		var endDate = new Date(forwardTime[1]+'/'+forwardTime[0]+'/'+forwardTime[2]);
		var startDate = new Date(backTime[1]+'/'+backTime[0]+'/'+backTime[2]);
		
				
		if(forward) {
			startDate.setDate(startDate.getDate()+7);
			endDate.setDate(endDate.getDate()+7);
			$("#trophyCollection div.trophyColumn").each(function() {
				jQthis = $(this);
												
				list =	$(this).find(".holder .animateTrophy");		
				listCount = list.size();
				
				var origCount = listCount - (increment+2);
		
				var original = $(this).find(".holder .animateTrophy:eq("+origCount+")")
							
				original.animate({ 
					"left" : "-600px"
				}, 
				750,"linear");
					
				original.next().animate(
					{
						"left" : "0px"
					}, 750,"linear"
				);
				
				
			});

		}
		else {
			startDate.setDate(startDate.getDate()-7);
			endDate.setDate(endDate.getDate()-7);
			list =	$("#trophyCollection div.trophyColumn:first .holder .animateTrophy");		
			listCount = list.size();
	
			if(listCount - increment == 0) {
				post("trophies/getTrophyList/", 
					{
						limit : increment
					},
					function(data) {
						
						//$("#trophyCollection").html(data.output);
						$("#trophyCollection div.trophyColumn").each(function() {
							jQthis = $(this);
							memberId = $(this).attr('rel');
							var original = $(this).find(".holder .animateTrophy:first")
							original.before(data.output[memberId]);
							
							original.animate({ 
								"left" : "600px"
							}, 
							750,"linear");
								
							original.prev().animate(
								{
									"left" : "0px"
								}, 750,"linear"
							);
							
							
						});
				});
			}
			else {
				$("#trophyCollection div.trophyColumn").each(function() {
					jQthis = $(this);
										
					var origCount = listCount - increment;
			
					var original = $(this).find(".holder .animateTrophy:eq("+origCount+")")
								
					original.animate({ 
						"left" : "600px"
					}, 
					750,"linear");
						
					original.prev().animate(
						{
							"left" : "0px"
						}, 750,"linear"
					);
					
					
				});
	
			}
		}
		//$("#trophyCollection").append(data.output);
		$("#trophyTimelineNav a").each(function() {
			$(this).attr('rel', increment);
		});
		
		var endDays = endDate.getDate();
		if(endDays < 10) {
			var endDays = '0'+endDays;	
		}
		var startDays = startDate.getDate();
		if(startDays < 10) {
			var startDays = '0'+startDays;	
		}
		
		var endMonth = endDate.getMonth()+1;
		var startMonth = startDate.getMonth()+1;
		
		if(startMonth < 10) {
			var startMonth = '0'+startMonth;	
		}
		
		if(endMonth < 10) {
			var endMonth = '0'+endMonth;	
		}
		
		
		$("#trophyTimelineNav .forwardTime").html(endDays+'-'+endMonth+'-'+endDate.getFullYear());
		$("#trophyTimelineNav .backTime").html(startDays+'-'+startMonth+'-'+startDate.getFullYear());
		return false;
		
	});
	
	/* Trophy icon changer */
	
	$("#trophyRightArrow").click(function() {
		jQthis = $(this);
		
		var current = $("#trophyIconList").find(".current");
		
		if (current.hasClass('last')) {
			var next = $("#trophyIconList li:first");	
		}
		else {
			var next = current.next();
		}
		
		newImgName = next.html();
		
		var where = jQthis.prev();
		var trophyLevel = 3;

		changeTrophyImg(newImgName, trophyLevel, where);
		
		current.removeClass('current');
		next.addClass('current');
	});
	
	// Left arrow
	$("#trophyLeftArrow").click(function() {
		jQthis = $(this);
		
		var current = $("#trophyIconList").find(".current");
		
		if (current.hasClass('first')) {
			var previous = $("#trophyIconList li:last");	
		}
		else {
			var previous = current.prev();
		}
		
		newImgName = previous.html();
		
		var trophyLevel = 3;
		var where = jQthis.next();
		
		changeTrophyImg(newImgName, trophyLevel, where);
				
		current.removeClass('current');
		previous.addClass('current');
	});
	
	$("#userAvatarScroll").imageScroll('', {list : '#userAvatarList', imgPath	: base_url+'img/avatars/', suffix : ''}, setAvatarField);
	
	
	/* Reward selection on todopopup */
	$("input.trophyForTodo").live('click', function() {
		$("#trophyInfo").toggleClass('hidden');
	});
	
	$("input.doneable").live('click', function() {
		$("#trophyInfo .trophyStickySelections").toggleClass('hidden');
	
	});
	
	/*Reward table navi */
	$(".trophyTableNavi li a").live('click', function() {
		var jQthis = $(this);
		var time = $(this).attr('rel');
		var thisClass = jQthis.attr('class');
		
		post("ajax/getpointstable", {
				fromThisTimeForward	:	time
					
			},  function(data) {
					$("#trophiesTableHolder").empty();
					$("#trophiesTableHolder").append(data.output);
					$(".trophyTableNavi li a").each(function(){
						$(this).removeClass('selected');	
					});
					$(".trophyTableNavi").find("."+thisClass+"").addClass('selected');
				});
		
		return false;
	});
	
	$("[name='sendEntry']").live('click', function() {
		hideModal();	
	});	
	
	/*Event commenting */
	$(".commentEvent").live('click', function() {
		jQthis = $(this);
		info = jQthis.attr('rel');
		eventInfo = info.split('-');
		$(".commentsForItem-"+eventInfo[1]).toggleClass('hidden');
		jQthis.parent().parent().parent().parent().find('.addComment').toggleClass('hidden');
		return false;
	});
	
	toolclick();
	
	
	/* Feed ajax updating */
	if (typeof(area) != "undefined" && area == "home") {
		$(".feedRefresh").live('mouseout', function() {
			refreshFeed(false, true);
		});	
	}
	
	/*--- KIDFINDER -- */
	
	$("[name='locate']").live('click', function() {
		id = $(this).parent().prev().find("[name='toLocate']").val();
		jQthis = $(this);
		jQthis.attr('disabled', 'true');
		var mapCanvas = $("#map");
		if(mapCanvas.find('.gmnoprint').length >0) {
			var loader = '<div class="mapLoaderBg" style="margin-top:190px;"><img src="'+base_url+'img/puhelinhukassa/search_loader.gif" id="kfLoaderImg" class="" /></div>';
			mapCanvas.html(loader);
		}
		else {
			mapCanvas.find('#kfLoaderImg').removeClass('hidden');
			mapCanvas.find('.mapStatus span:first').addClass('hidden');
			mapCanvas.find('.mapStatus span:last').removeClass('hidden');
		}
		
		var saunalahtiError = $("#saunalahtiNotice");
		if(saunalahtiError.length > 0) {
			saunalahtiError.remove();	
		}
		msg = $("#startMsg").html();
		addMessage("ack", msg, 0, "#systemMessageContainer");
		
		post("ajax/kidfinderlocation", {
				toLocate	:	id
					
			},  function(data) {
					
					mapCanvas.find('#kfLoaderImg').addClass('hidden');
					mapCanvas.find('.mapStatus span:first').removeClass('hidden');
					mapCanvas.find('.mapStatus span:last').addClass('hidden');
					jQthis.removeAttr('disabled');
					if(data.result == 1) {
						location.reload();	
						
					}
					else {
						jQthis.removeClass('hidden');
						jQthis.prev().addClass('hidden');
						addMessage("error", data.output, 0, "#systemMessageContainer");
						
					}
					//Saunalahti error
					if(data.result == -2) {
						var errorDiv = '<div id="saunalahtiNotice" style="margin: 8px 0; background-color:#fff1bb; color:#000; border: 2px solid #ff902d; font-size:12px; padding:10px; font-weight:bold;">'+
						'<span>'+data.additional+'</span> <a href="'+data.link+'" target="_blank">'+data.additional2+'</a></div>';
						console.log(errorDiv);
						$(".kidfinderContainer").prepend(errorDiv);
						
					}
					
				});
				
		
		return false;
	});
	
	/* Kidfinder Setup */
	
	$("#kfSetupTable input[name='addLocatee']").live('click', function() {
		var numberField = $(this).closest("tr").find("input[name='phoneNumber']");
		if(site_url.substr(-10, 10) !== "kidfinder/") {
			numCheck = numberField.val();
			var search = numCheck.search(/^\+/); 
			if(search === -1) {
				numCheck = false;	
			}
			 
		}
		else {	
			var numCheck = validateNumber(numberField.val());
		}
		if(!numCheck) {
			var errorText = $("#phoneError").text();
			addMessage("error", errorText, 0, "#systemMessageContainer");
			return false;
		}
		else {
			numberField.val(numCheck);
		}	
		return true;
		
	});
	
	/* Todo reminder sending */
	$("#icalExport").live('click', function() {
		jQthis = $(this);
		modalWindow(jQthis, "icalExport");
	});
	
	/* IcalExport popup */
	
	$("#icalExportView .cancelButton").click(function() {
		hideModal();
		return false;
	});
	
	$("#icalExportView #icalClick").click(function() {
		hideModal();
		
	});
	
	
	
	/* Feed Filter */
	$("#feedFilter input").live('click', function() {
		commentOpen = false; //just in case
		if($(this).attr('id') == "showFeedAll") {
			$("#feedFilterImg").removeClass('conversation');
			$("#feedFilterImg").addClass('all');
			$("#feedFilterImg").css('display', 'none');
			$("#feedFilterImg").fadeIn(750);
			theList = $("#presentToday").parent();
			theList.find("li.feedLine, li.ttl").each(function() {
		
				if($(this).hasClass('hidden') && ($(this).hasClass('ttl') && !$(this).next().hasClass('ttl') || !$(this).hasClass('ttl')) ) {
					$(this).removeClass('hidden');	
				}
		
			});
			
			
		}
		if($(this).attr('id') == "showFeedConversation") { //Show only notes, images and entries with comments
			$("#feedFilterImg").removeClass('all');
			$("#feedFilterImg").addClass('conversation');
			$("#feedFilterImg").css('display', 'none');
			$("#feedFilterImg").fadeIn(750);
			theList = $("#presentToday").parent();
			theList.find("li.feedLine").each(function() {
				jQthis = $(this);
			
				if (jQthis.hasClass('todo') || jQthis.hasClass('event') || jQthis.hasClass('system')) { //These we want to hide if they don't have comments
					var row = jQthis.find(".row");
					if(row.next().hasClass('addComment')) { //No comments here since they would show between row and addcomment
						jQthis.addClass('hidden'); //Let's hide the bastard
						//But what about the date delimiters?
						if(jQthis.next().hasClass('ttl')) { //This was the last feedline before datedelimiters
							looped = jQthis;
							if(looped.hasClass('hidden')) { //If this element has the class hidden, find out if previous has it as well
								var prevHidden = "hidden";	
								looped = looped.prev();
								while(prevHidden == "hidden") {
									if(looped.hasClass('hidden')) { //Loop until we find an element with no hidden class
										var prevHidden = "hidden";	
										looped = looped.prev();
									}
									else { //Found something that is not hidden
										if(looped.hasClass('ttl')) { //Is this a datedelimiter? If yes, lets hide it
											looped.addClass('hidden');
											
											
										}
										var prevHidden = "not";
									}
								}
							}
							
						}
					}
				}
			});
		}
	});
	
	/* Widgets Ajax Callbacks */
	/**
	* This is a wrapper function for Widgets to handle dynamic data. Read system/application/libraries/widgets.php for more instructions
	**/
	$(".widgetForm :submit").live('click', function() {
		submitButton = $(this);
		theForm = $(this).closest('.widgetForm');
		
		callBackFunction = theForm.find('.widgetCallBack').val();
			
		postFields = submitButton.attr('rel').split('-');
		
		//alert(postFields[0]);
		var data = {
			
		};
		
		for(var i in postFields) {
			postField = postFields[i];
			field = theForm.find('[name="'+postField+'"]');	
			data[postField] = field.val();
		}
		
		
		post("ajaxwidget/"+callBackFunction, data, 
				
		function(data) {
			
			if(data.result == 1) {
				submitButton.closest('.widget').replaceWith(data.additional);
				addMessage("ack", data.output, 0, "#systemMessageContainer");
			}
			else {
				
				
			}
			
		});

//		alert(callBackFunction);
		return false;
	
	});
	
	/* Other Widget Stuff */
	
	$(".toggleHiddenNext").live('click', function() {
		$(this).next().toggleClass('hidden');
		return false;
	});
	
	$(".widgetHeading").each(function() {
		//$(this).append('<a href="#" class="widgetCloseBg"><div class="widgetClose up"></div></a>');
	});
	
	$(".widgetClose").live('click', function() {
		$(this).toggleClass('closed');
		var widget = $(this).parent().parent().parent();
		
		widget.find('.widgetContent').slideToggle('slow');
		
		var params = {};
		if($(this).hasClass('closed')) {
			params.status = 'closed';	
		}
		else {
			params.status = 'open';	
		}
		var widId = widget.attr('class').split('-');
		params.identifier = widId[1];
		params.type = 'widget_status';
		post('ajax/addPreference', params, function(data) {
			//alert('posted');
		});
		return false;
	});
	
	$(".widgetSlotToggle").click(function() {
		jQthis = $(this);
		jQthis.find('li').each(function() {
			$(this).toggleClass('hidden');
		});
		var statusDiv = jQthis.find('div');
		statusDiv.toggleClass('closed');
		jQthis.next().slideToggle();
		
		var params = {};
		if(statusDiv.hasClass('closed')) {
			params.status = 'closed';	
		}
		else {
			params.status = 'open';	
		}
		
		params.identifier = jQthis.attr('rel');
		params.type = 'widget_slot_status';
		post('ajax/addPreference', params, function(data) {
			//alert('posted');
		});
		return false;

	});
	
	/* Recommend to Friend */
	$(".recommendLink").click(function() {
		$(".tellToSender").next().addClass('hidden');
		
		post("ajaxwidget/getFbRegisterLink/", false, 
			
			function(data) {
				if(data.result == 1) {
				
					$(".fbJoinLink").attr('rel', data.output);
						
				}
			});
		
		modalWindow($(this), "tellToFriend");
		
		
		$(".fbJoinLink").unbind('click');
			//Bind the triggers
			
		$(".fbJoinLink").click(function() {
			clickTrack($(this));
			var url = $(this).attr('rel');
			window.open(url, 'fb_tell', 'width=400, height=400');
			hideModal();
			return false;
		});
		
		$("[name='tellToMail']").unbind('click.submitClick'); //unbind previous
			$("[name='tellToMail']").bind('click.submitClick', function() {
				
					jQthis = $(this);
					jQthis.addClass("hidden");
					jQthis.prev().removeClass("hidden");
					
					var email_to = $(".tellTo").val();
					var sender = $(".tellToSender").val();
					
					if(sender == '') {
						$(".tellToSender").next().removeClass('hidden');
						jQthis.removeClass("hidden");
						jQthis.prev().addClass("hidden");
						return false;	
					}
					
					post("ajax/sendEmail/email_recommend", {
						email_to 	: email_to,
						sender		: sender
						
					}, function(data) {
						if(data.result == 1) {
							addMessage("ack", data.systemMessages.ack, 0, "#systemMessageContainer");
						}
						else {
							addMessage("notify", data.systemMessages.error, 0, "#systemMessageContainer");
						}
					}
				);
				
				$(".tellTo").val("");
				$(".tellToSender").val("");
				jQthis.removeClass("hidden");
				jQthis.prev().addClass("hidden");

				
				hideModal();
				return false;
			});

		
		
		return false;
	});
	
	/* Calendar Sharing */
	$(".calendarShareLink").click(function() {
		modalWindow($(this), "calShare");
		$("[name='shareCalSubmit']").unbind('click.shareCalClick'); //unbind previous
		$("[name='calShareFree']").unbind('keyup.shareCalKeyup'); //unbind previous
		$("#calShareView .shareCalSender").unbind('keyup.shareCalSenderKeyup'); //unbind previous
		
		$("#calShareView .shareCalSender").bind('keyup.shareCalSenderKeyup', function() {
			var senderName = $(this).val();
			$("#calShareView span.mailSender").text(senderName);
		}); 
		
		$("[name='calShareFree']").bind('keyup.shareCalKeyup', function() {
			var freeText = $(this).val();
			freeText = strip_html_tags(freeText);
			$("#calShareView p.mailFree").html(freeText);
		}); 

		$("[name='shareCalSubmit']").bind('click.shareCalClick', function() {
			jQthis = $(this);
			jQthis.addClass("hidden");
			jQthis.prev().removeClass("hidden");
			
			var email_to = $(".shareCalTo").val();
			var sender = $(".shareCalSender").val();
			var free = $("#calShareView [name='calShareFree']").val();
			if(free == '') {
				free = false;	
			}
			if(sender == '') {
				$(".shareCalSender").next().removeClass('hidden');
				jQthis.removeClass("hidden");
				jQthis.prev().addClass("hidden");
				return false;	
			}
			
			post("ajax/sendEmail/email_share_calendar", {
				email_to 	: email_to,
				sender		: sender,
				freeText	: free
				
				}, function(data) {
					if(data.result == 1) {
						addMessage("ack", data.systemMessages.ack, 0, "#systemMessageContainer");
					}
					else {
						addMessage("notify", data.systemMessages.error, 0, "#systemMessageContainer");
					}
				}
			);
			
			$(".shareCalTo").val("");
			$(".shareCalSender").val("");
			jQthis.removeClass("hidden");
			jQthis.prev().addClass("hidden");
	
			
			hideModal();
			return false;
		});
	});

	
	/* Welcome message binds */
	$("#welcomeMessage .addTodo a").click(function() {
	
		$("#addTodoPopupView .deleteButton").addClass("hidden");
		resetFeedPosting("todo");
		resetTodoTrophy();
		$("#todo-entryId").val("");
		popupWindow($(this), "addTodoPopup");
		$("#postTypeHolder").val("todo");
		$("#todoPopupTable input").each(function() {
			$(this).attr('checked', false);
			$(this).trigger('click');
		});
		
		return false;
	});

	
		// Bind click-tags
	$(".clickTrack").click(function() {
		clickTrack($(this));
	});	
	
	/**
	* User locations query
	**/
	if(typeof(area) != "undefined" && area == "locations") {
		setTimeout("refreshLocations()", 5000);
		setTimeout("clock('', '#locationDashboard #locationClock')", 1000);
		
		//refreshLocations();
	}
	
	if(typeof(area) != "undefined" && area == "locations_demo") {
		var demo = new location_animation(7, 10);
		var today = new Date();
		var startTime = Math.round(new Date(today.getFullYear(), today.getMonth(), today.getDate(), '00', '00', '00').getTime()/1000);
		var endTime = startTime+86400;
		
		get('ajax/getLocationsForPeriod/'+startTime+'/'+endTime, false, function(data) {
			
			if(data.result == 1) {
				var animation = {};
				animation.frames = {};
				animation.speed = 2;
				for(var i in data.output) {
					var animData = data.output[i];
					var animTime = new Date(animData.timestamp*1000);
					
					var hours = animTime.getHours();
					var minutes = animTime.getMinutes();
					
					if(hours < 10) {
						hours = '0'+hours;	
					}
					if(minutes < 10) {
						minutes = '0'+minutes;	
					}	
					
					var animTime = hours+':'+minutes;
					
					animation.frames[animTime] = {};
					animation.frames[animTime][animData.user_id] = {
						
							'check_type' : animData.check_type,
							'location_type' : parseInt(animData.location_type),
							'name' : animData.name	
					}
							
						
				}
				
				
			}
			else {
				var animation = {
					'speed' : 10, // minutes/second
					'frames' : {
						'07:25' : {
							'21' : {
								'check_type' : 'checkout',
								'location_type' : 0,
								'name' : 'Koti'	
							}	
						},	
						'09:30' : {
							'23' : {
								'check_type' : 'checkout',
								'location_type' : 0,
								'name' : 'Koti'
							},
							'22' : {
								'check_type' : 'checkout',
								'location_type' : 0, 
								'name' : 'Koti'
							}
						},
						'09:55' : {
							'23' : {
								'check_type' : 'checkin',
								'location_type' : 1,
								'name' : 'Work'
							}
							
						},
						'10:15' : {
							'22' : {
								'check_type' : 'checkin',
								'location_type' : 2,
								'name' : 'Robert\'s Coffee'
							}
							
						},
						'10:30' : {
							'22' : {
								'check_type' : 'checkout',
								'location_type' : 2,
								'name' : 'Robert\'s Coffee'
							}
							
						},
						'11:05' : {
							'22' : {
								'check_type' : 'checkin',
								'location_type' : 1,
								'name' : 'Work'
							}
							
						},
						'11:30' : {
							'21' : {
								'check_type' : 'checkin',
								'location_type' : 1,
								'name' : 'Work'	
							}	
						},
						'15:30' : {
							'21' : {
								'check_type' : 'checkout',
								'location_type' : 1,
								'name' : 'Work'	
							}	
						}		
					}

				}
			}
				
			
			demo.begin(animation);
		});
			
			
		
		$("#play").click(function() {
			if($(this).hasClass('pause')) {
				demo.pause();
				
			}
			else {
				demo.play();
					
			}	
			$(this).toggleClass('pause');
		});
	}
	
	

});
/* ------- end - document.ready ------- */

/* Feed refreshing magic */

function refreshFeed(timeDiff, removeOld, forceRefresh) {
	if(typeof(timeDiff) == "undefined" || timeDiff === false) {
		timeDiff = 5;	
	}
	if(typeof(removeOld) == "undefined") {
		removeOld = false;	
	}
	
	if(typeof(forceRefresh) == "undefined") {
		forceRefresh = false;	
	}
	
	if(commentOpen === false || forceRefresh) {

		var lastRead = $("#lastReadHolder").html();
		var now = new Date();
		var now = now.getTime();
		var now = now/1000;
		var now = Math.round(now);
		
		if ((now - lastRead) > timeDiff || forceRefresh) {
			//Dont try to refresh while post is on the way
			commentOpen = true;
			post("ajax/getFeedChanges", {
				lastRead	: lastRead
				
				
			},  function(data) {
					
				$("#lastReadHolder").html(data.additional);
				
				if (data.result == 1) {
					for(var i in data.output) {
						if (removeOld) {
							var entryId = data.output[i].target_id;
							
							toRemove = $(".feedLine.entry-"+entryId);
							if(toRemove.length > 0) {
																	
									postToTop(data.output[i].content, 1, toRemove);
									
								
							}
							else {
								postToTop(data.output[i].content, 1);
							}
						}
						
						else {
							postToTop(data.output[i].content, 1);
						}
							
					}
					if(typeof(data.todos) !== "undefined") {
						$("#content .todoList").html(data.todos);
					}
					resetFacebookCounter();
				}
				
				commentOpen = false;
			});		
		}
	}
	
}

/* location refresh */
function refreshLocations() {
	var timestamp = $("#lastReadHolder").html();
	$("#locationDashboard .locationDiv").each(function() {
		$(this).removeClass('recent');
	});

	get('ajax/getlocationchanges/'+fid+'/'+timestamp, false, function(data) {
		if(data.result == 1) {
			//Modify the css classes etc
			for(var i in data.output) {
				locType = "";
				labelDir = "";
				labelClass = "";
				var uid = data.output[i].user_id;
				var locRow = $("#locationDashboard #locationRow"+uid+" .locationCenter span");
				locRow.empty();
				var checkType = data.output[i].check_type;

				switch(data.output[i].location_type) {
					case "0":
						labelClass = 'home';
						if(checkType == 'checkout') {
							locType = 'locationCenter';
							labelDir = 'right';
						}
						else {
							locType = 'locationHome';
							labelDir = 'left';
						}
					
					break;
					case "1":
						labelClass = 'work';
						if(checkType == 'checkout') {
							locType = 'locationCenter';
							labelDir = 'left';
						}
						else {
							locType = 'locationWork';
							labelDir = 'right';
						}
					break;
					default:
					//@todo Make this work below in html-parsing
						locType = 'locationCenter';
						
						if(checkType == 'checkin') {
							if(data.output[i].name.length > 8) {
								locRow.addClass('shrink');
							} 
							else {
								locRow.removeClass('shrink');	
							}
							locRow.html(data.output[i].name);
						}
						
					break;
				}
				var uid = data.output[i].user_id;
				$("#locationDashboard #locationRow"+uid+" .locationDiv").each(function() {
					$(this).removeClass('active');
					if($(this).hasClass(locType)) {
						$(this).addClass('active').addClass('recent');	
					}
				});
				
				// Adjust the time labels
				var newDate = new Date(data.output[i].timestamp*1000);
				var hours = newDate.getHours();
				var minutes = newDate.getMinutes();
				if(hours < 10) {
					hours = "0"+hours;	
				}
				if(minutes < 10) {
					minutes = "0"+minutes;	
				}
				var label = $("#locationDashboard #locationRow"+uid+" .locationLabel");
				
				if(label.length > 0) {
					if(labelClass == "") {
						label.remove();	
					}
					else {
						label.replaceWith('<div class="locationLabel '+labelClass+' '+labelDir+'">'+hours+':'+minutes+'</div>');
					}
				}
				else {
					if(labelClass != "") {
						$("#locationDashboard #locationRow"+uid).append('<div class="locationLabel '+labelClass+' '+labelDir+'">'+hours+':'+minutes+'</div>');
					}
				}

			
			}
			$("#lastReadHolder").html(data.additional);	
		}
		if(area == "locations") {
			setTimeout("refreshLocations()", 10000);
		}
	});
}

/* insert post to top below input bar */
function postToTop(output, fade, toRemove) {
	
	if (typeof(fade) == 'undefined') {
		fade = false;	
	}
	if (typeof(toRemove) == 'undefined') {
		toRemove = false;	
	}
	if(fade) {
		if (toRemove) {
			$(toRemove).fadeOut(750, function() {
				if($(toRemove).parent().hasClass('feedLineRefresh')) {
					$(toRemove).parent().remove();
				}
				
				else {
					$(toRemove).remove();	
				}
			
			
				var content = "<div style='display:none;' class='feedLineRefresh'>"+output+"</div>";
			
				if($("#presentToday").hasClass("hidden")) {
					$("#presentToday").removeClass("hidden");
					
					$(content).insertAfter("#presentToday");
				}
				else {
					$(content).insertAfter("#presentToday");
				}
				$("#presentToday").next().fadeIn(750, function() {
					openFull(); //for imgs to work	
				});
			});
		}
		else {
			var content = "<div style='display:none;' class='feedLineRefresh'>"+output+"</div>";
			if($("#presentToday").hasClass("hidden")) {
				$("#presentToday").removeClass("hidden");
				
				$(content).insertAfter("#presentToday");
			}
			else {
				$(content).insertAfter("#presentToday");
			}
			$("#presentToday").next().fadeIn(750, function() {
					openFull(); //for imgs to work	
				});

		}
	}
	else {
		if($("#presentToday").hasClass("hidden")) {
			$("#presentToday").removeClass("hidden");
			$(output).insertAfter("#presentToday");
		}
		else {
			$(output).insertAfter("#presentToday");
		}
	}
	return true;
}

function validateNumber(number) {

    var numlen = number.length;

    var pattern = /^\+?[0-9]+$/;
    if(numlen > 13 || numlen < 7 || number.search(pattern) == -1 ) {
    	
        return false;
    } else {
        if (numlen < 11) {
		number = "+358" + number.substring(1);
 }
        return number; 
    }
}

function clickTrack(elem) {
	var elemName = elem.attr('name');
	var data = {
		clickedElem	:	elemName	
	};
	//We want to be able to track with no session, thus to ajaxwidget and not ajax controller
	post("ajaxwidget/clicktrack", data, 
				
		function(data) {
			
			
			
		});

		
}

/* JS clock, yippee */
function clock(lastTime, selector) {
	//console.log('tick');
	var curTime = new Date();
	var hours = curTime.getHours();
	var minutes = curTime.getMinutes();
	
	if(hours < 10) {
		hours = "0"+hours;	
	}
	if(minutes < 10) {
		minutes = "0"+minutes;	
	}
	
	var newTime = hours+':'+minutes;
	
	if(lastTime !== newTime) {
		$(selector).html(newTime);	
	}
		setTimeout('clock("'+newTime+'", "'+selector+'")', 1000);
	
}


function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

/**
* Validates time input for anytimepicker 
* @param str time
* @return valid time string (nn:nn) if valid, false if not
*/

function validateTime(time) {
	/* Check whether time input is correct */
	var toCheck = /^[0-9]{1,2}([:. ][0-9]{1,2})?$/ig;
	if(!time.match(toCheck)) {
	
		return false;
	}
	
	var minCheck = /[:. ][0-9]{1,2}$/ig;

	if(!time.match(minCheck)) {
		time = time+":00";
	}
	else {
		time = time.replace(/[. ]/gi, ":");
	}
	return time;
}

/**
* Validates date input for datepicker 
* @param str date
* @return correctly formatted date if valid, false if not
*/

function validateDate(date) {
	var returnDate = date.replace(/[.]/gi, "/");
	return returnDate;
}


/* Points progress bar */	
function animateProgress(jQthis) {
	width = jQthis.css('width');
	jQthis.css('width', 0);
	jQthis.animate({
		width : width
	}, 1500
	); 
	
}

/*
 For reseting event popup
 */

function resetPopup() {
	$(".eventIcons .icon-calendar").trigger("click");
	$("#event-textField").val("");
	$("[name='location']").val("");
	$("[name='repeat']").val("none");
	$("[name='repeat']").attr("disabled", false);
	$(".untilSelect").addClass('hidden');
	$(".fullDay").attr('checked', false);
	$("#postStartTime").removeClass("hidden");
	$("#postEndTime").removeClass("hidden");
	$("[name='endDate']").removeClass("hidden");
	$("#addEventPopupView .tabs [rel='eventPopupMain']").trigger("click");
	$("#addEventPopupView .eventMobileSelection input[type='checkbox']").removeAttr('checked');
	$('#addEventPopupView [name="alarmBefore"] option[value="none"]').attr('selected', true);
	$('#addEventPopupView #alarmSelectTime option[value="0"]').attr('selected', true);
	//set default times
	var currentTime = new Date();
	var hours = currentTime.getHours()+1;
	var endHours = currentTime.getHours()+2;
	var minutes = "00";
	
	if (hours < 10){
		hours = "0" + hours;
	}
	if (endHours < 10) {
		endHours = "0" + endHours;	
	}
	
	if (hours > 24) {
		var diff = hours - 24;
		hours = "0" + diff;
	}
	
	if (endHours > 24) {
		var diff = endHours - 24;
		endHours = "0" + diff;
	}

	$("#postStartTime").val(hours+':'+minutes);
	$("#postEndTime").val(endHours+':'+minutes);
	
	$("[name='endTime']").removeClass('errorBorder');	
	$("[name='startTime']").removeClass('errorBorder');
	
	//remove checkbox selections
	$(".memberId").each(function() {
		if ($(this).val() !== uid) {
			$(this).attr('checked', false);
		}
	});
			
	$(".mobileReminderBox").each(function() {
		$(this).attr('checked', false);
	});
}

function resetFeedPosting (feedType) {
	hidePopup();
	$("."+feedType+"MemberSelection .memberId").each(function() {
		if ($(this).val() !== uid) {
			$(this).attr('checked', false);
		}
	});
	$("#"+feedType+"-entryId").val("");
	$(".doneable").attr('checked', false);
	$("#postTypeHolder").val("note");
	
	var textField = $("#"+feedType+"-textField");
	textField.val("");
	textField.height(28);
	textField.updateHeight('destroy');

}

function countChecked() {
      var n = $(".eventMobileSelection input:checked").length;
      return n;
}
   
function changeCalDate(realdate) {
		$(".calendarStreamUl").empty();
		$(".calAjaxLoader").removeClass("hidden");
		var thedate = realdate;
		$("#dateHolder").val(thedate);
		post("ajax/calendar/", {
			thedate : thedate
			}, function(data) {
				//$(".calendarStream").append(data.output);	
				$(".calendarStreamUl").empty();
				$(".calAjaxLoader").addClass("hidden");
				$(".calendarStreamUl").append(data.output);
				$("input[type=file].multi").MultiFile();
				openFull();
				for (var i in data.eventDates) {
					thisDate = data.eventDates[i];	
					
					$("[title='"+thisDate+"']").addClass("hasEvents");
				}
			});
	
		
	
}
//hide previous confirm dialogs
function hideConfirms() {
	$("#modalWindow .confirm").each(		
			function(e) {
				if(!$(this).hasClass('hidden')){
					$(this).addClass('hidden');
				}
			}
	); 
}

//hide modal window
function hideModal() {
	 $("#modalWindow").addClass('hidden');
	 $(".modalview").addClass('hidden');
	 
	 $("#modalOverlay").fadeTo(500, 0);
	 window.setTimeout(function() { $("#modalOverlay").addClass('hidden')}, 500);
}

//hide popup window
function hidePopup() {
	 $("#popupWindow").addClass('hidden');
	 $(".popupview").addClass('hidden');
	 
	 $("#modalOverlay").fadeTo(500, 0);
	 window.setTimeout(function() { $("#modalOverlay").addClass('hidden')}, 500);
}
//hide previous confirm dialogs
function showConfirm(selector) {
	
		if(selector.hasClass('hidden')){
			selector.removeClass('hidden');
		}

}




//Popup modals!
/* hides and shows popup window */
function togglePopup(objClass) {
	$("#popupWindow").toggleClass("hidden");
	$("#popupWindow").find("#" + objClass + "View").toggleClass("hidden");
}

/* popup window main function */
function popupWindow(jQthis, objClass) {
	var docHeight = document.body.scrollTop;
	if(!docHeight) {
		var top = parseFloat(document.documentElement.scrollTop);
	}
	else {
	  var top = parseFloat(docHeight);
	}
	 top = top+50;
	 $("#popupWindow").css('top', top).removeClass('hidden');

     $("#" + objClass + "View").removeClass('hidden');
    
     $("#modalOverlay").removeClass('hidden');
     $("#modalOverlay").fadeTo(0, 0.3);
}

function deleteEntry(entryId, eventId, eventDate, toDelete, clickedElement) {
		post("ajax/stream_modify/deleteentry", {
			msgId		: entryId,
			eventId 	: eventId,
			eventDate 	: eventDate,
			toDelete	: toDelete
		}, function(data) {
			
			if(data.result == 1) {
				
				if(data.entryType == "todo") {
					$(".todoList").empty();
					$(".todoList").append(data.additional);
				}
				

				if(toDelete == "all") {
					removeEntries($(".future.event-"+eventId));
				}
				if(toDelete == "this" && clickedElement !== null) {
					removeEntries(clickedElement);
				}
					/*if($(jQthis).parents("li").hasClass("future")) {
						$(jQthis).parents("li:first").remove();
						
					}*/
						
				removeEntries($(".past.entry-" + entryId));

				/*if($(jQthis).parents("li").hasClass("note") || $(jQthis).parents("li").hasClass("image")) {
					$(jQthis).parents("li:first").remove();
					if($("#presentToday").next($(this).hasClass(".ttl"))) {
						$("#presentToday").addClass("hidden");
					}
				}*/
				if(data.entryType == "image" || data.entryType == "note") {
					//removeEntries($(".entry-" + entryId));
					if($("#presentToday").next().hasClass("ttl")) {
						$("#presentToday").addClass("hidden");						
					}
					$(".entry-" + entryId).remove();
				}
				else {		
					if(area == "home") {

						if(data.output !== false) {
							postToTop(data.output);
						}
					}
					else {
						location.reload();
					}
					
					/*$(data.output).insertAfter($(jQthis).parents("li")); // replaces an entry in the feed
					$(jQthis).parents("li").remove(); */
				}
				
				setClassFirst();
			}
			
			hideModal();
			
			return;
		});
	}		

/* edit calendar event */
function editCalendarEvent(eventId, entryId, eventStart, what) {
	
	if(what == "this") {
		eventId = $('#eventId').val();
		entryId = $('#entryId').val();
		eventStart = eventStart;
	}
	if(what == "all") {
		eventId = $('#eventId').val();
		entryId = null;
		eventStart = null;
	}

	post("ajax/get/event", {
		eventId		: eventId,
		msgId 		: entryId,
		eventStart 	: eventStart
		
	},  function(data) {
			var objects 		= data.additional; // list of id's of users who are objects of the event
			var content 		= data.output.content; // event content
			var startDate 		= data.output.startDate;
			var endDate			= data.output.endDate;
			var startTime		= data.output.startTime;
			var endTime			= data.output.endTime;
			var repeat			= data.output.repeat;
			var until			= data.output.until;
			var eventId			= data.output.eventId;
			var reminderObjects = data.reminderObjects;
			var badge 			= data.output.event_badge;
			var location 		= data.output.location;
			var reminderWhen 	= data.reminderWhen;
			var alarm 			= data.output.alarm;
			var alarmBefore		= data.output.alarm_before;
			//This is currently always same for start & end
			switch(alarmBefore) {
				case "start":
					var alarmOffset		= data.output.alarm_offset_start;
				break;
				
				case "end":
					var alarmOffset		= data.output.alarm_offset_end;
				break;
				
				case "both":
					var alarmOffset		= data.output.alarm_offset_start;
				break;	
			}
			
	
			switch(reminderWhen) {
				case "event_start":
					reminderWhen = "start";
				break;	
				case "event_end":
					reminderWhen = "end";
				break;
			}
			
			
			$("#addEventPopupView .tabs [rel='eventPopupMain']").trigger("click");
			$("#addEventPopupView .eventIconSelector").trigger("click");
			$("#addEventPopupView .eventIcons ."+badge+"").trigger("click");
					
			$("#addEventPopupView .memberId").each(function() {
				$(this).attr('checked', false);
			});
			
			$("#addEventPopupView .eventForAll").attr('checked', false);
			
			
			$("#addEventPopupView .mobileReminderBox").each(function() {
				$(this).attr('checked', false);
			});
			
			if (objects[0] == 'all') {
				$("#addEventPopupView .eventForAll").attr('checked', true);
	
			}
			else {
				// populate event objects
				for(var i = 0; i < objects.length; i++) {		
					var user = objects[i];
					$("#addEventPopupView .eventMemberSelection .memberId[value=\'"+user+"\']").attr('checked', true);
					
				}
			}
			//Reset these first
			$('#addEventPopupView [name="mobile-sendBefore"] option[value="none"]').attr('selected', true);
			$('#addEventPopupView [name="alarmBefore"] option[value="none"]').attr('selected', true);
			$('#addEventPopupView #alarmSelectTime option[value="0"]').attr('selected', true);
			//Set the alarm selection
			if(alarm == 1) {
				$('#addEventPopupView select[name="alarmBefore"] option[value="'+alarmBefore+'"]').attr('selected', true);
				var alarmMin = alarmOffset/60;
				$('#addEventPopupView #alarmSelectTime option[value="'+alarmMin+'"]').attr('selected', true);
			}
			
			if(data.reminderObjects.length > 0) {
				// populate event reminder objects
				for(var i = 0; i < reminderObjects.length; i++) {		
					var user = reminderObjects[i];
					
					$("#addEventPopupView .mobileReminderBox[value=\'"+user+"\']").attr('checked', true);
				} 
				$('#addEventPopupView [name="mobile-sendBefore"] option[value="'+reminderWhen+'"]').attr('selected', true);
				$('#addEventPopupView [name="mobile-sendTime"] option[value="'+data.reminderOffset+'"]').attr('selected', true);
			}

			$("#addEventPopupView [name='startDate']").val(startDate);
			$("#addEventPopupView [name='startTime']").val(startTime);
			$("#addEventPopupView [name='endDate']").val(endDate);
			$("#addEventPopupView [name='endTime']").val(endTime);
			$("#addEventPopupView [name='forTime']").val(until);
			$("#addEventPopupView [name='location']").val(location);
			
			// if we want to edit one occurrance of an event, hide until selector
			if(eventStart > 0 && repeat != "yearly" && repeat != "none") {
				$("#addEventPopupView [name='repeat']").val(repeat);
				$("#addEventPopupView [name='repeat']").attr("disabled","disabled");
				$("#addEventPopupView .untilSelect").addClass('hidden');
				
			}
			else {
				$("#addEventPopupView [name='repeat']").val(repeat);
				$("#addEventPopupView [name='repeat']").attr("disabled","");
				if(repeat != "none") {
					$("#addEventPopupView .untilSelect").removeClass('hidden');
				}
			}
			/*
			if(data.reminderObjects.length > 0) {
				$(".selectTime").attr("disabled","");
				$(".selectBefore").attr("disabled","");
				$(".mobileTime span").removeClass("grey");
			}
			else {
				
				
				//$(".mobileTime :input").attr("disabled", "disabled");	
				//$(".mobileTime span").addClass("grey");
			}
			*/
			if(repeat == "yearly") {
				$("#addEventPopupView .untilSelect").addClass('hidden');
			}
			
			if (startTime == "00:00" && endTime == "23:59") {
				$("#addEventPopupView .fullDay").trigger("click");	
			}
			
			$('#entryId').val(entryId);
			$('#eventId').val(eventId);
			$('#eventStart').val(eventStart);
			
			popupWindow($(this), "addEventPopup");
			if (content) {
				$("#event-textField").val(content);
			}
			else {
				$("#event-textField").val("");	
			}
		
						
	}); 
}

/* Reset image posting */
function resetImagePosting() {
	$(".MultiFile-label a").each(function() {
		$(this).trigger("click");	
	});
		
}
/* updates the classes to the list */
function setClassFirst() {
	$(".list.present").find("li").each(function() {
		$(this).removeClass("first");
	});
	$(".list.present").find(".ttl").next("li").each(function() {
		$(this).addClass("first");
	});
}

/* zebra-stribes */
function zebra(jQthis) {
	var feedline = $(jQthis).parents("li:first");
	$(feedline).find(".bubble").removeClass("even odd");
	$(feedline).find(".bubble:not('.hidden'):odd").addClass("even");
	$(feedline).find(".bubble:not('.hidden'):even").addClass("odd");
}


/* tooltip-magic */
function tooltip(target) {
	// unbinds the tooltip just in case
	$("."+target+"").unbind();

	// tooltip magic
	$("."+target+"").live("mouseover mouseout",
		function(e) {
			if (e.type == 'mouseover') {
			// gets the texts from elements rel attribute
			var getRel = $(this).attr("rel");
			// replace & wtih &amp;
			getRel = getRel.replace(/&/gi,"&amp;");			
			// makes the div#tooltip visible
			$("#"+target+"").removeClass("hidden").html("<p>" + getRel + "</p>").css("top", (e.pageY+10) + "px").css("left", (e.pageX+10) + "px");
			}
			else {
				$("#"+target+"").addClass("hidden");
			}
		});

	// moves the tooltip along with mouse
	$("."+target+"").mousemove(function(e) {
		$("#"+target+"").css("top", (e.pageY+10) + "px").css("left", (e.pageX+10) + "px");
	});	
}



/* toolclick-magic */
function toolclick() {
	$(".toolclick").live("click", function(e) {
		var getRel = $(this).attr("rel");
		getRel = getRel.replace(/&/gi,"&amp;");
		
		if($(this).hasClass("clicked")) {
			$(".clicked").removeClass("clicked");
			if($("#toolclick:visible")) {
				$("#toolclick").addClass("hidden").html("<p>" + getRel + "</p>").css("top",(e.pageY+10) + "px").css("left",(e.pageX-33) + "px");
			}
		}
		else {
			$(".clicked").removeClass("clicked");
			$(this).addClass("clicked");
			if($("#toolclick:visible")) {
				$("#toolclick").removeClass("hidden").html("<p>" + getRel + "</p>").css("top",(e.pageY+10) + "px").css("left",(e.pageX-33) + "px");
			}
		}	
		return false;
	});
}

/* fancybox */
function openFull() {
	$("a.openFull").fancybox();	
	
	$(".iframe").fancybox({
		"overlayShow"	: false,
		"overlayOpacity" : 0
	});	
}

function helpWindow() {
	$("a.helpWindow").fancybox({
		'showNavArrows' : true,
		'showCloseButton' : true,
		'overlayOpacity' : 0.8,
		'titleShow' : true,
		'titleFormat' : formatTitle,
		'titlePosition' : 'inside'
	});
}	

function formatTitle(title, currentArray, currentIndex, currentOpts) {
    return '<div">' + (title && title.length ? '<b>' + title + '</b> - ' : '' ) + '(' + (currentIndex + 1) + '/' + currentArray.length + ')</div>';
}

function showComments() {
	$(".entryComments").removeClass('hidden');
	
	$("em.eventCutterDots").remove();
	$("span.eventCutter").each(function() {
		
		$(this).after($(this).html());
		$(this).remove();
	});
}

function removeEntries(selector) {
	$(selector).each( 	
			function(index) {
				var el = $(this);				
				if(el.prev().attr('id') != "presentToday") {
					// if there's a date deloimiter before and after the element
					// or if the entry is right above the input bar 
					if((el.prev().hasClass('ttl') && el.next().hasClass('ttl')) || (el.next().attr('class') === null && el.prev().hasClass('ttl'))) {
						el.prev().remove();
					}
				}
				el.remove();
			}
	);
}

/* fadeout and remove element */
function fadeOutRemove(elem) {
	$(elem).fadeOut(1000, function() {
		$(elem).remove();
	});
}

/* hides and shows modal window */
function toggleModal(objClass) {
	$("#modalWindow").toggleClass("hidden");
	$("#modalWindow").find("#" + objClass + "View").toggleClass("hidden");
	$("#modalOverlay").removeClass('hidden');
     $("#modalOverlay").fadeTo(0, 0.3);
}

/* modal window main function */
function modalWindow(jQthis, objClass) {
	
	 $("#modalWindow").removeClass('hidden');
     $("#" + objClass + "View").removeClass('hidden');
    
     $("#modalOverlay").removeClass('hidden');
     $("#modalOverlay").fadeTo(0, 0.3);
   }

/* Form checks */
function checkForm(selector) {
	/* form ajax checks */
	formErrors = new Array();
	
	if(selector == "#registrationForm") {
		//Initialize the timezone selection check
		jQthis = $("#country");
		var field = jQthis.attr('name');
		var value = jQthis.val();
		var fieldName = field;
		/*Setup the post variable*/
		data = {};
		data['form'] = selector;
		data[fieldName] = value;
				
		/* Check if we can choose the timezone for the selected country or if we need to show timezone selector */
		post("register/formAjaxCheck/"+field, data,  
				
			function(data) {
				if (data.result == 1) {
					
					$("#timezone :selected").removeAttr("selected");
					$("#timezone option[value='"+data.output+"']").attr("selected", "selected");
					
				}
			else {
				$(".formguide.timezone span").empty();
				$(".formguide.timezone span").append(data.output);
				$(".formguide.timezone span").removeClass('hidden');
				$("#timezoneContainer").removeClass('hidden');
			}
		});
	}
	$(selector+" .birthdaySelector select").each(
			function() {
				$(this).focus(function() { //Show red
					jQthis = $(this);
					errorImg = jQthis.parent().find(".error");
					errorImg.removeClass("hidden");
					errorImg.prev().addClass("hidden");
					$(".formguide.birthday span").removeClass("hidden");
				});
				$(this).bind('change', function() {
					jQthis = $(this);
					errorImg = jQthis.parent().find(".error");
					
					var empty = false;
					$(selector+" .birthdaySelector select").each(
							function(e) {
							
								if($(this).val() === "") {
									empty = true;
								} 
								
					});
					
					if(!empty) { // If values chosen, do birthday checks
						
						
						post("register/ajaxcheck/birthday", {
							day		: $('#birthday_day').val(),
							month	: $('#birthday_month').val(),
							year	: $('#birthday_year').val(),
							form	: selector
						}, function(data) {
							
							if(data.result == -1) { // Error
								errorImg = $(".birthdaySelector").find(".error");
								errorImg.removeClass("hidden");
								errorImg.prev().addClass("hidden");
								$(".formguide.birthday span").removeClass("hidden");
								$(".formguide.birthday span").empty();
								$(".formguide.birthday span").append(data.output);
								$(".formguide.birthday span").addClass('errorMsg');
								formErrors['birthday'] = data.output; //form wont submit
								
							}
							else {
								
								$(".formguide.birthday span").empty();
								$(".formguide.birthday span").removeClass('errorMsg');
								
								
								if (data.result == 2) { //Show warning, no error
									$(".formguide.birthday span").append(data.output);
									
									toggleLoginFields("no");
									$("#allow_offers").attr('checked', false);
										
								}
								else {
									toggleLoginFields("allow");	
								}
								errorImg = $(".birthdaySelector").find(".error");
								errorImg.addClass("hidden");
								errorImg.prev().removeClass("hidden");
								
								if (typeof(formErrors['birthday']) != "undefined") {
									delete formErrors['birthday'];	
								}
							}
						});
					}
				});
				$(this).focusout(function() {
					jQthis = $(this);
					errorImg = jQthis.parent().find(".error");
					
					if (!($(".formguide.birthday span").hasClass('errorMsg'))) {
						$(".formguide.birthday span").addClass("hidden");
						delete formErrors['birthday'];
					}
				});
	});
		
	
	$(selector+" input").each(function() {
		
		$(this).focus(function() {
			jQthis = $(this);
			id = jQthis.attr('id');
			errorImg = jQthis.parent().find(".error");
			if (!($(".formguide."+id+" span").hasClass('errorMsg'))) {
				$(".formguide."+id+" span").removeClass("hidden");
			}
			if (id == "captcha") {
				errorImg = jQthis.parent().find(".error");
				errorImg.addClass("hidden");
			}
		});
		
		$(this).keyup(function(){
			jQthis = $(this);
			id = jQthis.attr('id');
			errorImg = jQthis.parent().find(".error");
			
	
			if (jQthis.val() != "") {
				if (id == "login_name" || id == "password" || id == "password_confirm") {
						
					var value = jQthis.val();
					var field = jQthis.attr('name');
					var fieldName = field;
					/*Setup the post variable*/
					data = {};
					data[fieldName] = value;
					data['form'] = selector;
					if (id == "password_confirm") {
						data['password'] = $("#password").val();	
					}
					post("register/formAjaxCheck/"+field, data,  
					
						function(data) {
							if (data.result == 1) {
							errorImg = $("[name='"+data.additional+"']").parent().find(".error");
							errorImg.addClass("hidden");
							errorImg.prev().removeClass("hidden");
							$(".formguide."+data.additional+" span").removeClass('errorMsg');
							$(".formguide."+data.additional+" span").empty();
							if (typeof(formErrors[id]) != "undefined") {
								delete formErrors[id];	
							};
							if (id == "login_name") {
								if(typeof(data.more) != "undefined" && data.more == 1) {
									showOneElement("div.newMemberInstructions", ".newMemberInstruction", ".loginEmail");
								}
								else if(data.result == 1) {
									showOneElement("div.newMemberInstructions", ".newMemberInstruction", ".loginNoMail");	
								}
							}
						}
						else {
							errorImg = $("[name='"+data.additional+"']").parent().find(".error");
							errorImg.removeClass("hidden");
							errorImg.prev().addClass("hidden");
							
							$(".formguide."+data.additional+" span").empty();
							$(".formguide."+data.additional+" span").addClass('errorMsg');
							$(".formguide."+data.additional+" span").append(data.output);
							formErrors[id] = data.output;	
						}
					});
				
				}
				
				else {
					
						errorImg.addClass("hidden");
						if(id != "captcha") {
							errorImg.prev().removeClass("hidden");
						}
						delete formErrors[id];
					}
				
			}
		
		});
		
		$(this).focusout(function() {
			jQthis = $(this);
			id = jQthis.attr('id');
			errorImg = jQthis.parent().find(".error");
			if (jQthis.val() == "") {
				errorImg.prev().addClass("hidden");
				errorImg.addClass("hidden");
				$(".formguide."+id+" span").addClass("hidden");
				delete formErrors[id];
			}
			else if (id == "login_name" || id == "password" || id == "password_confirm") {
						
					var value = jQthis.val();
					var field = jQthis.attr('name');
					var fieldName = field;
					/*Setup the post variable*/
					data = {};
					data['form'] = selector;
					data[fieldName] = value;
					
					if (id == "password_confirm") {
						data['password'] = $("#password").val();	
					}
					post("register/formAjaxCheck/"+field, data,  
					
						function(data) {
							if (data.result == 1) {
							errorImg = $("[name='"+data.additional+"']").parent().find(".error");
							errorImg.addClass("hidden");
							errorImg.prev().removeClass("hidden");
							$(".formguide."+data.additional+" span").removeClass('errorMsg');
							$(".formguide."+data.additional+" span").empty();
							if (typeof(formErrors[data.additional]) != "undefined") {
								delete formErrors[data.additional];	
							};

						}
						else {
							errorImg = $("[name='"+data.additional+"']").parent().find(".error");
							errorImg.removeClass("hidden");
							errorImg.prev().addClass("hidden");
							
							$(".formguide."+data.additional+" span").empty();
							$(".formguide."+data.additional+" span").addClass('errorMsg');
							$(".formguide."+data.additional+" span").append(data.output);
							formErrors[data.additional] = data.output;	
						}
					});
				
				}

			if (!($(".formguide."+id+" span").hasClass('errorMsg'))) {
				$(".formguide."+id+" span").addClass("hidden");
			}
			
		});
	
	});
	
	$(selector+" #language").bind({
		focus: function() {
		
			jQthis = $(this);
			id = jQthis.attr('id');
			errorImg = jQthis.parent().find(".error");
			
			
			$(".formguide."+id+" span").removeClass('hidden');
			
			errorImg.prev().removeClass("hidden");
		},
		
				
		focusout: function() {
			jQthis = $(this);
			id = jQthis.attr('id');
			errorImg = jQthis.parent().find(".error");
			
			$(".formguide."+id+" span").addClass('hidden');

		}

		
	});
	
	$(selector+" #country").bind({
		focus: function() {
		
			jQthis = $(this);
			id = jQthis.attr('id');
			errorImg = jQthis.parent().find(".error");
			
		
			$(".formguide."+id+" span").removeClass('hidden');
			
			errorImg.prev().removeClass("hidden");
		},
		
		change: function() {
			jQthis = $(this);
			var field = jQthis.attr('name');
			var value = jQthis.val();
			var fieldName = field;
					/*Setup the post variable*/
					data = {};
					data['form'] = selector;
					data[fieldName] = value;
					
			/* Check if we can choose the timezone for the selected country or if we need to show timezone selector */
			post("register/formAjaxCheck/"+field, data,  
					
				function(data) {
					if (data.result == 1) {
						$("#timezoneContainer").addClass('hidden');
						$(".formguide.timezone span").addClass('hidden');
						$("#timezone :selected").removeAttr("selected");
						$("#timezone option[value='"+data.output+"']").attr("selected", "selected");
						
					}
				else {
					$(".formguide.timezone span").empty();
					$(".formguide.timezone span").append(data.output);
					$(".formguide.timezone span").removeClass('hidden');
					$("#timezoneContainer").removeClass('hidden');
				}
			});

	
		},
		
		focusout: function() {
			jQthis = $(this);
			id = jQthis.attr('id');
			errorImg = jQthis.parent().find(".error");
			
			$(".formguide."+id+" span").addClass('hidden');
			
						
		}

		
	});
	
	$(selector+" #timezone").bind({
		focusout: function() {
		
			jQthis = $(this);
			id = jQthis.attr('id');
			errorImg = jQthis.parent().find(".error");
			
		
			$(".formguide."+id+" span").addClass('hidden');
			
			errorImg.prev().removeClass("hidden");
		}
	});

	
	$(selector+" .genderSelector input").bind({
		click: function() {
		
			jQthis = $(this);
			id = jQthis.attr('name');
			errorImg = jQthis.parent().parent().find(".error");
			
			
			$(".formguide."+id+" span").removeClass('hidden');
			
			errorImg.prev().removeClass("hidden");
		},
		
		
		focusout: function() {
			jQthis = $(this);
			id = jQthis.attr('name');
			errorImg = jQthis.parent().parent().find(".error");
			
			$(".formguide."+id+" span").addClass('hidden');

		}

		
	});

	$(selector+" input[type='submit']").live('click', function() {
		/*dont submit if empty fields*/
		var errorLength = 0;
		$(selector+" input").each(function() {
			jQthis = $(this);
				id = jQthis.attr('name');
				errorImg = jQthis.parent().find(".error");

			if (jQthis.val() == "" && (jQthis.hasClass("noErrorCount") !== true)) {
				$(".formguide."+id+" span").removeClass('hidden');
				errorImg.removeClass("hidden");
				++errorLength;
			}
			
		});
		$(selector+" select").each(function() {
			if ($(this).val() == "") {
				if ($(this).parent().hasClass('birthdaySelector')) {
					$(".formguide.birthday span").removeClass('hidden');
					$(".birthdaySelector .error").removeClass('hidden');	
				}
				else {
					jQthis = $(this);
					id = jQthis.attr('name');
					errorImg = jQthis.parent().find(".error");
					$(".formguide."+id+" span").removeClass('hidden');
					errorImg.removeClass("hidden");
				}
				++errorLength;
			}
			else {
				
				okImg = $(this).parent().find('.ok');	
				if (okImg.next().hasClass('hidden')) {
					okImg.removeClass('hidden');
				}
				
			}
		});
		
		$(".genderSelector").parent().find('.ok').removeClass('hidden');
		if($("#allowLogin").is(':checked')) {
			$.ajaxSetup({
				async	: false
			});
			/* Check for duplicate username */
				var jQthis = $('#login_name');
				id = jQthis.attr('name');
				errorImg = jQthis.parent().find(".error");
				var value = jQthis.val();
				var field = jQthis.attr('name');
				var fieldName = field;
				/*Setup the post variable*/
				data = {};
				data[fieldName] = value;
	
				post("register/formAjaxCheck/login_name_duplicate", data,  
						
						function(data) {
							if (data.result == 1) {
							
							
	
						}
						else {
							
							errorImg.removeClass("hidden");
							errorImg.prev().addClass("hidden");
							
							$(".formguide."+id+" span").empty();
							$(".formguide."+id+" span").addClass('errorMsg');
							$(".formguide."+id+" span").removeClass('hidden');
							$(".formguide."+id+" span").append(data.output);
							formErrors[id] = data.output;
							++errorLength;	
						}
					});
			$.ajaxSetup({
				async	: true
			});	
		}	
		for(var id in formErrors) {
			++errorLength;	
					
		}
		if (errorLength == 0) {
			$(selector).submit();	
		}
		
		return false;
	});
	
	if (typeof(captchaError) != "undefined") {
		$(selector+" .ok").each(function() {
			$(this).removeClass("hidden");
		});
		errorImg = $("#captcha").parent().find(".error");
		errorImg.removeClass("hidden");
		errorImg.prev().addClass("hidden");
		$(".formguide.captcha span").removeClass('hidden');
		
	}

	
}

function resetTodoTrophy() {
	$(".trophyForTodo").attr('checked', false);
	$("#trophyInfo").addClass('hidden');
	$("#trophyInfo .trophyStickySelections").addClass('hidden');
	$('[name="trophyTitle"]').val("");
	$('[name="bronzeLimit"]').val("1");
	$('[name="silverLimit"]').val("2");
	$('[name="goldLimit"]').val("3");
	$('[name="bronzeLimit"]').val("1");
	
	$('#trophyIconList').find('.current').removeClass('current');
	$('#trophyIconList :contains("default")').addClass('current');
	
	$('[name="trophyTimeHolder"]').find("option[value='weekly']").attr("selected","selected");
	var where = $("#trophyInfo .trophyIconBig");
	changeTrophyImg('default', 3, where);
			
}


function scrollHideForward(target, elemType) {
	var current = $(target).find(".current");
	
	if (current.hasClass('last')) {
		var next = $(target+" "+elemType+":first");	
	}
	else {
		var next = current.next();
	}
	
	current.addClass('hidden');
	next.removeClass('hidden');
	
	current.removeClass('current');
	next.addClass('current');
};

function scrollHideBackward(target, elemType) {

	var current = $(target).find(".current");
		
	if (current.hasClass('first')) {
		var previous = $(target+" "+elemType+":last");	
	}
	else {
		var previous = current.prev();
	}
	
	current.addClass('hidden');
	previous.removeClass('hidden');
			
	current.removeClass('current');
	previous.addClass('current');
};



function changeTrophyImg(newImgName, trophyLevel, where) {

		newImgName = newImgName.replace(/ /gi, '');
		var newImg = "<img src='"+base_url+"img/trophies/"+newImgName+"_"+trophyLevel+".png' alt='Trophy icon' class='trophyIconBig' />";
		
		where.replaceWith(newImg);
		
		
		$("#trophyIconSave").val(newImgName);
		
		
		$(".trophySettings .trophyImg").each(function() {
			
			trophyLevel = $(this).attr('rel');
			var newImg = "<img src='"+base_url+"img/trophies/"+newImgName+"_"+trophyLevel+".png' alt='Trophy icon' class='trophyIconBig' />";
			$(this).find("img:first").replaceWith(newImg);
		});
	
}
/**
* Updates the unread entries count to Facebook
**/
function updateFacebookCounter() {
	data = "";
	post("ajax/updateFacebookCounter", data);  
}

/**
* Resets the unread entries count for Facebook
**/
function resetFacebookCounter() {
	data = "";
	post("ajax/resetFacebookCounter", data);  
}

function setupAllowLogin() {
	$("#allowLogin").bind('click', function() {
		
		if($(this).is(":checked")) {
			var mode = "allow";	
			
		}
		else {
			var mode = "no";
		}
		toggleLoginFields(mode);	
	});
	
}

function toggleLoginFields(mode) {
	if (mode == "allow") {
		$(".loginNameFields :input").each(function() {
			$(this).attr("disabled", false);
			$(this).removeClass("noErrorCount");
			$(this).prev().removeClass('grey');
			$("#allowLogin").attr('checked', true);
		});
		showOneElement("div.newMemberInstructions", ".newMemberInstruction", ".loginNoMail");
	}
	else {
		$(".loginNameFields :input").each(function() {
			$(this).attr("disabled", true);
			$(this).addClass("noErrorCount");
			$(this).prev().addClass('grey');
			$(this).val("");
			$("#allowLogin").attr('checked', false);
			var thisId = $(this).attr('id');
			if (typeof(formErrors[thisId]) != "undefined") {
				delete formErrors[thisId];	
			};
			showOneElement("div.newMemberInstructions", ".newMemberInstruction", ".noLogin");
		});	
	}		
}

function setFeedFilterAll() {
	if($("#showFeedConversation").is(":checked")) {
		$("#showFeedAll").trigger('click');	
	}	
}
/**
* Shows one item inside a given container and hides rest given elements
* @param container jQuery selector for container
* @param element jQuery selector for the elements to be hidden (div, span, .toHide etc)
* @param item unique jQuery selector for the element we want to show (class)
**/
function showOneElement(container, element, item) { 
	$(container+" "+element).each(function() {
		$(this).addClass('hidden');
	});	
	$(container+" "+element+item).removeClass('hidden');
	
}

function resetCommentHeight() { //Reset the comment expanding function
	delete clone;
	delete heightSave;
	delete newHeight;
}

function setAvatarField(imgName) {
	$("#avatarSave").val(imgName);
	return;	
}

/* For stripping html tags but preserving BR */
function strip_html_tags(htmlstring) {
	console.log(htmlstring);
	
	htmlstring = htmlstring.replace(/(<([^>]+)>)/ig,"");
	htmlstring = htmlstring.replace(/\n/gi, '\n<br />');	
	return htmlstring;
}

/**
* For expanding input fields dynamically (plugin)
**/
(function($){
	$.fn.updateHeight = function(method, options) { 
		if(typeof(method) === "undefined") {
			method = 'init';	
		}
		var methods = {
			init : function() {
				return this.each(function() {
					
					/* Setup vars */
					var opts = $.extend({}, $.fn.updateHeight.defaults, options);
					var thisObj = $(this);
					/* Store some data if not already done */
					if(typeof(thisObj.data('clone')) === "undefined") {
						var cloneSave = thisObj.clone();
						cloneSave.css({
	                        position: 'absolute',
	                        top: 0,
	                        left: -9999
	                    });
			            cloneSave.removeAttr('id').removeAttr('name');
			            cloneSave.insertBefore(thisObj);
						thisObj.data('clone', cloneSave);
						
					}
					
					var clone = thisObj.data('clone');				
					clone.val($(this).val());
					clone.height('0');
					clone.scrollTop(10000);
					
					$(this).css('overflow-y', 'hidden');
					var lineHeight = $(this).css('line-height');
					var lineHeight = parseFloat(lineHeight);
					
					if(typeof(thisObj.data('heightSave')) === "undefined") {
						thisObj.data('heightSave', thisObj.height());	
					}
					
					var heightSave = thisObj.data('heightSave');
					var curHeight = clone.scrollTop();
					
					if((curHeight - heightSave) >= 0) {
						
						newHeight = heightSave+(opts.lines*lineHeight);
						thisObj.height(newHeight);
						clone.height(newHeight);
						thisObj.data('clone', clone);
						thisObj.data('heightSave', newHeight);
					}
					else { 
						return;
					}
				});

				
			},
			destroy : function() {
				return this.each(function() {
					
					var thisObj = $(this);
					if (typeof(thisObj.data('clone')) !== "undefined") {
						thisObj.removeData('clone');
					}
					if(typeof(thisObj.data('heightSave')) !== "undefined") {
						thisObj.removeData('heightSave');	
					}
				});
			}
		};
			
		if (methods[method]) {
			
	      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
	    } else if ( typeof method === 'object' || ! method ) {
	    	
	      return methods.init.apply(this, Array.prototype.slice.call(arguments, 1));
	    } else {
	      $.error( 'Method ' +  method + ' does not exist on UpdateHeight' );
	    }
	};
	
	$.fn.updateHeight.defaults = {
			"lines"		:	3
			
		};
	    
})(jQuery);

/**
* Image scroll selector 
* Call this on an image to get scrollable changer
* Requires a list with elements from which the images are to be selected
**/
(function($){
	$.fn.imageScroll = function(method, options, callBackFunction) {
		
		
		var methods = {
			init	:	function(options) {
				return this.each(function() {
			
					var opts = $.extend({}, $.fn.imageScroll.defaults, options);
					thisElem = $(this);

					$(this).before('<div id="'+opts.name+opts.leftArrow+'" class="'+opts.leftArrow+'">&nbsp;</div>');
					$(this).after('<div id="'+opts.name+opts.rightArrow+'" class="'+opts.rightArrow+'">&nbsp;</div>');
					
					$("#"+opts.name+opts.leftArrow).bind('click.imagescroll', function() {
						
						doScroll("left", opts);
					});
					
					$("#"+opts.name+opts.rightArrow).bind('click.imagescrollr', function() {
						
						doScroll("right", opts);
					});

				});

			},
			destroy	:	function(options) {
				return this.each(function(){
					var opts = $.extend({}, $.fn.imageScroll.defaults, options);
					
			         $(window).unbind('.imagescroll');
			         $(window).unbind('.imagescrollr');
			         $("#"+opts.name+opts.leftArrow).remove();
			         $("#"+opts.name+opts.rightArrow).remove();
		       });
		
			}
		};
		
			
		if (methods[method]) {
			
	      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
	    } else if ( typeof method === 'object' || ! method ) {
	    	
	      return methods.init.apply(this, Array.prototype.slice.call(arguments, 1));
	    } else {
	      $.error( 'Method ' +  method + ' does not exist on imagescroll' );
	    }    

		
				
		function doScroll(direction, opts) {
			
			var currentImg = $(opts.list).find(".current");
			
			if (currentImg.hasClass('last') && direction == "right") {
				var nextImg = $(opts.list+" .first");	
			}
			else if (direction=="right") {
				var nextImg = currentImg.next();
			}
			
			else if (currentImg.hasClass('first') && direction == "left") {
				var nextImg = $(opts.list+" .last");
			}
			else {
				var nextImg = currentImg.prev();	
			}
			
			var newImgName = nextImg.html();
			var newImg = '<img src="'+opts.imgPath+newImgName+opts.suffix+'" />';
			
			thisElem.html(newImg);
			
			nextImg.addClass('current');
			currentImg.removeClass('current');
			
			if(typeof (callBackFunction) == "function") {
		      	callBackFunction.call(this, newImgName);
		    }

		};

		
		
	};
	
		$.fn.imageScroll.defaults = {
			name		:	"avatar",
			rightArrow	:	"scrollRightArrow",
			leftArrow	:	"scrollLeftArrow",
			list		: 	"#userAvatarList",
			imgPath		:	"/img",
			suffix		:	".png"
		};
})(jQuery);


/************************************ PLUGINS START ********************************************************/


/*!
 * jQuery UI 1.8rc3
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
/*
 * jQuery UI 1.8rc3
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
jQuery.ui||(function(b){var a=b.browser.mozilla&&(parseFloat(b.browser.version)<1.9);b.ui={version:"1.8rc3",plugin:{add:function(d,e,g){var f=b.ui[d].prototype;for(var c in g){f.plugins[c]=f.plugins[c]||[];f.plugins[c].push([e,g[c]])}},call:function(c,e,d){var g=c.plugins[e];if(!g||!c.element[0].parentNode){return}for(var f=0;f<g.length;f++){if(c.options[g[f][0]]){g[f][1].apply(c.element,d)}}}},contains:function(d,c){return document.compareDocumentPosition?d.compareDocumentPosition(c)&16:d!==c&&d.contains(c)},hasScroll:function(f,d){if(b(f).css("overflow")=="hidden"){return false}var c=(d&&d=="left")?"scrollLeft":"scrollTop",e=false;if(f[c]>0){return true}f[c]=1;e=(f[c]>0);f[c]=0;return e},isOverAxis:function(d,c,e){return(d>c)&&(d<(c+e))},isOver:function(h,d,g,f,c,e){return b.ui.isOverAxis(h,g,c)&&b.ui.isOverAxis(d,f,e)},keyCode:{BACKSPACE:8,CAPS_LOCK:20,COMMA:188,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38}};b.fn.extend({_focus:b.fn.focus,focus:function(c,d){return typeof c==="number"?this.each(function(){var e=this;setTimeout(function(){b(e).focus();(d&&d.call(e))},c)}):this._focus.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable","off").css("MozUserSelect","").unbind("selectstart.ui")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect","none").bind("selectstart.ui",function(){return false})},scrollParent:function(){var c;if((b.browser.msie&&(/(static|relative)/).test(this.css("position")))||(/absolute/).test(this.css("position"))){c=this.parents().filter(function(){return(/(relative|absolute|fixed)/).test(b.curCSS(this,"position",1))&&(/(auto|scroll)/).test(b.curCSS(this,"overflow",1)+b.curCSS(this,"overflow-y",1)+b.curCSS(this,"overflow-x",1))}).eq(0)}else{c=this.parents().filter(function(){return(/(auto|scroll)/).test(b.curCSS(this,"overflow",1)+b.curCSS(this,"overflow-y",1)+b.curCSS(this,"overflow-x",1))}).eq(0)}return(/fixed/).test(this.css("position"))||!c.length?b(document):c},zIndex:function(f){if(f!==undefined){return this.css("zIndex",f)}if(this.length){var d=b(this[0]),c,e;while(d.length&&d[0]!==document){c=d.css("position");if(c=="absolute"||c=="relative"||c=="fixed"){e=parseInt(d.css("zIndex"));if(!isNaN(e)&&e!=0){return e}}d=d.parent()}}return 0}});b.extend(b.expr[":"],{data:function(e,d,c){return !!b.data(e,c[3])},focusable:function(d){var e=d.nodeName.toLowerCase(),c=b.attr(d,"tabindex");return(/input|select|textarea|button|object/.test(e)?!d.disabled:"a"==e||"area"==e?d.href||!isNaN(c):!isNaN(c))&&!b(d)["area"==e?"parents":"closest"](":hidden").length},tabbable:function(d){var c=b.attr(d,"tabindex");return(isNaN(c)||c>=0)&&b(d).is(":focusable")}})})(jQuery);;/*
 * jQuery UI Datepicker 1.8rc3
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Datepicker
 *
 * Depends:
 *	jquery.ui.core.js
 */
(function($){$.extend($.ui,{datepicker:{version:"1.8rc3"}});var PROP_NAME="datepicker";var dpuuid=new Date().getTime();function Datepicker(){this.debug=false;this._curInst=null;this._keyEvent=false;this._disabledInputs=[];this._datepickerShowing=false;this._inDialog=false;this._mainDivId="ui-datepicker-div";this._inlineClass="ui-datepicker-inline";this._appendClass="ui-datepicker-append";this._triggerClass="ui-datepicker-trigger";this._dialogClass="ui-datepicker-dialog";this._disableClass="ui-datepicker-disabled";this._unselectableClass="ui-datepicker-unselectable";this._currentClass="ui-datepicker-current-day";this._dayOverClass="ui-datepicker-days-cell-over";this.regional=[];this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:false,showMonthAfterYear:false,yearSuffix:""};this._defaults={showOn:"focus",showAnim:"show",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:false,hideIfNoPrevNext:false,navigationAsDateFormat:false,gotoCurrent:false,changeMonth:false,changeYear:false,yearRange:"c-10:c+10",showOtherMonths:false,selectOtherMonths:false,showWeek:false,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"_default",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:true,showButtonPanel:false,autoSize:false};$.extend(this._defaults,this.regional[""]);this.dpDiv=$('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>')}$.extend(Datepicker.prototype,{markerClassName:"hasDatepicker",log:function(){if(this.debug){console.log.apply("",arguments)}},_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(settings){extendRemove(this._defaults,settings||{});return this},_attachDatepicker:function(target,settings){var inlineSettings=null;for(var attrName in this._defaults){var attrValue=target.getAttribute("date:"+attrName);if(attrValue){inlineSettings=inlineSettings||{};try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}}}var nodeName=target.nodeName.toLowerCase();var inline=(nodeName=="div"||nodeName=="span");if(!target.id){target.id="dp"+(++this.uuid)}var inst=this._newInst($(target),inline);inst.settings=$.extend({},settings||{},inlineSettings||{});if(nodeName=="input"){this._connectDatepicker(target,inst)}else{if(inline){this._inlineDatepicker(target,inst)}}},_newInst:function(target,inline){var id=target[0].id.replace(/([^A-Za-z0-9_])/g,"\\\\$1");return{id:id,input:target,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:inline,dpDiv:(!inline?this.dpDiv:$('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}},_connectDatepicker:function(target,inst){var input=$(target);inst.append=$([]);inst.trigger=$([]);if(input.hasClass(this.markerClassName)){return}this._attachments(input,inst);input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function(event,key,value){inst.settings[key]=value}).bind("getData.datepicker",function(event,key){return this._get(inst,key)});this._autoSize(inst);$.data(target,PROP_NAME,inst)},_attachments:function(input,inst){var appendText=this._get(inst,"appendText");var isRTL=this._get(inst,"isRTL");if(inst.append){inst.append.remove()}if(appendText){inst.append=$('<span class="'+this._appendClass+'">'+appendText+"</span>");input[isRTL?"before":"after"](inst.append)}input.unbind("focus",this._showDatepicker);if(inst.trigger){inst.trigger.remove()}var showOn=this._get(inst,"showOn");if(showOn=="focus"||showOn=="both"){input.focus(this._showDatepicker)}if(showOn=="button"||showOn=="both"){var buttonText=this._get(inst,"buttonText");var buttonImage=this._get(inst,"buttonImage");inst.trigger=$(this._get(inst,"buttonImageOnly")?$("<img/>").addClass(this._triggerClass).attr({src:buttonImage,alt:buttonText,title:buttonText}):$('<button type="button"></button>').addClass(this._triggerClass).html(buttonImage==""?buttonText:$("<img/>").attr({src:buttonImage,alt:buttonText,title:buttonText})));input[isRTL?"before":"after"](inst.trigger);inst.trigger.click(function(){if($.datepicker._datepickerShowing&&$.datepicker._lastInput==input[0]){$.datepicker._hideDatepicker()}else{$.datepicker._showDatepicker(input[0])}return false})}},_autoSize:function(inst){if(this._get(inst,"autoSize")&&!inst.inline){var date=new Date(2009,12-1,20);var dateFormat=this._get(inst,"dateFormat");if(dateFormat.match(/[DM]/)){var findMax=function(names){var max=0;var maxI=0;for(var i=0;i<names.length;i++){if(names[i].length>max){max=names[i].length;maxI=i}}return maxI};date.setMonth(findMax(this._get(inst,(dateFormat.match(/MM/)?"monthNames":"monthNamesShort"))));date.setDate(findMax(this._get(inst,(dateFormat.match(/DD/)?"dayNames":"dayNamesShort")))+20-date.getDay())}inst.input.attr("size",this._formatDate(inst,date).length)}},_inlineDatepicker:function(target,inst){var divSpan=$(target);if(divSpan.hasClass(this.markerClassName)){return}divSpan.addClass(this.markerClassName).append(inst.dpDiv).bind("setData.datepicker",function(event,key,value){inst.settings[key]=value}).bind("getData.datepicker",function(event,key){return this._get(inst,key)});$.data(target,PROP_NAME,inst);this._setDate(inst,this._getDefaultDate(inst),true);this._updateDatepicker(inst);this._updateAlternate(inst)},_dialogDatepicker:function(input,date,onSelect,settings,pos){var inst=this._dialogInst;if(!inst){var id="dp"+(++this.uuid);this._dialogInput=$('<input type="text" id="'+id+'" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>');this._dialogInput.keydown(this._doKeyDown);$("body").append(this._dialogInput);inst=this._dialogInst=this._newInst(this._dialogInput,false);inst.settings={};$.data(this._dialogInput[0],PROP_NAME,inst)}extendRemove(inst.settings,settings||{});date=(date&&date.constructor==Date?this._formatDate(inst,date):date);this._dialogInput.val(date);this._pos=(pos?(pos.length?pos:[pos.pageX,pos.pageY]):null);if(!this._pos){var browserWidth=document.documentElement.clientWidth;var browserHeight=document.documentElement.clientHeight;var scrollX=document.documentElement.scrollLeft||document.body.scrollLeft;var scrollY=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[(browserWidth/2)-100+scrollX,(browserHeight/2)-150+scrollY]}this._dialogInput.css("left",(this._pos[0]+20)+"px").css("top",this._pos[1]+"px");inst.settings.onSelect=onSelect;this._inDialog=true;this.dpDiv.addClass(this._dialogClass);this._showDatepicker(this._dialogInput[0]);if($.blockUI){$.blockUI(this.dpDiv)}$.data(this._dialogInput[0],PROP_NAME,inst);return this},_destroyDatepicker:function(target){var $target=$(target);var inst=$.data(target,PROP_NAME);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();$.removeData(target,PROP_NAME);if(nodeName=="input"){inst.append.remove();inst.trigger.remove();$target.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)}else{if(nodeName=="div"||nodeName=="span"){$target.removeClass(this.markerClassName).empty()}}},_enableDatepicker:function(target){var $target=$(target);var inst=$.data(target,PROP_NAME);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();if(nodeName=="input"){target.disabled=false;inst.trigger.filter("button").each(function(){this.disabled=false}).end().filter("img").css({opacity:"1.0",cursor:""})}else{if(nodeName=="div"||nodeName=="span"){var inline=$target.children("."+this._inlineClass);inline.children().removeClass("ui-state-disabled")}}this._disabledInputs=$.map(this._disabledInputs,function(value){return(value==target?null:value)})},_disableDatepicker:function(target){var $target=$(target);var inst=$.data(target,PROP_NAME);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();if(nodeName=="input"){target.disabled=true;inst.trigger.filter("button").each(function(){this.disabled=true}).end().filter("img").css({opacity:"0.5",cursor:"default"})}else{if(nodeName=="div"||nodeName=="span"){var inline=$target.children("."+this._inlineClass);inline.children().addClass("ui-state-disabled")}}this._disabledInputs=$.map(this._disabledInputs,function(value){return(value==target?null:value)});this._disabledInputs[this._disabledInputs.length]=target},_isDisabledDatepicker:function(target){if(!target){return false}for(var i=0;i<this._disabledInputs.length;i++){if(this._disabledInputs[i]==target){return true}}return false},_getInst:function(target){try{return $.data(target,PROP_NAME)}catch(err){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(target,name,value){var inst=this._getInst(target);if(arguments.length==2&&typeof name=="string"){return(name=="defaults"?$.extend({},$.datepicker._defaults):(inst?(name=="all"?$.extend({},inst.settings):this._get(inst,name)):null))}var settings=name||{};if(typeof name=="string"){settings={};settings[name]=value}if(inst){if(this._curInst==inst){this._hideDatepicker()}var date=this._getDateDatepicker(target,true);extendRemove(inst.settings,settings);this._attachments($(target),inst);this._autoSize(inst);this._setDateDatepicker(target,date);this._updateDatepicker(inst)}},_changeDatepicker:function(target,name,value){this._optionDatepicker(target,name,value)},_refreshDatepicker:function(target){var inst=this._getInst(target);if(inst){this._updateDatepicker(inst)}},_setDateDatepicker:function(target,date){var inst=this._getInst(target);if(inst){this._setDate(inst,date);this._updateDatepicker(inst);this._updateAlternate(inst)}},_getDateDatepicker:function(target,noDefault){var inst=this._getInst(target);if(inst&&!inst.inline){this._setDateFromField(inst,noDefault)}return(inst?this._getDate(inst):null)},_doKeyDown:function(event){var inst=$.datepicker._getInst(event.target);var handled=true;var isRTL=inst.dpDiv.is(".ui-datepicker-rtl");inst._keyEvent=true;if($.datepicker._datepickerShowing){switch(event.keyCode){case 9:$.datepicker._hideDatepicker();handled=false;break;case 13:var sel=$("td."+$.datepicker._dayOverClass,inst.dpDiv).add($("td."+$.datepicker._currentClass,inst.dpDiv));if(sel[0]){$.datepicker._selectDay(event.target,inst.selectedMonth,inst.selectedYear,sel[0])}else{$.datepicker._hideDatepicker()}return false;break;case 27:$.datepicker._hideDatepicker();break;case 33:$.datepicker._adjustDate(event.target,(event.ctrlKey?-$.datepicker._get(inst,"stepBigMonths"):-$.datepicker._get(inst,"stepMonths")),"M");break;case 34:$.datepicker._adjustDate(event.target,(event.ctrlKey?+$.datepicker._get(inst,"stepBigMonths"):+$.datepicker._get(inst,"stepMonths")),"M");break;case 35:if(event.ctrlKey||event.metaKey){$.datepicker._clearDate(event.target)}handled=event.ctrlKey||event.metaKey;break;case 36:if(event.ctrlKey||event.metaKey){$.datepicker._gotoToday(event.target)}handled=event.ctrlKey||event.metaKey;break;case 37:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,(isRTL?+1:-1),"D")}handled=event.ctrlKey||event.metaKey;if(event.originalEvent.altKey){$.datepicker._adjustDate(event.target,(event.ctrlKey?-$.datepicker._get(inst,"stepBigMonths"):-$.datepicker._get(inst,"stepMonths")),"M")}break;case 38:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,-7,"D")}handled=event.ctrlKey||event.metaKey;break;case 39:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,(isRTL?-1:+1),"D")}handled=event.ctrlKey||event.metaKey;if(event.originalEvent.altKey){$.datepicker._adjustDate(event.target,(event.ctrlKey?+$.datepicker._get(inst,"stepBigMonths"):+$.datepicker._get(inst,"stepMonths")),"M")}break;case 40:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,+7,"D")}handled=event.ctrlKey||event.metaKey;break;default:handled=false}}else{if(event.keyCode==36&&event.ctrlKey){$.datepicker._showDatepicker(this)}else{handled=false}}if(handled){event.preventDefault();event.stopPropagation()}},_doKeyPress:function(event){var inst=$.datepicker._getInst(event.target);if($.datepicker._get(inst,"constrainInput")){var chars=$.datepicker._possibleChars($.datepicker._get(inst,"dateFormat"));var chr=String.fromCharCode(event.charCode==undefined?event.keyCode:event.charCode);return event.ctrlKey||(chr<" "||!chars||chars.indexOf(chr)>-1)}},_doKeyUp:function(event){var inst=$.datepicker._getInst(event.target);if(inst.input.val()!=inst.lastVal){try{var date=$.datepicker.parseDate($.datepicker._get(inst,"dateFormat"),(inst.input?inst.input.val():null),$.datepicker._getFormatConfig(inst));if(date){$.datepicker._setDateFromField(inst);$.datepicker._updateAlternate(inst);$.datepicker._updateDatepicker(inst)}}catch(event){$.datepicker.log(event)}}return true},_showDatepicker:function(input){input=input.target||input;if(input.nodeName.toLowerCase()!="input"){input=$("input",input.parentNode)[0]}if($.datepicker._isDisabledDatepicker(input)||$.datepicker._lastInput==input){return}var inst=$.datepicker._getInst(input);if($.datepicker._curInst&&$.datepicker._curInst!=inst){$.datepicker._curInst.dpDiv.stop(true,true)}var beforeShow=$.datepicker._get(inst,"beforeShow");extendRemove(inst.settings,(beforeShow?beforeShow.apply(input,[input,inst]):{}));inst.lastVal=null;$.datepicker._lastInput=input;$.datepicker._setDateFromField(inst);if($.datepicker._inDialog){input.value=""}if(!$.datepicker._pos){$.datepicker._pos=$.datepicker._findPos(input);$.datepicker._pos[1]+=input.offsetHeight}var isFixed=false;$(input).parents().each(function(){isFixed|=$(this).css("position")=="fixed";return !isFixed});if(isFixed&&$.browser.opera){$.datepicker._pos[0]-=document.documentElement.scrollLeft;$.datepicker._pos[1]-=document.documentElement.scrollTop}var offset={left:$.datepicker._pos[0],top:$.datepicker._pos[1]};$.datepicker._pos=null;inst.dpDiv.css({position:"absolute",display:"block",top:"-1000px"});$.datepicker._updateDatepicker(inst);offset=$.datepicker._checkOffset(inst,offset,isFixed);inst.dpDiv.css({position:($.datepicker._inDialog&&$.blockUI?"static":(isFixed?"fixed":"absolute")),display:"none",left:offset.left+"px",top:offset.top+"px"});if(!inst.inline){var showAnim=$.datepicker._get(inst,"showAnim");var duration=$.datepicker._get(inst,"duration");var postProcess=function(){$.datepicker._datepickerShowing=true;var borders=$.datepicker._getBorders(inst.dpDiv);inst.dpDiv.find("iframe.ui-datepicker-cover").css({left:-borders[0],top:-borders[1],width:inst.dpDiv.outerWidth(),height:inst.dpDiv.outerHeight()})};inst.dpDiv.zIndex($(input).zIndex()+1);if($.effects&&$.effects[showAnim]){inst.dpDiv.show(showAnim,$.datepicker._get(inst,"showOptions"),duration,postProcess)}else{inst.dpDiv[showAnim||"show"]((showAnim?duration:null),postProcess)}if(!showAnim){postProcess()}if(inst.input.is(":visible")&&!inst.input.is(":disabled")){inst.input.focus()}$.datepicker._curInst=inst}},_updateDatepicker:function(inst){var self=this;var borders=$.datepicker._getBorders(inst.dpDiv);inst.dpDiv.empty().append(this._generateHTML(inst)).find("iframe.ui-datepicker-cover").css({left:-borders[0],top:-borders[1],width:inst.dpDiv.outerWidth(),height:inst.dpDiv.outerHeight()}).end().find("button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a").bind("mouseout",function(){$(this).removeClass("ui-state-hover");if(this.className.indexOf("ui-datepicker-prev")!=-1){$(this).removeClass("ui-datepicker-prev-hover")}if(this.className.indexOf("ui-datepicker-next")!=-1){$(this).removeClass("ui-datepicker-next-hover")}}).bind("mouseover",function(){if(!self._isDisabledDatepicker(inst.inline?inst.dpDiv.parent()[0]:inst.input[0])){$(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");$(this).addClass("ui-state-hover");if(this.className.indexOf("ui-datepicker-prev")!=-1){$(this).addClass("ui-datepicker-prev-hover")}if(this.className.indexOf("ui-datepicker-next")!=-1){$(this).addClass("ui-datepicker-next-hover")}}}).end().find("."+this._dayOverClass+" a").trigger("mouseover").end();var numMonths=this._getNumberOfMonths(inst);var cols=numMonths[1];var width=17;if(cols>1){inst.dpDiv.addClass("ui-datepicker-multi-"+cols).css("width",(width*cols)+"em")}else{inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("")}inst.dpDiv[(numMonths[0]!=1||numMonths[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi");inst.dpDiv[(this._get(inst,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl");if(inst==$.datepicker._curInst&&$.datepicker._datepickerShowing&&inst.input&&inst.input.is(":visible")&&!inst.input.is(":disabled")){inst.input.focus()}},_getBorders:function(elem){var convert=function(value){return{thin:1,medium:2,thick:3}[value]||value};return[parseFloat(convert(elem.css("border-left-width"))),parseFloat(convert(elem.css("border-top-width")))]},_checkOffset:function(inst,offset,isFixed){var dpWidth=inst.dpDiv.outerWidth();var dpHeight=inst.dpDiv.outerHeight();var inputWidth=inst.input?inst.input.outerWidth():0;var inputHeight=inst.input?inst.input.outerHeight():0;var viewWidth=document.documentElement.clientWidth+$(document).scrollLeft();var viewHeight=document.documentElement.clientHeight+$(document).scrollTop();offset.left-=(this._get(inst,"isRTL")?(dpWidth-inputWidth):0);offset.left-=(isFixed&&offset.left==inst.input.offset().left)?$(document).scrollLeft():0;offset.top-=(isFixed&&offset.top==(inst.input.offset().top+inputHeight))?$(document).scrollTop():0;offset.left-=Math.min(offset.left,(offset.left+dpWidth>viewWidth&&viewWidth>dpWidth)?Math.abs(offset.left+dpWidth-viewWidth):0);offset.top-=Math.min(offset.top,(offset.top+dpHeight>viewHeight&&viewHeight>dpHeight)?Math.abs(dpHeight+inputHeight):0);return offset},_findPos:function(obj){var inst=this._getInst(obj);var isRTL=this._get(inst,"isRTL");while(obj&&(obj.type=="hidden"||obj.nodeType!=1)){obj=obj[isRTL?"previousSibling":"nextSibling"]}var position=$(obj).offset();return[position.left,position.top]},_hideDatepicker:function(input){var inst=this._curInst;if(!inst||(input&&inst!=$.data(input,PROP_NAME))){return}if(this._datepickerShowing){var showAnim=this._get(inst,"showAnim");var duration=this._get(inst,"duration");var postProcess=function(){$.datepicker._tidyDialog(inst);this._curInst=null};if($.effects&&$.effects[showAnim]){inst.dpDiv.hide(showAnim,$.datepicker._get(inst,"showOptions"),duration,postProcess)}else{inst.dpDiv[(showAnim=="slideDown"?"slideUp":(showAnim=="fadeIn"?"fadeOut":"hide"))]((showAnim?duration:null),postProcess)}if(!showAnim){postProcess()}var onClose=this._get(inst,"onClose");if(onClose){onClose.apply((inst.input?inst.input[0]:null),[(inst.input?inst.input.val():""),inst])}this._datepickerShowing=false;this._lastInput=null;if(this._inDialog){this._dialogInput.css({position:"absolute",left:"0",top:"-100px"});if($.blockUI){$.unblockUI();$("body").append(this.dpDiv)}}this._inDialog=false}},_tidyDialog:function(inst){inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(event){if(!$.datepicker._curInst){return}var $target=$(event.target);if($target[0].id!=$.datepicker._mainDivId&&$target.parents("#"+$.datepicker._mainDivId).length==0&&!$target.hasClass($.datepicker.markerClassName)&&!$target.hasClass($.datepicker._triggerClass)&&$.datepicker._datepickerShowing&&!($.datepicker._inDialog&&$.blockUI)){$.datepicker._hideDatepicker()}},_adjustDate:function(id,offset,period){var target=$(id);var inst=this._getInst(target[0]);if(this._isDisabledDatepicker(target[0])){return}this._adjustInstDate(inst,offset+(period=="M"?this._get(inst,"showCurrentAtPos"):0),period);this._updateDatepicker(inst)},_gotoToday:function(id){var target=$(id);var inst=this._getInst(target[0]);if(this._get(inst,"gotoCurrent")&&inst.currentDay){inst.selectedDay=inst.currentDay;inst.drawMonth=inst.selectedMonth=inst.currentMonth;inst.drawYear=inst.selectedYear=inst.currentYear}else{var date=new Date();inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear()}this._notifyChange(inst);this._adjustDate(target)},_selectMonthYear:function(id,select,period){var target=$(id);var inst=this._getInst(target[0]);inst._selectingMonthYear=false;inst["selected"+(period=="M"?"Month":"Year")]=inst["draw"+(period=="M"?"Month":"Year")]=parseInt(select.options[select.selectedIndex].value,10);this._notifyChange(inst);this._adjustDate(target)},_clickMonthYear:function(id){var target=$(id);var inst=this._getInst(target[0]);if(inst.input&&inst._selectingMonthYear&&!$.browser.msie){inst.input.focus()}inst._selectingMonthYear=!inst._selectingMonthYear},_selectDay:function(id,month,year,td){var target=$(id);if($(td).hasClass(this._unselectableClass)||this._isDisabledDatepicker(target[0])){return}var inst=this._getInst(target[0]);inst.selectedDay=inst.currentDay=$("a",td).html();inst.selectedMonth=inst.currentMonth=month;inst.selectedYear=inst.currentYear=year;this._selectDate(id,this._formatDate(inst,inst.currentDay,inst.currentMonth,inst.currentYear))},_clearDate:function(id){var target=$(id);var inst=this._getInst(target[0]);this._selectDate(target,"")},_selectDate:function(id,dateStr){var target=$(id);var inst=this._getInst(target[0]);dateStr=(dateStr!=null?dateStr:this._formatDate(inst));if(inst.input){inst.input.val(dateStr)}this._updateAlternate(inst);var onSelect=this._get(inst,"onSelect");if(onSelect){onSelect.apply((inst.input?inst.input[0]:null),[dateStr,inst])}else{if(inst.input){inst.input.trigger("change")}}if(inst.inline){this._updateDatepicker(inst)}else{this._hideDatepicker();this._lastInput=inst.input[0];if(typeof(inst.input[0])!="object"){inst.input.focus()}this._lastInput=null}},_updateAlternate:function(inst){var altField=this._get(inst,"altField");if(altField){var altFormat=this._get(inst,"altFormat")||this._get(inst,"dateFormat");var date=this._getDate(inst);var dateStr=this.formatDate(altFormat,date,this._getFormatConfig(inst));$(altField).each(function(){$(this).val(dateStr)})}},noWeekends:function(date){var day=date.getDay();return[(day>0&&day<6),""]},iso8601Week:function(date){var checkDate=new Date(date.getTime());checkDate.setDate(checkDate.getDate()+4-(checkDate.getDay()||7));var time=checkDate.getTime();checkDate.setMonth(0);checkDate.setDate(1);return Math.floor(Math.round((time-checkDate)/86400000)/7)+1},parseDate:function(format,value,settings){if(format==null||value==null){throw"Invalid arguments"}value=(typeof value=="object"?value.toString():value+"");if(value==""){return null}var shortYearCutoff=(settings?settings.shortYearCutoff:null)||this._defaults.shortYearCutoff;var dayNamesShort=(settings?settings.dayNamesShort:null)||this._defaults.dayNamesShort;var dayNames=(settings?settings.dayNames:null)||this._defaults.dayNames;var monthNamesShort=(settings?settings.monthNamesShort:null)||this._defaults.monthNamesShort;var monthNames=(settings?settings.monthNames:null)||this._defaults.monthNames;var year=-1;var month=-1;var day=-1;var doy=-1;var literal=false;var lookAhead=function(match){var matches=(iFormat+1<format.length&&format.charAt(iFormat+1)==match);if(matches){iFormat++}return matches};var getNumber=function(match){lookAhead(match);var size=(match=="@"?14:(match=="!"?20:(match=="y"?4:(match=="o"?3:2))));var digits=new RegExp("^\\d{1,"+size+"}");var num=value.substring(iValue).match(digits);if(!num){throw"Missing number at position "+iValue}iValue+=num[0].length;return parseInt(num[0],10)};var getName=function(match,shortNames,longNames){var names=(lookAhead(match)?longNames:shortNames);for(var i=0;i<names.length;i++){if(value.substr(iValue,names[i].length)==names[i]){iValue+=names[i].length;return i+1}}throw"Unknown name at position "+iValue};var checkLiteral=function(){if(value.charAt(iValue)!=format.charAt(iFormat)){throw"Unexpected literal at position "+iValue}iValue++};var iValue=0;for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{checkLiteral()}}else{switch(format.charAt(iFormat)){case"d":day=getNumber("d");break;case"D":getName("D",dayNamesShort,dayNames);break;case"o":doy=getNumber("o");break;case"m":month=getNumber("m");break;case"M":month=getName("M",monthNamesShort,monthNames);break;case"y":year=getNumber("y");break;case"@":var date=new Date(getNumber("@"));year=date.getFullYear();month=date.getMonth()+1;day=date.getDate();break;case"!":var date=new Date((getNumber("!")-this._ticksTo1970)/10000);year=date.getFullYear();month=date.getMonth()+1;day=date.getDate();break;case"'":if(lookAhead("'")){checkLiteral()}else{literal=true}break;default:checkLiteral()}}}if(year==-1){year=new Date().getFullYear()}else{if(year<100){year+=new Date().getFullYear()-new Date().getFullYear()%100+(year<=shortYearCutoff?0:-100)}}if(doy>-1){month=1;day=doy;do{var dim=this._getDaysInMonth(year,month-1);if(day<=dim){break}month++;day-=dim}while(true)}var date=this._daylightSavingAdjust(new Date(year,month-1,day));if(date.getFullYear()!=year||date.getMonth()+1!=month||date.getDate()!=day){throw"Invalid date"}return date},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(((1970-1)*365+Math.floor(1970/4)-Math.floor(1970/100)+Math.floor(1970/400))*24*60*60*10000000),formatDate:function(format,date,settings){if(!date){return""}var dayNamesShort=(settings?settings.dayNamesShort:null)||this._defaults.dayNamesShort;var dayNames=(settings?settings.dayNames:null)||this._defaults.dayNames;var monthNamesShort=(settings?settings.monthNamesShort:null)||this._defaults.monthNamesShort;var monthNames=(settings?settings.monthNames:null)||this._defaults.monthNames;var lookAhead=function(match){var matches=(iFormat+1<format.length&&format.charAt(iFormat+1)==match);if(matches){iFormat++}return matches};var formatNumber=function(match,value,len){var num=""+value;if(lookAhead(match)){while(num.length<len){num="0"+num}}return num};var formatName=function(match,value,shortNames,longNames){return(lookAhead(match)?longNames[value]:shortNames[value])};var output="";var literal=false;if(date){for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{output+=format.charAt(iFormat)}}else{switch(format.charAt(iFormat)){case"d":output+=formatNumber("d",date.getDate(),2);break;case"D":output+=formatName("D",date.getDay(),dayNamesShort,dayNames);break;case"o":output+=formatNumber("o",(date.getTime()-new Date(date.getFullYear(),0,0).getTime())/86400000,3);break;case"m":output+=formatNumber("m",date.getMonth()+1,2);break;case"M":output+=formatName("M",date.getMonth(),monthNamesShort,monthNames);break;case"y":output+=(lookAhead("y")?date.getFullYear():(date.getYear()%100<10?"0":"")+date.getYear()%100);break;case"@":output+=date.getTime();break;case"!":output+=date.getTime()*10000+this._ticksTo1970;break;case"'":if(lookAhead("'")){output+="'"}else{literal=true}break;default:output+=format.charAt(iFormat)}}}}return output},_possibleChars:function(format){var chars="";var literal=false;var lookAhead=function(match){var matches=(iFormat+1<format.length&&format.charAt(iFormat+1)==match);if(matches){iFormat++}return matches};for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{chars+=format.charAt(iFormat)}}else{switch(format.charAt(iFormat)){case"d":case"m":case"y":case"@":chars+="0123456789";break;case"D":case"M":return null;case"'":if(lookAhead("'")){chars+="'"}else{literal=true}break;default:chars+=format.charAt(iFormat)}}}return chars},_get:function(inst,name){return inst.settings[name]!==undefined?inst.settings[name]:this._defaults[name]},_setDateFromField:function(inst,noDefault){if(inst.input.val()==inst.lastVal){return}var dateFormat=this._get(inst,"dateFormat");var dates=inst.lastVal=inst.input?inst.input.val():null;var date,defaultDate;date=defaultDate=this._getDefaultDate(inst);var settings=this._getFormatConfig(inst);try{date=this.parseDate(dateFormat,dates,settings)||defaultDate}catch(event){this.log(event);dates=(noDefault?"":dates)}inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear();inst.currentDay=(dates?date.getDate():0);inst.currentMonth=(dates?date.getMonth():0);inst.currentYear=(dates?date.getFullYear():0);this._adjustInstDate(inst)},_getDefaultDate:function(inst){return this._restrictMinMax(inst,this._determineDate(inst,this._get(inst,"defaultDate"),new Date()))},_determineDate:function(inst,date,defaultDate){var offsetNumeric=function(offset){var date=new Date();date.setDate(date.getDate()+offset);return date};var offsetString=function(offset){try{return $.datepicker.parseDate($.datepicker._get(inst,"dateFormat"),offset,$.datepicker._getFormatConfig(inst))}catch(e){}var date=(offset.toLowerCase().match(/^c/)?$.datepicker._getDate(inst):null)||new Date();var year=date.getFullYear();var month=date.getMonth();var day=date.getDate();var pattern=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;var matches=pattern.exec(offset);while(matches){switch(matches[2]||"d"){case"d":case"D":day+=parseInt(matches[1],10);break;case"w":case"W":day+=parseInt(matches[1],10)*7;break;case"m":case"M":month+=parseInt(matches[1],10);day=Math.min(day,$.datepicker._getDaysInMonth(year,month));break;case"y":case"Y":year+=parseInt(matches[1],10);day=Math.min(day,$.datepicker._getDaysInMonth(year,month));break}matches=pattern.exec(offset)}return new Date(year,month,day)};date=(date==null?defaultDate:(typeof date=="string"?offsetString(date):(typeof date=="number"?(isNaN(date)?defaultDate:offsetNumeric(date)):date)));date=(date&&date.toString()=="Invalid Date"?defaultDate:date);if(date){date.setHours(0);date.setMinutes(0);date.setSeconds(0);date.setMilliseconds(0)}return this._daylightSavingAdjust(date)},_daylightSavingAdjust:function(date){if(!date){return null}date.setHours(date.getHours()>12?date.getHours()+2:0);return date},_setDate:function(inst,date,noChange){var clear=!(date);var origMonth=inst.selectedMonth;var origYear=inst.selectedYear;date=this._restrictMinMax(inst,this._determineDate(inst,date,new Date()));inst.selectedDay=inst.currentDay=date.getDate();inst.drawMonth=inst.selectedMonth=inst.currentMonth=date.getMonth();inst.drawYear=inst.selectedYear=inst.currentYear=date.getFullYear();if((origMonth!=inst.selectedMonth||origYear!=inst.selectedYear)&&!noChange){this._notifyChange(inst)}this._adjustInstDate(inst);if(inst.input){inst.input.val(clear?"":this._formatDate(inst))}},_getDate:function(inst){var startDate=(!inst.currentYear||(inst.input&&inst.input.val()=="")?null:this._daylightSavingAdjust(new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));return startDate},_generateHTML:function(inst){var today=new Date();today=this._daylightSavingAdjust(new Date(today.getFullYear(),today.getMonth(),today.getDate()));var isRTL=this._get(inst,"isRTL");var showButtonPanel=this._get(inst,"showButtonPanel");var hideIfNoPrevNext=this._get(inst,"hideIfNoPrevNext");var navigationAsDateFormat=this._get(inst,"navigationAsDateFormat");var numMonths=this._getNumberOfMonths(inst);var showCurrentAtPos=this._get(inst,"showCurrentAtPos");var stepMonths=this._get(inst,"stepMonths");var isMultiMonth=(numMonths[0]!=1||numMonths[1]!=1);var currentDate=this._daylightSavingAdjust((!inst.currentDay?new Date(9999,9,9):new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));var minDate=this._getMinMaxDate(inst,"min");var maxDate=this._getMinMaxDate(inst,"max");var drawMonth=inst.drawMonth-showCurrentAtPos;var drawYear=inst.drawYear;if(drawMonth<0){drawMonth+=12;drawYear--}if(maxDate){var maxDraw=this._daylightSavingAdjust(new Date(maxDate.getFullYear(),maxDate.getMonth()-(numMonths[0]*numMonths[1])+1,maxDate.getDate()));maxDraw=(minDate&&maxDraw<minDate?minDate:maxDraw);while(this._daylightSavingAdjust(new Date(drawYear,drawMonth,1))>maxDraw){drawMonth--;if(drawMonth<0){drawMonth=11;drawYear--}}}inst.drawMonth=drawMonth;inst.drawYear=drawYear;var prevText=this._get(inst,"prevText");prevText=(!navigationAsDateFormat?prevText:this.formatDate(prevText,this._daylightSavingAdjust(new Date(drawYear,drawMonth-stepMonths,1)),this._getFormatConfig(inst)));var prev=(this._canAdjustMonth(inst,-1,drawYear,drawMonth)?'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._adjustDate('#"+inst.id+"', -"+stepMonths+", 'M');\" title=\""+prevText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"e":"w")+'">'+prevText+"</span></a>":(hideIfNoPrevNext?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+prevText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"e":"w")+'">'+prevText+"</span></a>"));var nextText=this._get(inst,"nextText");nextText=(!navigationAsDateFormat?nextText:this.formatDate(nextText,this._daylightSavingAdjust(new Date(drawYear,drawMonth+stepMonths,1)),this._getFormatConfig(inst)));var next=(this._canAdjustMonth(inst,+1,drawYear,drawMonth)?'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._adjustDate('#"+inst.id+"', +"+stepMonths+", 'M');\" title=\""+nextText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"w":"e")+'">'+nextText+"</span></a>":(hideIfNoPrevNext?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+nextText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"w":"e")+'">'+nextText+"</span></a>"));var currentText=this._get(inst,"currentText");var gotoDate=(this._get(inst,"gotoCurrent")&&inst.currentDay?currentDate:today);currentText=(!navigationAsDateFormat?currentText:this.formatDate(currentText,gotoDate,this._getFormatConfig(inst)));var controls=(!inst.inline?'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_'+dpuuid+'.datepicker._hideDatepicker();">'+this._get(inst,"closeText")+"</button>":"");var buttonPanel=(showButtonPanel)?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(isRTL?controls:"")+(this._isInRange(inst,gotoDate)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._gotoToday('#"+inst.id+"');\">"+currentText+"</button>":"")+(isRTL?"":controls)+"</div>":"";var firstDay=parseInt(this._get(inst,"firstDay"),10);firstDay=(isNaN(firstDay)?0:firstDay);var showWeek=this._get(inst,"showWeek");var dayNames=this._get(inst,"dayNames");var dayNamesShort=this._get(inst,"dayNamesShort");var dayNamesMin=this._get(inst,"dayNamesMin");var monthNames=this._get(inst,"monthNames");var monthNamesShort=this._get(inst,"monthNamesShort");var beforeShowDay=this._get(inst,"beforeShowDay");var showOtherMonths=this._get(inst,"showOtherMonths");var selectOtherMonths=this._get(inst,"selectOtherMonths");var calculateWeek=this._get(inst,"calculateWeek")||this.iso8601Week;var defaultDate=this._getDefaultDate(inst);var html="";for(var row=0;row<numMonths[0];row++){var group="";for(var col=0;col<numMonths[1];col++){var selectedDate=this._daylightSavingAdjust(new Date(drawYear,drawMonth,inst.selectedDay));var cornerClass=" ui-corner-all";var calender="";if(isMultiMonth){calender+='<div class="ui-datepicker-group';if(numMonths[1]>1){switch(col){case 0:calender+=" ui-datepicker-group-first";cornerClass=" ui-corner-"+(isRTL?"right":"left");break;case numMonths[1]-1:calender+=" ui-datepicker-group-last";cornerClass=" ui-corner-"+(isRTL?"left":"right");break;default:calender+=" ui-datepicker-group-middle";cornerClass="";break}}calender+='">'}calender+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+cornerClass+'">'+(/all|left/.test(cornerClass)&&row==0?(isRTL?next:prev):"")+(/all|right/.test(cornerClass)&&row==0?(isRTL?prev:next):"")+this._generateMonthYearHeader(inst,drawMonth,drawYear,minDate,maxDate,row>0||col>0,monthNames,monthNamesShort)+'</div><table class="ui-datepicker-calendar"><thead><tr>';var thead=(showWeek?'<th class="ui-datepicker-week-col">'+this._get(inst,"weekHeader")+"</th>":"");for(var dow=0;dow<7;dow++){var day=(dow+firstDay)%7;thead+="<th"+((dow+firstDay+6)%7>=5?' class="ui-datepicker-week-end"':"")+'><span title="'+dayNames[day]+'">'+dayNamesMin[day]+"</span></th>"}calender+=thead+"</tr></thead><tbody>";var daysInMonth=this._getDaysInMonth(drawYear,drawMonth);if(drawYear==inst.selectedYear&&drawMonth==inst.selectedMonth){inst.selectedDay=Math.min(inst.selectedDay,daysInMonth)}var leadDays=(this._getFirstDayOfMonth(drawYear,drawMonth)-firstDay+7)%7;var numRows=(isMultiMonth?6:Math.ceil((leadDays+daysInMonth)/7));var printDate=this._daylightSavingAdjust(new Date(drawYear,drawMonth,1-leadDays));for(var dRow=0;dRow<numRows;dRow++){calender+="<tr>";var tbody=(!showWeek?"":'<td class="ui-datepicker-week-col">'+this._get(inst,"calculateWeek")(printDate)+"</td>");for(var dow=0;dow<7;dow++){var daySettings=(beforeShowDay?beforeShowDay.apply((inst.input?inst.input[0]:null),[printDate]):[true,""]);var otherMonth=(printDate.getMonth()!=drawMonth);var unselectable=(otherMonth&&!selectOtherMonths)||!daySettings[0]||(minDate&&printDate<minDate)||(maxDate&&printDate>maxDate);tbody+='<td class="'+((dow+firstDay+6)%7>=5?" ui-datepicker-week-end":"")+(otherMonth?" ui-datepicker-other-month":"")+((printDate.getTime()==selectedDate.getTime()&&drawMonth==inst.selectedMonth&&inst._keyEvent)||(defaultDate.getTime()==printDate.getTime()&&defaultDate.getTime()==selectedDate.getTime())?" "+this._dayOverClass:"")+(unselectable?" "+this._unselectableClass+" ui-state-disabled":"")+(otherMonth&&!showOtherMonths?"":" "+daySettings[1]+(printDate.getTime()==currentDate.getTime()?" "+this._currentClass:"")+(printDate.getTime()==today.getTime()?" ui-datepicker-today":""))+'"'+((!otherMonth||showOtherMonths)&&daySettings[2]?' title="'+daySettings[2]+'"':"")+(unselectable?"":' onclick="DP_jQuery_'+dpuuid+".datepicker._selectDay('#"+inst.id+"',"+printDate.getMonth()+","+printDate.getFullYear()+', this);return false;"')+">"+(otherMonth&&!showOtherMonths?"&#xa0;":(unselectable?'<span class="ui-state-default">'+printDate.getDate()+"</span>":'<a class="ui-state-default'+(printDate.getTime()==today.getTime()?" ui-state-highlight":"")+(printDate.getTime()==currentDate.getTime()?" ui-state-active":"")+(otherMonth?" ui-priority-secondary":"")+'" href="#">'+printDate.getDate()+"</a>"))+"</td>";printDate.setDate(printDate.getDate()+1);printDate=this._daylightSavingAdjust(printDate)}calender+=tbody+"</tr>"}drawMonth++;if(drawMonth>11){drawMonth=0;drawYear++}calender+="</tbody></table>"+(isMultiMonth?"</div>"+((numMonths[0]>0&&col==numMonths[1]-1)?'<div class="ui-datepicker-row-break"></div>':""):"");group+=calender}html+=group}html+=buttonPanel+($.browser.msie&&parseInt($.browser.version,10)<7&&!inst.inline?'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>':"");inst._keyEvent=false;return html},_generateMonthYearHeader:function(inst,drawMonth,drawYear,minDate,maxDate,secondary,monthNames,monthNamesShort){var changeMonth=this._get(inst,"changeMonth");var changeYear=this._get(inst,"changeYear");var showMonthAfterYear=this._get(inst,"showMonthAfterYear");var html='<div class="ui-datepicker-title">';var monthHtml="";if(secondary||!changeMonth){monthHtml+='<span class="ui-datepicker-month">'+monthNames[drawMonth]+"</span>"}else{var inMinYear=(minDate&&minDate.getFullYear()==drawYear);var inMaxYear=(maxDate&&maxDate.getFullYear()==drawYear);monthHtml+='<select class="ui-datepicker-month" onchange="DP_jQuery_'+dpuuid+".datepicker._selectMonthYear('#"+inst.id+"', this, 'M');\" onclick=\"DP_jQuery_"+dpuuid+".datepicker._clickMonthYear('#"+inst.id+"');\">";for(var month=0;month<12;month++){if((!inMinYear||month>=minDate.getMonth())&&(!inMaxYear||month<=maxDate.getMonth())){monthHtml+='<option value="'+month+'"'+(month==drawMonth?' selected="selected"':"")+">"+monthNamesShort[month]+"</option>"}}monthHtml+="</select>"}if(!showMonthAfterYear){html+=monthHtml+(secondary||!(changeMonth&&changeYear)?"&#xa0;":"")}if(secondary||!changeYear){html+='<span class="ui-datepicker-year">'+drawYear+"</span>"}else{var years=this._get(inst,"yearRange").split(":");var thisYear=new Date().getFullYear();var determineYear=function(value){var year=(value.match(/c[+-].*/)?drawYear+parseInt(value.substring(1),10):(value.match(/[+-].*/)?thisYear+parseInt(value,10):parseInt(value,10)));return(isNaN(year)?thisYear:year)};var year=determineYear(years[0]);var endYear=Math.max(year,determineYear(years[1]||""));year=(minDate?Math.max(year,minDate.getFullYear()):year);endYear=(maxDate?Math.min(endYear,maxDate.getFullYear()):endYear);html+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+dpuuid+".datepicker._selectMonthYear('#"+inst.id+"', this, 'Y');\" onclick=\"DP_jQuery_"+dpuuid+".datepicker._clickMonthYear('#"+inst.id+"');\">";for(;year<=endYear;year++){html+='<option value="'+year+'"'+(year==drawYear?' selected="selected"':"")+">"+year+"</option>"}html+="</select>"}html+=this._get(inst,"yearSuffix");if(showMonthAfterYear){html+=(secondary||!(changeMonth&&changeYear)?"&#xa0;":"")+monthHtml}html+="</div>";return html},_adjustInstDate:function(inst,offset,period){var year=inst.drawYear+(period=="Y"?offset:0);var month=inst.drawMonth+(period=="M"?offset:0);var day=Math.min(inst.selectedDay,this._getDaysInMonth(year,month))+(period=="D"?offset:0);var date=this._restrictMinMax(inst,this._daylightSavingAdjust(new Date(year,month,day)));inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear();if(period=="M"||period=="Y"){this._notifyChange(inst)}},_restrictMinMax:function(inst,date){var minDate=this._getMinMaxDate(inst,"min");var maxDate=this._getMinMaxDate(inst,"max");date=(minDate&&date<minDate?minDate:date);date=(maxDate&&date>maxDate?maxDate:date);return date},_notifyChange:function(inst){var onChange=this._get(inst,"onChangeMonthYear");if(onChange){onChange.apply((inst.input?inst.input[0]:null),[inst.selectedYear,inst.selectedMonth+1,inst])}},_getNumberOfMonths:function(inst){var numMonths=this._get(inst,"numberOfMonths");return(numMonths==null?[1,1]:(typeof numMonths=="number"?[1,numMonths]:numMonths))},_getMinMaxDate:function(inst,minMax){return this._determineDate(inst,this._get(inst,minMax+"Date"),null)},_getDaysInMonth:function(year,month){return 32-new Date(year,month,32).getDate()},_getFirstDayOfMonth:function(year,month){return new Date(year,month,1).getDay()},_canAdjustMonth:function(inst,offset,curYear,curMonth){var numMonths=this._getNumberOfMonths(inst);var date=this._daylightSavingAdjust(new Date(curYear,curMonth+(offset<0?offset:numMonths[0]*numMonths[1]),1));if(offset<0){date.setDate(this._getDaysInMonth(date.getFullYear(),date.getMonth()))}return this._isInRange(inst,date)},_isInRange:function(inst,date){var minDate=this._getMinMaxDate(inst,"min");var maxDate=this._getMinMaxDate(inst,"max");return((!minDate||date.getTime()>=minDate.getTime())&&(!maxDate||date.getTime()<=maxDate.getTime()))},_getFormatConfig:function(inst){var shortYearCutoff=this._get(inst,"shortYearCutoff");shortYearCutoff=(typeof shortYearCutoff!="string"?shortYearCutoff:new Date().getFullYear()%100+parseInt(shortYearCutoff,10));return{shortYearCutoff:shortYearCutoff,dayNamesShort:this._get(inst,"dayNamesShort"),dayNames:this._get(inst,"dayNames"),monthNamesShort:this._get(inst,"monthNamesShort"),monthNames:this._get(inst,"monthNames")}},_formatDate:function(inst,day,month,year){if(!day){inst.currentDay=inst.selectedDay;inst.currentMonth=inst.selectedMonth;inst.currentYear=inst.selectedYear}var date=(day?(typeof day=="object"?day:this._daylightSavingAdjust(new Date(year,month,day))):this._daylightSavingAdjust(new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));return this.formatDate(this._get(inst,"dateFormat"),date,this._getFormatConfig(inst))}});function extendRemove(target,props){$.extend(target,props);for(var name in props){if(props[name]==null||props[name]==undefined){target[name]=props[name]}}return target}function isArray(a){return(a&&(($.browser.safari&&typeof a=="object"&&a.length)||(a.constructor&&a.constructor.toString().match(/\Array\(\)/))))}$.fn.datepicker=function(options){if(!$.datepicker.initialized){$(document).mousedown($.datepicker._checkExternalClick).find("body").append($.datepicker.dpDiv);$.datepicker.initialized=true}var otherArgs=Array.prototype.slice.call(arguments,1);if(typeof options=="string"&&(options=="isDisabled"||options=="getDate"||options=="widget")){return $.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this[0]].concat(otherArgs))}if(options=="option"&&arguments.length==2&&typeof arguments[1]=="string"){return $.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this[0]].concat(otherArgs))}return this.each(function(){typeof options=="string"?$.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this].concat(otherArgs)):$.datepicker._attachDatepicker(this,options)})};$.datepicker=new Datepicker();$.datepicker.initialized=false;$.datepicker.uuid=new Date().getTime();$.datepicker.version="1.8rc3";window["DP_jQuery_"+dpuuid]=$})(jQuery);;


/*
 ### jQuery Multiple File Upload Plugin v1.47 - 2010-03-26 ###
 * Home: http://www.fyneworks.com/jquery/multiple-file-upload/
 * Code: http://code.google.com/p/jquery-multifile-plugin/
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 ###
*/
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}(';3(X.1M)(6($){$.7.2=6(h){3(5.Q==0)8 5;3(R U[0]==\'1f\'){3(5.Q>1){l i=U;8 5.N(6(){$.7.2.14($(5),i)})};$.7.2[U[0]].14(5,$.27(U).26(1)||[]);8 5};l h=$.L({},$.7.2.D,h||{});$(\'21\').1D(\'2-S\').V(\'2-S\').1i($.7.2.15);3($.7.2.D.12){$.7.2.1s($.7.2.D.12);$.7.2.D.12=11};5.1D(\'.2-1a\').V(\'2-1a\').N(6(){X.2=(X.2||0)+1;l e=X.2;l g={e:5,E:$(5),P:$(5).P()};3(R h==\'1W\')h={m:h};l o=$.L({},$.7.2.D,h||{},($.1p?g.E.1p():($.2t?g.E.Z():11))||{},{});3(!(o.m>0)){o.m=g.E.K(\'2e\');3(!(o.m>0)){o.m=(u(g.e.1o.B(/\\b(m|2a)\\-([0-9]+)\\b/q)||[\'\']).B(/[0-9]+/q)||[\'\'])[0];3(!(o.m>0))o.m=-1;1Z o.m=u(o.m).B(/[0-9]+/q)[0]}};o.m=18 1X(o.m);o.j=o.j||g.E.K(\'j\')||\'\';3(!o.j){o.j=(g.e.1o.B(/\\b(j\\-[\\w\\|]+)\\b/q))||\'\';o.j=18 u(o.j).t(/^(j|1e)\\-/i,\'\')};$.L(g,o||{});g.A=$.L({},$.7.2.D.A,g.A);$.L(g,{n:0,J:[],2c:[],19:g.e.I||\'2\'+u(e),1k:6(z){8 g.19+(z>0?\'1U\'+u(z):\'\')},G:6(a,b){l c=g[a],k=$(b).K(\'k\');3(c){l d=c(b,k,g);3(d!=11)8 d}8 1h}});3(u(g.j).Q>1){g.j=g.j.t(/\\W+/g,\'|\').t(/^\\W|\\W$/g,\'\');g.1w=18 2h(\'\\\\.(\'+(g.j?g.j:\'\')+\')$\',\'q\')};g.M=g.19+\'25\';g.E.1j(\'<O T="2-1j" I="\'+g.M+\'"></O>\');g.1l=$(\'#\'+g.M+\'\');g.e.H=g.e.H||\'p\'+e+\'[]\';3(!g.C){g.1l.1d(\'<O T="2-C" I="\'+g.M+\'1m"></O>\');g.C=$(\'#\'+g.M+\'1m\')};g.C=$(g.C);g.10=6(c,d){g.n++;c.2=g;3(d>0)c.I=c.H=\'\';3(d>0)c.I=g.1k(d);c.H=u(g.1n.t(/\\$H/q,$(g.P).K(\'H\')).t(/\\$I/q,$(g.P).K(\'I\')).t(/\\$g/q,e).t(/\\$i/q,d));3((g.m>0)&&((g.n-1)>(g.m)))c.16=1h;g.17=g.J[d]=c;c=$(c);c.1g(\'\').K(\'k\',\'\')[0].k=\'\';c.V(\'2-1a\');c.2z(6(){$(5).1O();3(!g.G(\'1R\',5,g))8 y;l a=\'\',v=u(5.k||\'\');3(g.j&&v&&!v.B(g.1w))a=g.A.1q.t(\'$1e\',u(v.B(/\\.\\w{1,4}$/q)));1r(l f 29 g.J)3(g.J[f]&&g.J[f]!=5)3(g.J[f].k==v)a=g.A.1t.t(\'$p\',v.B(/[^\\/\\\\]+$/q));l b=$(g.P).P();b.V(\'2\');3(a!=\'\'){g.1u(a);g.n--;g.10(b[0],d);c.1v().2d(b);c.F();8 y};$(5).1x({1y:\'1N\',1z:\'-1P\'});c.1Q(b);g.1A(5,d);g.10(b[0],d+1);3(!g.G(\'1S\',5,g))8 y});$(c).Z(\'2\',g)};g.1A=6(c,d){3(!g.G(\'1T\',c,g))8 y;l r=$(\'<O T="2-1V"></O>\'),v=u(c.k||\'\'),a=$(\'<1B T="2-1C" 1C="\'+g.A.Y.t(\'$p\',v)+\'">\'+g.A.p.t(\'$p\',v.B(/[^\\/\\\\]+$/q)[0])+\'</1B>\'),b=$(\'<a T="2-F" 1Y="#\'+g.M+\'">\'+g.A.F+\'</a>\');g.C.1d(r.1d(b,\' \',a));b.1E(6(){3(!g.G(\'20\',c,g))8 y;g.n--;g.17.16=y;g.J[d]=11;$(c).F();$(5).1v().F();$(g.17).1x({1y:\'\',1z:\'\'});$(g.17).13().1g(\'\').K(\'k\',\'\')[0].k=\'\';3(!g.G(\'22\',c,g))8 y;8 y});3(!g.G(\'23\',c,g))8 y};3(!g.2)g.10(g.e,0);g.n++;g.E.Z(\'2\',g)})};$.L($.7.2,{13:6(){l a=$(5).Z(\'2\');3(a)a.C.24(\'a.2-F\').1E();8 $(5)},15:6(a){a=(R(a)==\'1f\'?a:\'\')||\'1F\';l o=[];$(\'1b:p.2\').N(6(){3($(5).1g()==\'\')o[o.Q]=5});8 $(o).N(6(){5.16=1h}).V(a)},1c:6(a){a=(R(a)==\'1f\'?a:\'\')||\'1F\';8 $(\'1b:p.\'+a).28(a).N(6(){5.16=y})},S:{},1s:6(b,c,d){l e,k;d=d||[];3(d.1G.1H().1I("1J")<0)d=[d];3(R(b)==\'6\'){$.7.2.15();k=b.14(c||X,d);1K(6(){$.7.2.1c()},1L);8 k};3(b.1G.1H().1I("1J")<0)b=[b];1r(l i=0;i<b.Q;i++){e=b[i]+\'\';3(e)(6(a){$.7.2.S[a]=$.7[a]||6(){};$.7[a]=6(){$.7.2.15();k=$.7.2.S[a].14(5,U);1K(6(){$.7.2.1c()},1L);8 k}})(e)}}});$.7.2.D={j:\'\',m:-1,1n:\'$H\',A:{F:\'x\',1q:\'2f 2g 2b a $1e p.\\2i 2j...\',p:\'$p\',Y:\'2k Y: $p\',1t:\'2l p 2m 2n 2o Y:\\n$p\'},12:[\'1i\',\'2p\',\'2q\',\'2r\',\'2s\'],1u:6(s){2u(s)}};$.7.13=6(){8 5.N(6(){2v{5.13()}2w(e){}})};$(6(){$("1b[2x=p].2y").2()})})(1M);',62,160,'||MultiFile|if||this|function|fn|return|||||||||||accept|value|var|max|||file|gi|||replace|String||||false||STRING|match|list|options||remove|trigger|name|id|slaves|attr|extend|wrapID|each|div|clone|length|typeof|intercepted|class|arguments|addClass||window|selected|data|addSlave|null|autoIntercept|reset|apply|disableEmpty|disabled|current|new|instanceKey|applied|input|reEnableEmpty|append|ext|string|val|true|submit|wrap|generateID|wrapper|_list|namePattern|className|metadata|denied|for|intercept|duplicate|error|parent|rxAccept|css|position|top|addToList|span|title|not|click|mfD|constructor|toString|indexOf|Array|setTimeout|1000|jQuery|absolute|blur|3000px|after|onFileSelect|afterFileSelect|onFileAppend|_F|label|number|Number|href|else|onFileRemove|form|afterFileRemove|afterFileAppend|find|_wrap|slice|makeArray|removeClass|in|limit|select|files|prepend|maxlength|You|cannot|RegExp|nTry|again|File|This|has|already|been|ajaxSubmit|ajaxForm|validate|valid|meta|alert|try|catch|type|multi|change'.split('|'),0,{}))

/*
 * jQuery Form Plugin
 * version: 2.36 (07-NOV-2009)
 * @requires jQuery v1.2.6 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
;(function($) {

/*
	Usage Note:
	-----------
	Do not use both ajaxSubmit and ajaxForm on the same form.  These
	functions are intended to be exclusive.  Use ajaxSubmit if you want
	to bind your own submit handler to the form.  For example,

	$(document).ready(function() {
		$('#myForm').bind('submit', function() {
			$(this).ajaxSubmit({
				target: '#output'
			});
			return false; // <-- important!
		});
	});

	Use ajaxForm when you want the plugin to manage all the event binding
	for you.  For example,

	$(document).ready(function() {
		$('#myForm').ajaxForm({
			target: '#output'
		});
	});

	When using ajaxForm, the ajaxSubmit function will be invoked for you
	at the appropriate time.
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
	// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
	if (!this.length) {
		log('ajaxSubmit: skipping submit process - no element selected');
		return this;
	}

	if (typeof options == 'function')
		options = { success: options };

	var url = $.trim(this.attr('action'));
	if (url) {
		// clean url (don't include hash vaue)
		url = (url.match(/^([^#]+)/)||[])[1];
   	}
   	url = url || window.location.href || '';

	options = $.extend({
		url:  url,
		type: this.attr('method') || 'GET',
		iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
	}, options || {});

	// hook for manipulating the form data before it is extracted;
	// convenient for use with rich editors like tinyMCE or FCKEditor
	var veto = {};
	this.trigger('form-pre-serialize', [this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
		return this;
	}

	// provide opportunity to alter form data before it is serialized
	if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSerialize callback');
		return this;
	}

	var a = this.formToArray(options.semantic);
	if (options.data) {
		options.extraData = options.data;
		for (var n in options.data) {
		  if(options.data[n] instanceof Array) {
			for (var k in options.data[n])
			  a.push( { name: n, value: options.data[n][k] } );
		  }
		  else
			 a.push( { name: n, value: options.data[n] } );
		}
	}

	// give pre-submit callback an opportunity to abort the submit
	if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSubmit callback');
		return this;
	}

	// fire vetoable 'validate' event
	this.trigger('form-submit-validate', [a, this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
		return this;
	}

	var q = $.param(a);

	if (options.type.toUpperCase() == 'GET') {
		options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
		options.data = null;  // data is null for 'get'
	}
	else
		options.data = q; // data is the query string for 'post'

	var $form = this, callbacks = [];
	if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
	if (options.clearForm) callbacks.push(function() { $form.clearForm(); });

	// perform a load on the target only if dataType is not provided
	if (!options.dataType && options.target) {
		var oldSuccess = options.success || function(){};
		callbacks.push(function(data) {
			$(options.target).html(data).each(oldSuccess, arguments);
		});
	}
	else if (options.success)
		callbacks.push(options.success);

	options.success = function(data, status) {
		for (var i=0, max=callbacks.length; i < max; i++)
			callbacks[i].apply(options, [data, status, $form]);
	};

	// are there files to upload?
	var files = $('input:file', this).fieldValue();
	var found = false;
	for (var j=0; j < files.length; j++)
		if (files[j])
			found = true;

	var multipart = false;
//	var mp = 'multipart/form-data';
//	multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);

	// options.iframe allows user to force iframe mode
	// 06-NOV-09: now defaulting to iframe mode if file input is detected
   if ((files.length && options.iframe !== false) || options.iframe || found || multipart) {
	   // hack to fix Safari hang (thanks to Tim Molendijk for this)
	   // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
	   if (options.closeKeepAlive)
		   $.get(options.closeKeepAlive, fileUpload);
	   else
		   fileUpload();
	   }
   else
	   $.ajax(options);

	// fire 'notify' event
	this.trigger('form-submit-notify', [this, options]);
	return this;


	// private function for handling file uploads (hat tip to YAHOO!)
	function fileUpload() {
		var form = $form[0];

		if ($(':input[name=submit]', form).length) {
			alert('Error: Form elements must not be named "submit".');
			return;
		}

		var opts = $.extend({}, $.ajaxSettings, options);
		var s = $.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);

		var id = 'jqFormIO' + (new Date().getTime());
		var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ opts.iframeSrc +'" />');
		var io = $io[0];

		$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

		var xhr = { // mock object
			aborted: 0,
			responseText: null,
			responseXML: null,
			status: 0,
			statusText: 'n/a',
			getAllResponseHeaders: function() {},
			getResponseHeader: function() {},
			setRequestHeader: function() {},
			abort: function() {
				this.aborted = 1;
				$io.attr('src', opts.iframeSrc); // abort op in progress
			}
		};

		var g = opts.global;
		// trigger ajax global events so that activity/block indicators work like normal
		if (g && ! $.active++) $.event.trigger("ajaxStart");
		if (g) $.event.trigger("ajaxSend", [xhr, opts]);

		if (s.beforeSend && s.beforeSend(xhr, s) === false) {
			s.global && $.active--;
			return;
		}
		if (xhr.aborted)
			return;

		var cbInvoked = 0;
		var timedOut = 0;

		// add submitting element to data if we know it
		var sub = form.clk;
		if (sub) {
			var n = sub.name;
			if (n && !sub.disabled) {
				options.extraData = options.extraData || {};
				options.extraData[n] = sub.value;
				if (sub.type == "image") {
					options.extraData[name+'.x'] = form.clk_x;
					options.extraData[name+'.y'] = form.clk_y;
				}
			}
		}

		// take a breath so that pending repaints get some cpu time before the upload starts
		setTimeout(function() {
			// make sure form attrs are set
			var t = $form.attr('target'), a = $form.attr('action');

			// update form attrs in IE friendly way
			form.setAttribute('target',id);
			if (form.getAttribute('method') != 'POST')
				form.setAttribute('method', 'POST');
			if (form.getAttribute('action') != opts.url)
				form.setAttribute('action', opts.url);

			// ie borks in some cases when setting encoding
			if (! options.skipEncodingOverride) {
				$form.attr({
					encoding: 'multipart/form-data',
					enctype:  'multipart/form-data'
				});
			}

			// support timout
			if (opts.timeout)
				setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

			// add "extra" data to form if provided in options
			var extraInputs = [];
			try {
				if (options.extraData)
					for (var n in options.extraData)
						extraInputs.push(
							$('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
								.appendTo(form)[0]);

				// add iframe to doc and submit the form
				$io.appendTo('body');
				io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
				form.submit();
			}
			finally {
				// reset attrs and remove "extra" input elements
				form.setAttribute('action',a);
				t ? form.setAttribute('target', t) : $form.removeAttr('target');
				$(extraInputs).remove();
			}
		}, 10);

		var domCheckCount = 50;

		function cb() {
			if (cbInvoked++) return;

			io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

			var ok = true;
			try {
				if (timedOut) throw 'timeout';
				// extract the server response from the iframe
				var data, doc;

				doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
				
				var isXml = opts.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
				log('isXml='+isXml);
				if (!isXml && (doc.body == null || doc.body.innerHTML == '')) {
				 	if (--domCheckCount) {
						// in some browsers (Opera) the iframe DOM is not always traversable when
						// the onload callback fires, so we loop a bit to accommodate
						cbInvoked = 0;
						setTimeout(cb, 100);
						return;
					}
					log('Could not access iframe DOM after 50 tries.');
					return;
				}

				xhr.responseText = doc.body ? doc.body.innerHTML : null;
				xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
				xhr.getResponseHeader = function(header){
					var headers = {'content-type': opts.dataType};
					return headers[header];
				};

				if (opts.dataType == 'json' || opts.dataType == 'script') {
					// see if user embedded response in textarea
					var ta = doc.getElementsByTagName('textarea')[0];
					if (ta)
						xhr.responseText = ta.value;
					else {
						// account for browsers injecting pre around json response
						var pre = doc.getElementsByTagName('pre')[0];
						if (pre)
							xhr.responseText = pre.innerHTML;
					}			  
				}
				else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
					xhr.responseXML = toXml(xhr.responseText);
				}
				data = $.httpData(xhr, opts.dataType);
			}
			catch(e){
				ok = false;
				$.handleError(opts, xhr, 'error', e);
			}

			// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
			if (ok) {
				opts.success(data, 'success');
				if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
			}
			if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
			if (g && ! --$.active) $.event.trigger("ajaxStop");
			if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

			// clean up
			setTimeout(function() {
				$io.remove();
				xhr.responseXML = null;
			}, 100);
		};

		function toXml(s, doc) {
			if (window.ActiveXObject) {
				doc = new ActiveXObject('Microsoft.XMLDOM');
				doc.async = 'false';
				doc.loadXML(s);
			}
			else
				doc = (new DOMParser()).parseFromString(s, 'text/xml');
			return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
		};
	};
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *	is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *	used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */
$.fn.ajaxForm = function(options) {
	return this.ajaxFormUnbind().bind('submit.form-plugin', function() {
		$(this).ajaxSubmit(options);
		return false;
	}).bind('click.form-plugin', function(e) {
		var target = e.target;
		var $el = $(target);
		if (!($el.is(":submit,input:image"))) {
			// is this a child element of the submit el?  (ex: a span within a button)
			var t = $el.closest(':submit');
			if (t.length == 0)
				return;
			target = t[0];
		}
		var form = this;
		form.clk = target;
		if (target.type == 'image') {
			if (e.offsetX != undefined) {
				form.clk_x = e.offsetX;
				form.clk_y = e.offsetY;
			} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
				var offset = $el.offset();
				form.clk_x = e.pageX - offset.left;
				form.clk_y = e.pageY - offset.top;
			} else {
				form.clk_x = e.pageX - target.offsetLeft;
				form.clk_y = e.pageY - target.offsetTop;
			}
		}
		// clear form vars
		setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
	});
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
	return this.unbind('submit.form-plugin click.form-plugin');
};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
	var a = [];
	if (this.length == 0) return a;

	var form = this[0];
	var els = semantic ? form.getElementsByTagName('*') : form.elements;
	if (!els) return a;
	for(var i=0, max=els.length; i < max; i++) {
		var el = els[i];
		var n = el.name;
		if (!n) continue;

		if (semantic && form.clk && el.type == "image") {
			// handle image inputs on the fly when semantic == true
			if(!el.disabled && form.clk == el) {
				a.push({name: n, value: $(el).val()});
				a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
			}
			continue;
		}

		var v = $.fieldValue(el, true);
		if (v && v.constructor == Array) {
			for(var j=0, jmax=v.length; j < jmax; j++)
				a.push({name: n, value: v[j]});
		}
		else if (v !== null && typeof v != 'undefined')
			a.push({name: n, value: v});
	}

	if (!semantic && form.clk) {
		// input type=='image' are not found in elements array! handle it here
		var $input = $(form.clk), input = $input[0], n = input.name;
		if (n && !input.disabled && input.type == 'image') {
			a.push({name: n, value: $input.val()});
			a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
		}
	}
	return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
	//hand off to jQuery.param for proper encoding
	return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
	var a = [];
	this.each(function() {
		var n = this.name;
		if (!n) return;
		var v = $.fieldValue(this, successful);
		if (v && v.constructor == Array) {
			for (var i=0,max=v.length; i < max; i++)
				a.push({name: n, value: v[i]});
		}
		else if (v !== null && typeof v != 'undefined')
			a.push({name: this.name, value: v});
	});
	//hand off to jQuery.param for proper encoding
	return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *	  <input name="A" type="text" />
 *	  <input name="A" type="text" />
 *	  <input name="B" type="checkbox" value="B1" />
 *	  <input name="B" type="checkbox" value="B2"/>
 *	  <input name="C" type="radio" value="C1" />
 *	  <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *	   array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
	for (var val=[], i=0, max=this.length; i < max; i++) {
		var el = this[i];
		var v = $.fieldValue(el, successful);
		if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
			continue;
		v.constructor == Array ? $.merge(val, v) : val.push(v);
	}
	return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
	var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
	if (typeof successful == 'undefined') successful = true;

	if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
		(t == 'checkbox' || t == 'radio') && !el.checked ||
		(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
		tag == 'select' && el.selectedIndex == -1))
			return null;

	if (tag == 'select') {
		var index = el.selectedIndex;
		if (index < 0) return null;
		var a = [], ops = el.options;
		var one = (t == 'select-one');
		var max = (one ? index+1 : ops.length);
		for(var i=(one ? index : 0); i < max; i++) {
			var op = ops[i];
			if (op.selected) {
				var v = op.value;
				if (!v) // extra pain for IE...
					v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
				if (one) return v;
				a.push(v);
			}
		}
		return a;
	}
	return el.value;
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
	return this.each(function() {
		$('input,select,textarea', this).clearFields();
	});
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
	return this.each(function() {
		var t = this.type, tag = this.tagName.toLowerCase();
		if (t == 'text' || t == 'password' || tag == 'textarea')
			this.value = '';
		else if (t == 'checkbox' || t == 'radio')
			this.checked = false;
		else if (tag == 'select')
			this.selectedIndex = -1;
	});
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
	return this.each(function() {
		// guard against an input with the name of 'reset'
		// note that IE reports the reset function as an 'object'
		if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
			this.reset();
	});
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) {
	if (b == undefined) b = true;
	return this.each(function() {
		this.disabled = !b;
	});
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
	if (select == undefined) select = true;
	return this.each(function() {
		var t = this.type;
		if (t == 'checkbox' || t == 'radio')
			this.checked = select;
		else if (this.tagName.toLowerCase() == 'option') {
			var $sel = $(this).parent('select');
			if (select && $sel[0] && $sel[0].type == 'select-one') {
				// deselect all other options
				$sel.find('option').selected(false);
			}
			this.selected = select;
		}
	});
};

// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
	if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
		window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};

})(jQuery);

/*
 *
 * Copyright (c) 2009 C. F., Wong (<a href="http://cloudgen.w0ng.hk">Cloudgen Examplet Store</a>)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * See details in: <a href="http://cloudgen.w0ng.hk/javascript/javascript.php">Javascript Examplet</a>
 *
 */
(function($){
	$.fn.caret=function(options,opt2){
		var start,end,t=this[0];
		if(typeof options==="object" && typeof options.start==="number" && typeof options.end==="number") {
			start=options.start;
			end=options.end;
		} else if(typeof options==="number" && typeof opt2==="number"){
			start=options;
			end=opt2;
		} else if(typeof options==="string"){
			if((start=t.value.indexOf(options))>-1) end=start+options.length;
			else start=null;
		} else if(Object.prototype.toString.call(options)==="[object RegExp]"){
			var re=options.exec(t.value);
			if(re != null) {
				start=re.index;
				end=start+re[0].length;
			}
		}
		if(typeof start!="undefined"){
			if($.browser.msie){
				var selRange = this[0].createTextRange();
				selRange.collapse(true);
				selRange.moveStart('character', start);
				selRange.moveEnd('character', end-start);
				selRange.select();
			} else {
				this[0].selectionStart=start;
				this[0].selectionEnd=end;
			}
			this[0].focus();
			return this
		} else {
			if($.browser.msie){
				var val = this.val();
				var range = document.selection.createRange().duplicate();
				range.moveEnd("character", val.length)
				var s = (range.text == "" ? val.length : val.lastIndexOf(range.text));
				range = document.selection.createRange().duplicate();
				range.moveStart("character", -val.length);
				var e = range.text.length;				
			} else {
				var s=t.selectionStart,
					e=t.selectionEnd;
			}
			var te=t.value.substring(s,e);
			return {start:s,end:e,text:te,replace:function(st){
				return t.value.substring(0,s)+st+t.value.substring(e,t.value.length)
			}}
		}
		return this;
	}
})(jQuery);

// jQuery Month Calendar Plugin 1.0 Copyright 2009 Jarrett Vance http://jvance.com/pages/jQueryMonthCalPlugin.xhtml
(function ($) {
  $.fn.calendar = function (options) {
    var opts = $.extend({}, $.fn.calendar.defaults, options);
       
    return this.each(function () {
    printDate = new String();
    printDate = getUrl(opts.current, opts);

      var $this = $(this);
      $this.find('td')
        .hover(function () { $(this).addClass('hover') }, function () { $(this).removeClass('hover') })
        .live('click', function () { 
        	printDate =  $(this).find('a').attr('title');
        	
        	changeCalDate($(this).find('a').attr('title')); //Call the calendar changing function from fambit.js (need to do it from here to get the correct date for next month)
        	
        	
        		if (typeof(area) != "undefined" && area == "calendar") {
        		return changeDay($this, $(this), new Date($(this).find('a').attr('title')), opts);
        		
        	}
        	
        });
      $this.find('a[rel=prev], a[rel=next]').click(function () {
        changeMonth($this, opts, ($(this).attr('rel') == 'next'));
        return false;
      });
      refreshCal($this, opts);
     /* Calendar Print */
		$("#printCalendarView").live("click", function (){
			window.open(base_url+'calendar/printView/1/0/'+printDate.replace(/\//g, '-')+'/'+calForward);		
		});
	/* Calendar Month PDF-print */
		$("#printCalendarMonth").live("click", function (){
			printDateArray = printDate.split('/');
			window.open(base_url+'calendar?print=true&month='+printDateArray[1], "pdf", "width=600, height=400");
		});
	 
    });
  }

  function changeMonth($cal, opts, next) {
    if (next && opts.month == 11) {
    var year = new Date(opts.year, opts.month, 1);
  
    opts.year = year.getFullYear()+1;
    
   
    
      opts.month = 0;
    } else if (!next && opts.month == 0) {
      opts.year = opts.year - 1;
      opts.month = 11;
    } else {
      opts.month = next ? opts.month + 1 : opts.month - 1;
    }
    refreshCal($cal, opts);
  }

  function changeDay($cal, $cell, date, opts) {
    opts.current = date;
    opts.year = date.getFullYear();
    opts.month = date.getMonth();
    refreshCal($cal, opts);
    
    //allow outside cancel
    return opts.dateChanged(date);
  };

  function refreshCal($cal, opts) {
  	var monthNames = new Array();
    monthNames['en'] = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    monthNames['fi'] = ['Tammikuu', 'Helmikuu', 'Maaliskuu', 'Huhtikuu', 'Toukokuu', 'Kesäkuu', 'Heinäkuu', 'Elokuu', 'Syyskuu', 'Lokakuu', 'Marraskuu', 'Joulukuu'];
    monthNames['fr'] = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'];
    monthNames['pt'] = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Decembro'];
   monthNames['de'] = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
    
    $cal.find('.month').empty();
    $cal.find('.month').append('<a href="http://'+host_url+'calendar/index/'+opts.year+'-'+(opts.month+1)+'-1">'+monthNames[lang][opts.month] + ' ' + opts.year+'</a>');
    $cal.find('td').removeClass('out').removeClass('today').removeClass('current');
    var days = getDaysInMonthForDate(opts.year, opts.month, opts.current);
    var tds = $cal.find('td');
    for (j = 0; j < 42; j++) {
      $(tds[j]).find('a').text(days[j].date.getDate())
        .attr('title', /*days[j].date.toDateString()*/getUrl(days[j].date, opts))
        .attr('href', /*getUrl(days[j].date, opts)*/opts.naviUrl+getUrl(days[j].date, opts));
      if (days[j].out) $(tds[j]).addClass('out');
      if (days[j].current) $(tds[j]).addClass('current');
      if (days[j].today) $(tds[j]).addClass('today');
    }
    
    //Get dates with events on them from Ajax.php
  
    	
	    var postUrl = getUrl(days[0].date, opts);
	    postUrl = postUrl.replace(/\//g, "-");
	    if(typeof(familyLastRead) != "undefined") {
	    	postUrl = postUrl+"/"+familyLastRead;
	    }
	    
	    get("ajax/getDatesWithEvents/" + postUrl, {
			}, function(data) {
			
			//$(".calendarStreamUl").append(data.output);
			
			$("#cal-navigation a").each(function() {
				myDate = $(this).attr('title');
				
				myDate = myDate.replace(/-/g, "");
				myDate = myDate.replace(/\//g, "");
				if(typeof(data.output[myDate]) != "undefined") {
					
					$(this).addClass('hasEvents');	
				}
				
			});
			
			/*
			for (var i in data.output) {
				thisDate = data.output[i];	
				
				$("#cal-navigation [title='"+thisDate+"']").addClass("hasEvents");
				thisDate = thisDate.replace(/\//g, "-");
				$("#cal-navigation [title='"+thisDate+"']").addClass("hasEvents");
			}
			*/
			
			
		});
    
   		
  }

  function getUrl(date, opts) {
    var url = opts.templateUrl;
    url = url.replace(opts.templateYear, date.getFullYear());
    url = url.replace(opts.templateMonth, ((date.getMonth() + 1) < 10 ? "0" : "") + (date.getMonth() + 1));
    url = url.replace(opts.templateDay, (date.getDate() < 10 ? "0" : "") + date.getDate());
    return url;
  }


  function getDaysInMonthForDate(year, month, current) {
    var today = new Date();
    var first = new Date(year, month, 1);
    first.setDate(first.getDate() - first.getDay());

    var days = new Array(42);
    for (j = 0; j < 42; j++) {
      var d = new Date(first);
      d.setDate(first.getDate() + j +1);
      days[j] = {
        date: d,
        out: !(d.getFullYear() == year && d.getMonth() == month),
        today: d.getFullYear() == today.getFullYear() && d.getMonth() == today.getMonth() && d.getDate() == today.getDate(),
        current: d.getFullYear() == current.getFullYear() && d.getMonth() == current.getMonth() && d.getDate() == current.getDate()
      }
    }
    return days;
  };

  $.fn.calendar.defaults = {
    current: new Date(),
    year: new Date().getFullYear(),
    month: new Date().getMonth(),
    templateYear: 'year',
    templateMonth: 'month',
    templateDay: 'day',
    templateUrl: 'year-month-day',
    naviUrl: '#',
    dateChanged: function (date) { return true; }
  };
})(jQuery);

Encoder = {

	// When encoding do we convert characters into html or numerical entities
	EncodeType : "entity",  // entity OR numerical

	isEmpty : function(val){
		if(val){
			return ((val===null) || val.length==0 || /^\s+$/.test(val));
		}else{
			return true;
		}
	},
	// Convert HTML entities into numerical entities
	HTML2Numerical : function(s){
		var arr1 = new Array('&nbsp;','&iexcl;','&cent;','&pound;','&curren;','&yen;','&brvbar;','&sect;','&uml;','&copy;','&ordf;','&laquo;','&not;','&shy;','&reg;','&macr;','&deg;','&plusmn;','&sup2;','&sup3;','&acute;','&micro;','&para;','&middot;','&cedil;','&sup1;','&ordm;','&raquo;','&frac14;','&frac12;','&frac34;','&iquest;','&agrave;','&aacute;','&acirc;','&atilde;','&Auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&Ouml;','&times;','&oslash;','&ugrave;','&uacute;','&ucirc;','&Uuml;','&yacute;','&thorn;','&szlig;','&agrave;','&aacute;','&acirc;','&atilde;','&auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&ouml;','&divide;','&oslash;','&ugrave;','&uacute;','&ucirc;','&uuml;','&yacute;','&thorn;','&yuml;','&quot;','&amp;','&lt;','&gt;','&oelig;','&oelig;','&scaron;','&scaron;','&yuml;','&circ;','&tilde;','&ensp;','&emsp;','&thinsp;','&zwnj;','&zwj;','&lrm;','&rlm;','&ndash;','&mdash;','&lsquo;','&rsquo;','&sbquo;','&ldquo;','&rdquo;','&bdquo;','&dagger;','&dagger;','&permil;','&lsaquo;','&rsaquo;','&euro;','&fnof;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigmaf;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&thetasym;','&upsih;','&piv;','&bull;','&hellip;','&prime;','&prime;','&oline;','&frasl;','&weierp;','&image;','&real;','&trade;','&alefsym;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&crarr;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&forall;','&part;','&exist;','&empty;','&nabla;','&isin;','&notin;','&ni;','&prod;','&sum;','&minus;','&lowast;','&radic;','&prop;','&infin;','&ang;','&and;','&or;','&cap;','&cup;','&int;','&there4;','&sim;','&cong;','&asymp;','&ne;','&equiv;','&le;','&ge;','&sub;','&sup;','&nsub;','&sube;','&supe;','&oplus;','&otimes;','&perp;','&sdot;','&lceil;','&rceil;','&lfloor;','&rfloor;','&lang;','&rang;','&loz;','&spades;','&clubs;','&hearts;','&diams;');
		var arr2 = new Array('&#160;','&#161;','&#162;','&#163;','&#164;','&#165;','&#166;','&#167;','&#168;','&#169;','&#170;','&#171;','&#172;','&#173;','&#174;','&#175;','&#176;','&#177;','&#178;','&#179;','&#180;','&#181;','&#182;','&#183;','&#184;','&#185;','&#186;','&#187;','&#188;','&#189;','&#190;','&#191;','&#192;','&#193;','&#194;','&#195;','&#196;','&#197;','&#198;','&#199;','&#200;','&#201;','&#202;','&#203;','&#204;','&#205;','&#206;','&#207;','&#208;','&#209;','&#210;','&#211;','&#212;','&#213;','&#214;','&#215;','&#216;','&#217;','&#218;','&#219;','&#220;','&#221;','&#222;','&#223;','&#224;','&#225;','&#226;','&#227;','&#228;','&#229;','&#230;','&#231;','&#232;','&#233;','&#234;','&#235;','&#236;','&#237;','&#238;','&#239;','&#240;','&#241;','&#242;','&#243;','&#244;','&#245;','&#246;','&#247;','&#248;','&#249;','&#250;','&#251;','&#252;','&#253;','&#254;','&#255;','&#34;','&#38;','&#60;','&#62;','&#338;','&#339;','&#352;','&#353;','&#376;','&#710;','&#732;','&#8194;','&#8195;','&#8201;','&#8204;','&#8205;','&#8206;','&#8207;','&#8211;','&#8212;','&#8216;','&#8217;','&#8218;','&#8220;','&#8221;','&#8222;','&#8224;','&#8225;','&#8240;','&#8249;','&#8250;','&#8364;','&#402;','&#913;','&#914;','&#915;','&#916;','&#917;','&#918;','&#919;','&#920;','&#921;','&#922;','&#923;','&#924;','&#925;','&#926;','&#927;','&#928;','&#929;','&#931;','&#932;','&#933;','&#934;','&#935;','&#936;','&#937;','&#945;','&#946;','&#947;','&#948;','&#949;','&#950;','&#951;','&#952;','&#953;','&#954;','&#955;','&#956;','&#957;','&#958;','&#959;','&#960;','&#961;','&#962;','&#963;','&#964;','&#965;','&#966;','&#967;','&#968;','&#969;','&#977;','&#978;','&#982;','&#8226;','&#8230;','&#8242;','&#8243;','&#8254;','&#8260;','&#8472;','&#8465;','&#8476;','&#8482;','&#8501;','&#8592;','&#8593;','&#8594;','&#8595;','&#8596;','&#8629;','&#8656;','&#8657;','&#8658;','&#8659;','&#8660;','&#8704;','&#8706;','&#8707;','&#8709;','&#8711;','&#8712;','&#8713;','&#8715;','&#8719;','&#8721;','&#8722;','&#8727;','&#8730;','&#8733;','&#8734;','&#8736;','&#8743;','&#8744;','&#8745;','&#8746;','&#8747;','&#8756;','&#8764;','&#8773;','&#8776;','&#8800;','&#8801;','&#8804;','&#8805;','&#8834;','&#8835;','&#8836;','&#8838;','&#8839;','&#8853;','&#8855;','&#8869;','&#8901;','&#8968;','&#8969;','&#8970;','&#8971;','&#9001;','&#9002;','&#9674;','&#9824;','&#9827;','&#9829;','&#9830;');
		return this.swapArrayVals(s,arr1,arr2);
	},	

	// Convert Numerical entities into HTML entities
	NumericalToHTML : function(s){
		var arr1 = new Array('&#160;','&#161;','&#162;','&#163;','&#164;','&#165;','&#166;','&#167;','&#168;','&#169;','&#170;','&#171;','&#172;','&#173;','&#174;','&#175;','&#176;','&#177;','&#178;','&#179;','&#180;','&#181;','&#182;','&#183;','&#184;','&#185;','&#186;','&#187;','&#188;','&#189;','&#190;','&#191;','&#192;','&#193;','&#194;','&#195;','&#196;','&#197;','&#198;','&#199;','&#200;','&#201;','&#202;','&#203;','&#204;','&#205;','&#206;','&#207;','&#208;','&#209;','&#210;','&#211;','&#212;','&#213;','&#214;','&#215;','&#216;','&#217;','&#218;','&#219;','&#220;','&#221;','&#222;','&#223;','&#224;','&#225;','&#226;','&#227;','&#228;','&#229;','&#230;','&#231;','&#232;','&#233;','&#234;','&#235;','&#236;','&#237;','&#238;','&#239;','&#240;','&#241;','&#242;','&#243;','&#244;','&#245;','&#246;','&#247;','&#248;','&#249;','&#250;','&#251;','&#252;','&#253;','&#254;','&#255;','&#34;','&#38;','&#60;','&#62;','&#338;','&#339;','&#352;','&#353;','&#376;','&#710;','&#732;','&#8194;','&#8195;','&#8201;','&#8204;','&#8205;','&#8206;','&#8207;','&#8211;','&#8212;','&#8216;','&#8217;','&#8218;','&#8220;','&#8221;','&#8222;','&#8224;','&#8225;','&#8240;','&#8249;','&#8250;','&#8364;','&#402;','&#913;','&#914;','&#915;','&#916;','&#917;','&#918;','&#919;','&#920;','&#921;','&#922;','&#923;','&#924;','&#925;','&#926;','&#927;','&#928;','&#929;','&#931;','&#932;','&#933;','&#934;','&#935;','&#936;','&#937;','&#945;','&#946;','&#947;','&#948;','&#949;','&#950;','&#951;','&#952;','&#953;','&#954;','&#955;','&#956;','&#957;','&#958;','&#959;','&#960;','&#961;','&#962;','&#963;','&#964;','&#965;','&#966;','&#967;','&#968;','&#969;','&#977;','&#978;','&#982;','&#8226;','&#8230;','&#8242;','&#8243;','&#8254;','&#8260;','&#8472;','&#8465;','&#8476;','&#8482;','&#8501;','&#8592;','&#8593;','&#8594;','&#8595;','&#8596;','&#8629;','&#8656;','&#8657;','&#8658;','&#8659;','&#8660;','&#8704;','&#8706;','&#8707;','&#8709;','&#8711;','&#8712;','&#8713;','&#8715;','&#8719;','&#8721;','&#8722;','&#8727;','&#8730;','&#8733;','&#8734;','&#8736;','&#8743;','&#8744;','&#8745;','&#8746;','&#8747;','&#8756;','&#8764;','&#8773;','&#8776;','&#8800;','&#8801;','&#8804;','&#8805;','&#8834;','&#8835;','&#8836;','&#8838;','&#8839;','&#8853;','&#8855;','&#8869;','&#8901;','&#8968;','&#8969;','&#8970;','&#8971;','&#9001;','&#9002;','&#9674;','&#9824;','&#9827;','&#9829;','&#9830;');
		var arr2 = new Array('&nbsp;','&iexcl;','&cent;','&pound;','&curren;','&yen;','&brvbar;','&sect;','&uml;','&copy;','&ordf;','&laquo;','&not;','&shy;','&reg;','&macr;','&deg;','&plusmn;','&sup2;','&sup3;','&acute;','&micro;','&para;','&middot;','&cedil;','&sup1;','&ordm;','&raquo;','&frac14;','&frac12;','&frac34;','&iquest;','&agrave;','&aacute;','&acirc;','&atilde;','&Auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&Ouml;','&times;','&oslash;','&ugrave;','&uacute;','&ucirc;','&Uuml;','&yacute;','&thorn;','&szlig;','&agrave;','&aacute;','&acirc;','&atilde;','&auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&ouml;','&divide;','&oslash;','&ugrave;','&uacute;','&ucirc;','&uuml;','&yacute;','&thorn;','&yuml;','&quot;','&amp;','&lt;','&gt;','&oelig;','&oelig;','&scaron;','&scaron;','&yuml;','&circ;','&tilde;','&ensp;','&emsp;','&thinsp;','&zwnj;','&zwj;','&lrm;','&rlm;','&ndash;','&mdash;','&lsquo;','&rsquo;','&sbquo;','&ldquo;','&rdquo;','&bdquo;','&dagger;','&dagger;','&permil;','&lsaquo;','&rsaquo;','&euro;','&fnof;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigmaf;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&thetasym;','&upsih;','&piv;','&bull;','&hellip;','&prime;','&prime;','&oline;','&frasl;','&weierp;','&image;','&real;','&trade;','&alefsym;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&crarr;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&forall;','&part;','&exist;','&empty;','&nabla;','&isin;','&notin;','&ni;','&prod;','&sum;','&minus;','&lowast;','&radic;','&prop;','&infin;','&ang;','&and;','&or;','&cap;','&cup;','&int;','&there4;','&sim;','&cong;','&asymp;','&ne;','&equiv;','&le;','&ge;','&sub;','&sup;','&nsub;','&sube;','&supe;','&oplus;','&otimes;','&perp;','&sdot;','&lceil;','&rceil;','&lfloor;','&rfloor;','&lang;','&rang;','&loz;','&spades;','&clubs;','&hearts;','&diams;');
		return this.swapArrayVals(s,arr1,arr2);
	},


	// Numerically encodes all unicode characters
	numEncode : function(s){
		
		if(this.isEmpty(s)) return "";

		var e = "";
		for (var i = 0; i < s.length; i++)
		{
			var c = s.charAt(i);
			if (c < " " || c > "~")
			{
				c = "&#" + c.charCodeAt() + ";";
			}
			e += c;
		}
		return e;
	},
	
	// HTML Decode numerical and HTML entities back to original values
	htmlDecode : function(s){

		var c,m,d = s;
		
		if(this.isEmpty(d)) return "";

		// convert HTML entites back to numerical entites first
		d = this.HTML2Numerical(d);
		
		// look for numerical entities &#34;
		arr=d.match(/&#[0-9]{1,5};/g);
		
		// if no matches found in string then skip
		if(arr!=null){
			for(var x=0;x<arr.length;x++){
				m = arr[x];
				c = m.substring(2,m.length-1); //get numeric part which is refernce to unicode character
				// if its a valid number we can decode
				if(c >= -32768 && c <= 65535){
					// decode every single match within string
					d = d.replace(m, String.fromCharCode(c));
				}else{
					d = d.replace(m, ""); //invalid so replace with nada
				}
			}			
		}

		return d;
	},		

	// encode an input string into either numerical or HTML entities
	htmlEncode : function(s,dbl){
			
		if(this.isEmpty(s)) return "";

		// do we allow double encoding? E.g will &amp; be turned into &amp;amp;
		dbl = dbl | false; //default to prevent double encoding
		
		// if allowing double encoding we do ampersands first
		if(dbl){
			if(this.EncodeType=="numerical"){
				s = s.replace(/&/g, "&#38;");
			}else{
				s = s.replace(/&/g, "&amp;");
			}
		}

		// convert the xss chars to numerical entities ' " < >
		s = this.XSSEncode(s,false);
		
		if(this.EncodeType=="numerical" || !dbl){
			// Now call function that will convert any HTML entities to numerical codes
			s = this.HTML2Numerical(s);
		}

		// Now encode all chars above 127 e.g unicode
		s = this.numEncode(s);

		// now we know anything that needs to be encoded has been converted to numerical entities we
		// can encode any ampersands & that are not part of encoded entities
		// to handle the fact that I need to do a negative check and handle multiple ampersands &&&
		// I am going to use a placeholder

		// if we don't want double encoded entities we ignore the & in existing entities
		if(!dbl){
			s = s.replace(/&#/g,"##AMPHASH##");
		
			if(this.EncodeType=="numerical"){
				s = s.replace(/&/g, "&#38;");
			}else{
				s = s.replace(/&/g, "&amp;");
			}

			s = s.replace(/##AMPHASH##/g,"&#");
		}
		
		// replace any malformed entities
		s = s.replace(/&#\d*([^\d;]|$)/g, "$1");

		if(!dbl){
			// safety check to correct any double encoded &amp;
			s = this.correctEncoding(s);
		}

		// now do we need to convert our numerical encoded string into entities
		if(this.EncodeType=="entity"){
			s = this.NumericalToHTML(s);
		}

		return s;					
	},

	// Encodes the basic 4 characters used to malform HTML in XSS hacks
	XSSEncode : function(s,en){
		if(!this.isEmpty(s)){
			en = en || true;
			// do we convert to numerical or html entity?
			if(en){
				s = s.replace(/\'/g,"&#39;"); //no HTML equivalent as &apos is not cross browser supported
				s = s.replace(/\"/g,"&quot;");
				s = s.replace(/</g,"&lt;");
				s = s.replace(/>/g,"&gt;");
			}else{
				s = s.replace(/\'/g,"&#39;"); //no HTML equivalent as &apos is not cross browser supported
				s = s.replace(/\"/g,"&#34;");
				s = s.replace(/</g,"&#60;");
				s = s.replace(/>/g,"&#62;");
			}
			return s;
		}else{
			return "";
		}
	},

	// returns true if a string contains html or numerical encoded entities
	hasEncoded : function(s){
		if(/&#[0-9]{1,5};/g.test(s)){
			return true;
		}else if(/&[A-Z]{2,6};/gi.test(s)){
			return true;
		}else{
			return false;
		}
	},

	// will remove any unicode characters
	stripUnicode : function(s){
		return s.replace(/[^\x20-\x7E]/g,"");
		
	},

	// corrects any double encoded &amp; entities e.g &amp;amp;
	correctEncoding : function(s){
		return s.replace(/(&amp;)(amp;)+/,"$1");
	},


	// Function to loop through an array swaping each item with the value from another array e.g swap HTML entities with Numericals
	swapArrayVals : function(s,arr1,arr2){
		if(this.isEmpty(s)) return "";
		var re;
		if(arr1 && arr2){
			//ShowDebug("in swapArrayVals arr1.length = " + arr1.length + " arr2.length = " + arr2.length)
			// array lengths must match
			if(arr1.length == arr2.length){
				for(var x=0,i=arr1.length;x<i;x++){
					re = new RegExp(arr1[x], 'g');
					s = s.replace(re,arr2[x]); //swap arr1 item with matching item from arr2	
				}
			}
		}
		return s;
	},

	inArray : function( item, arr ) {
		for ( var i = 0, x = arr.length; i < x; i++ ){
			if ( arr[i] === item ){
				return i;
			}
		}
		return -1;
	}

}

/*****************************************************************************
 *  FILE:  anytime.js - The Any+Time(TM) JavaScript Library (source)
 *
 *  VERSION: 4.1112
 *
 *  Copyright 2008-2010 Andrew M. Andrews III (www.AMA3.com). Some Rights 
 *  Reserved. This work licensed under the Creative Commons Attribution-
 *  Noncommercial-Share Alike 3.0 Unported License except in jurisdicitons
 *  for which the license has been ported by Creative Commons International,
 *  where the work is licensed under the applicable ported license instead.
 *  For a copy of the unported license, visit
 *  http://creativecommons.org/licenses/by-nc-sa/3.0/
 *  or send a letter to Creative Commons, 171 Second Street, Suite 300,
 *  San Francisco, California, 94105, USA.  For ported versions of the
 *  license, visit http://creativecommons.org/international/
 *
 *  Alternative licensing arrangements may be made by contacting the
 *  author at http://www.AMA3.com/contact/
 *
 *  The Any+Time(TM) JavaScript Library provides the following ECMAScript
 *  functionality:
 *
 *    AnyTime.Converter
 *      Converts Dates to/from Strings, allowing a wide range of formats
 *      closely matching those provided by the MySQL DATE_FORMAT() function,
 *      with some noteworthy enhancements.
 *
 *    AnyTime.pad()
 *      Pads a value with a specific number of leading zeroes.
 *      
 *    AnyTime.noPicker()
 *      Destroys a calendar widget previously added by AnyTime.picker().
 *      Can also be invoked via jQuery using $(selector).AnyTime_noPicker()
 *
 *    AnyTime.picker()
 *      Attaches a calendar widget to a text field for selecting date/time
 *      values with fewer mouse movements than most similar pickers.  Any
 *      format supported by AnyTime.Converter can be used for the text field.
 *      If JavaScript is disabled, the text field remains editable without
 *      any of the picker features.
 *      Can also be invoked via jQuery using $(selector).AnyTime_picker()
 *
 *  IMPORTANT NOTICE:  This code depends upon the jQuery JavaScript Library
 *  (www.jquery.com), currently version 1.4.
 *
 *  The Any+Time(TM) code and styles in anytime.css have been tested (but not
 *  extensively) on Windows Vista in Internet Explorer 8.0, Firefox 3.0, Opera
 *  10.10 and Safari 4.0.  Minor variations in IE6+7 are to be expected, due
 *  to their broken box model. Please report any other problems to the author
 *  (URL above).
 *
 *  Any+Time is a trademark of Andrew M. Andrews III.
 *  Thanks to Chu for help with a setMonth() issue!
 ****************************************************************************/

var AnyTime =
{
  	//=============================================================================
  	//  AnyTime.pad() pads a value with a specified number of zeroes and returns
  	//  a string containing the padded value.
  	//=============================================================================

  	pad: function( val, len )
  	{
  		var str = String(Math.abs(val));
  		while ( str.length < len )
  		str = '0'+str;
  		if ( val < 0 )
  		str = '-'+str;
  		return str;
  	}
};

(function($)
{
	// private members

	var __oneDay = (24*60*60*1000);
	var __daysIn = [ 31,28,31,30,31,30,31,31,30,31,30,31 ];
	var __iframe = null;
	var __initialized = false;
	var __msie6 = ( navigator.userAgent.indexOf('MSIE 6') > 0 ); 
	var __msie7 = ( navigator.userAgent.indexOf('MSIE 7') > 0 ); 
  	var __pickers = [];

  	//  Add methods to jQuery to create and destroy pickers using
  	//  the typical jQuery approach.
  	
  	jQuery.prototype.AnyTime_picker = function( options )
  	{
  		return this.each( function(i) { AnyTime.picker( this.id, options ); } );
  	}
  	
  	jQuery.prototype.AnyTime_noPicker = function()
  	{
  		return this.each( function(i) { AnyTime.noPicker( this.id ); } );
  	}
  	
  	//	Add special methods to jQuery to compute the height and width
	//	of picker components differently for Internet Explorer 6.x
	//  This prevents the pickers from being too tall and wide.
  	
  	jQuery.prototype.AnyTime_height = function(inclusive)
  	{
  		return ( __msie6 ?
  					Number(this.css('height').replace(/[^0-9]/g,'')) :
  					this.outerHeight(inclusive) );
  	};

  	jQuery.prototype.AnyTime_width = function(inclusive)
  	{
  		return ( __msie6 ?
  					(1+Number(this.css('width').replace(/[^0-9]/g,''))) :
  					this.outerWidth(inclusive) );
  	};

  	
  	// 	Add a method to jQuery to change the classes of an element to
  	//  indicate whether it's value is current (used by AnyTime.picker),
  	//  and another to trigger the click handler for the currently-
  	//  selected button under an element.

  	jQuery.prototype.AnyTime_current = function(isCurrent,isLegal)
	{
	    if ( isCurrent )
	    {
		  this.removeClass('AnyTime-out-btn ui-state-default ui-state-disabled ui-state-highlight');
	      this.addClass('AnyTime-cur-btn ui-state-default ui-state-highlight');
	    }
	    else
	    {
	      this.removeClass('AnyTime-cur-btn ui-state-highlight');
	      if ( ! isLegal )
	    	  this.addClass('AnyTime-out-btn ui-state-disabled');
	      else
	    	  this.removeClass('AnyTime-out-btn ui-state-disabled');
	    }
	};
	
	jQuery.prototype.AnyTime_clickCurrent = function()
	{
		this.find('.AnyTime-cur-btn').triggerHandler('click');
	}
  	
  	$(document).ready( 
  		function()
		{
			//  Ping the server for statistical purposes (remove if offended).
			
  						
			//  IE6 doesn't float popups over <select> elements unless an
			//	<iframe> is inserted between them!  The <iframe> is added to
			//	the page *before* the popups are moved, so they will appear
			//  after the <iframe>.
			
			if ( __msie6 )
			{
				__iframe = $('<iframe frameborder="0" scrolling="no"></iframe>');
				__iframe.src = "javascript:'<html></html>';";
				$(__iframe).css( {
					display: 'block',
					height: '1px',
					left: '0',
					top: '0',
					width: '1px',
					zIndex: 0
					} );
				$(document.body).append(__iframe);
			}
			
			//  Move popup windows to the end of the page.  This allows them to
			//  overcome XHTML restrictions on <table> placement enforced by MSIE.
			
			for ( var id in __pickers )
			  __pickers[id].onReady();
			
			__initialized = true;
		
		} ); // document.ready
  	
//=============================================================================
//  AnyTime.Converter
//
//  This object converts between Date objects and Strings.
//
//  To use AnyTime.Converter, simply create an instance for a format string,
//  and then (repeatedly) invoke the format() and/or parse() methods to
//  perform the conversions.  For example:
//
//    var converter = new AnyTime.Converter({format:'%Y-%m-%d'})
//    var datetime = converter.parse('1967-07-30') // July 30, 1967 @ 00:00
//    alert( converter.format(datetime) ); // outputs: 1967-07-30
//
//  Constructor parameter:
//
//  options - an object of optional parameters that override default behaviors.
//    The supported options are:
//
//    baseYear - the number to add to two-digit years if the %y format
//      specifier is used.  By default, AnyTime.Converter follows the
//      MySQL assumption that two-digit years are in the range 1970 to 2069
//      (see http://dev.mysql.com/doc/refman/5.1/en/y2k-issues.html).
//      The most common alternatives for baseYear are 1900 and 2000.
//
//    dayAbbreviations - an array of seven strings, indexed 0-6, to be used
//      as ABBREVIATED day names.  If not specified, the following are used:
//      ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
//      Note that if the firstDOW option is passed to AnyTime.picker() (see
//      AnyTime.picker()), this array should nonetheless begin with the 
//      desired abbreviation for Sunday.
//
//    dayNames - an array of seven strings, indexed 0-6, to be used as
//      day names.  If not specified, the following are used: ['Sunday',
//        'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
//      Note that if the firstDOW option is passed to AnyTime.picker() (see
//      AnyTime.picker()), this array should nonetheless begin with the
//      desired name for Sunday.
//
//    eraAbbreviations - an array of two strings, indexed 0-1, to be used
//      as ABBREVIATED era names.  Item #0 is the abbreviation for "Before
//      Common Era" (years before 0001, sometimes represented as negative
//      years or "B.C"), while item #1 is the abbreviation for "Common Era"
//      (years from 0001 to present, usually represented as unsigned years
//      or years "A.D.").  If not specified, the following are used:
//      ['BCE','CE']
//
//    format - a string specifying the pattern of strings involved in the
//      conversion.  The parse() method can take a string in this format and
//      convert it to a Date, and the format() method can take a Date object
//      and convert it to a string matching the format.
//
//      Fields in the format string must match those for the DATE_FORMAT()
//      function in MySQL, as defined here:
//      http://tinyurl.com/bwd45#function_date-format
//
//      IMPORTANT:  Some MySQL specifiers are not supported (especially
//      those involving day-of-the-year, week-of-the-year) or approximated.
//      See the code for exact behavior.
//
//      In addition to the MySQL format specifiers, the following custom
//      specifiers are also supported:
//
//        %B - If the year is before 0001, then the "Before Common Era"
//          abbreviation (usually BCE or the obsolete BC) will go here.
//
//        %C - If the year is 0001 or later, then the "Common Era"
//          abbreviation (usually CE or the obsolete AD) will go here.
//
//        %E - If the year is before 0001, then the "Before Common Era"
//          abbreviation (usually BCE or the obsolete BC) will go here.
//          Otherwise, the "Common Era" abbreviation (usually CE or the
//          obsolete AD) will go here.
//
//        %Z - The current four-digit year, without any sign.  This is
//          commonly used with years that might be before (or after) 0001,
//          when the %E (or %B and %C) specifier is used instead of a sign.
//          For example, 45 BCE is represented "0045".  By comparison, in
//          the "%Y" format, 45 BCE is represented "-0045".
//
//        %z - The current year, without any sign, using only the necessary
//          number of digits.  This if the year is commonly used with years
//          that might be before (or after) 0001, when the %E (or %B and %C)
//          specifier is used instead of a sign.  For example, the year
//          45 BCE is represented as "45", and the year 312 CE as "312".
//
//        %# - the timezone offset, with a sign, in minutes.
//
//        %+ - the timezone offset, with a sign, in hours and minutes, in
//          four-digit, 24-hour format with no delimiter (for example, +0530).
//          To remember the difference between %+ and %-, it might be helpful
//          to remember that %+ might have more characters than %-.
//
//        %: - the timezone offset, with a sign, in hours and minutes, in
//          four-digit, 24-hour format with a colon delimiter (for example,
//          +05:30).  This is similar to the %z format used by Java.  
//          To remember the difference between %: and %;, it might be helpful
//          to remember that a colon (:) has a period (.) on the bottom and
//          a semicolon (;) has a comma (,), and in English sentence structure,
//          a period represents a more significant stop than a comma, and
//          %: might be a longer string than %; (I know it's a stretch, but
//          it's easier than looking it up every time)!
//  	
//        %- - the timezone offset, with a sign, in hours and minutes, in
//          three-or-four-digit, 24-hour format with no delimiter (for
//          example, +530).
//
//        %; - the timezone offset, with a sign, in hours and minutes, in
//          three-or-four-digit, 24-hour format with a colon delimiter
//          (for example, +5:30).
//
//        %@ - the timezone offset label.  By default, this will be the
//          string "UTC" followed by the offset, with a sign, in hours and  
//          minutes, in four-digit, 24-hour format with a colon delimiter
//          (for example, UTC+05:30).  However, if Any+Time(TM) has been
//          extended with a member named utcLabel (for example, by the
//          anytimetz.js file), then it is assumed to be an array of arrays,
//          where the primary array is indexed by time zone offsets, and
//          each sub-array contains a potential label for that offset.
//          When parsing with %@, the array is scanned for matches to the
//          input string, and if a match is found, the corresponding UTC
//          offset is used.  When formatting, the array is scanned for a
//          matching offset, and if one is found, the first member of the
//          sub-array is used for output (unless overridden with
//          utcFormatOffsetSubIndex or setUtcFormatOffsetSubIndex()).
//          If the array does not exist, or does not contain a sub-array
//          for the offset, then the default format is used.
//
//    monthAbbreviations - an array of twelve strings, indexed 0-6, to be
//      used as ABBREVIATED month names.  If not specified, the following
//      are used: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep',
//        'Oct','Nov','Dec']
//
//    monthNames - an array of twelve strings, indexed 0-6, to be used as
//      month names.  If not specified, the following are used:
//      ['January','February','March','April','May','June','July',
//        'August','September','October','November','December']
//
//    utcFormatOffsetAlleged - the offset from UTC, in minutes, to claim that
//      a Date object represents during formatting, even though it is formatted
//      using local time. Unlike utcFormatOffsetImposed, which actually
//      converts the Date object to the specified different time zone, this
//      option merely reports the alleged offset when a timezone specifier
//      (%#, %+, %-, %:, %; %@) is encountered in the format string.
//      This primarily exists so AnyTime.picker can edit the time as specified
//      (without conversion to local time) and then convert the edited time to
//      a different time zone (as selected using the picker).  Any initial
//      value specified here can be changed by setUtcFormatOffsetAlleged().
//      If a format offset is alleged, one cannot also be imposed (the imposed
//      offset is ignored).
//
//    utcFormatOffsetImposed - the offset from UTC, in minutes, to specify when
//      formatting a Date object.  By default, a Date is always formatted
//      using the local time zone.
//
//    utcFormatOffsetSubIndex - when extending AnyTime with a utcLabel array
//      (for example, by the anytimetz.js file), the specified sub-index is
//      used to choose the Time Zone label for the UTC offset when formatting
//      a Date object.  This primarily exists so AnyTime.picker can specify
//      the label selected using the picker.  Any initial value specified here
//      can be changed by setUtcFormatOffsetSubIndex().
//
//    utcParseOffsetAssumed - the offset from UTC, in minutes, to assume when
//      parsing a String object.  By default, a Date is always parsed using the
//      local time zone, unless the format string includes a timezone
//      specifier (%#, %+, %-, %:, %; or %@), in which case the timezone
//      specified in the string is used. The Date object created by parsing
//      always represents local time regardless of the input time zone.
//
//    utcParseOffsetCapture - if true, any parsed string is always treated as
//      though it represents local time, and any offset specified by the string
//      (or utcParseOffsetAssume) is captured for return by the 
//      getUtcParseOffsetCaptured() method.  If the %@ format specifier is
//      used, the sub-index of any matched label is also captured for return
//      by the getUtcParseOffsetSubIndex() method.  This primarily exists so
//      AnyTime.picker can edit the time as specified (without conversion to
//      local time) and then convert the edited time to a different time zone
//      (as selected using the picker). 
//=============================================================================

AnyTime.Converter = function(options)
{
  	// private members

  	var _flen = 0;
	var _longDay = 9;
	var _longMon = 9;
	var _shortDay = 6;
	var _shortMon = 3;
	var _offAl = Number.MIN_VALUE; // format time zone offset alleged
	var _offCap = Number.MIN_VALUE; // parsed time zone offset captured
	var _offF = Number.MIN_VALUE; // format time zone offset imposed
	var _offFSI = (-1); // format time zone label subindex
	var _offP = Number.MIN_VALUE; // parsed time zone offset assumed
	var _offPSI = (-1);        // parsed time zone label subindex captured
	var _captureOffset = false;

	// public members
  
	this.fmt = '%Y-%m-%d %T';
	this.dAbbr = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
	this.dNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
	this.eAbbr = ['BCE','CE'];
	this.mAbbr = [ 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' ];
	this.mNames = [ 'January','February','March','April','May','June','July','August','September','October','November','December' ];
	this.baseYear = null;
	
	//-------------------------------------------------------------------------
	//  AnyTime.Converter.dAt() returns true if the character in str at pos
	//  is a digit.
	//-------------------------------------------------------------------------
	
	this.dAt = function( str, pos )
	{
	    return ( (str.charCodeAt(pos)>='0'.charCodeAt(0)) &&
	            (str.charCodeAt(pos)<='9'.charCodeAt(0)) );
	};
	
	//-------------------------------------------------------------------------
	//  AnyTime.Converter.format() returns a String containing the value
	//  of a specified Date object, using the format string passed to
	//  AnyTime.Converter().
	//
	//  Method parameter:
	//
	//    date - the Date object to be converted
	//-------------------------------------------------------------------------
	
	this.format = function( date )
	{
		var d = new Date(date.getTime());
		if ( ( _offAl == Number.MIN_VALUE ) && ( _offF != Number.MIN_VALUE ) )
		  d.setTime( ( d.getTime() + (d.getTimezoneOffset()*60000) ) + (_offF*60000) );
			
	    var t;
	    var str = '';
	    for ( var f = 0 ; f < _flen ; f++ )
	    {
	      if ( this.fmt.charAt(f) != '%' )
	        str += this.fmt.charAt(f);
	      else
	      {
	    	var ch = this.fmt.charAt(f+1)
	        switch ( ch )
	        {
	          case 'a': // Abbreviated weekday name (Sun..Sat)
	            str += this.dAbbr[ d.getDay() ];
	            break;
	          case 'B': // BCE string (eAbbr[0], usually BCE or BC, only if appropriate) (NON-MYSQL)
	            if ( d.getFullYear() < 0 )
	              str += this.eAbbr[0];
	            break;
	          case 'b': // Abbreviated month name (Jan..Dec)
	            str += this.mAbbr[ d.getMonth() ];
	            break;
	          case 'C': // CE string (eAbbr[1], usually CE or AD, only if appropriate) (NON-MYSQL)
	            if ( d.getFullYear() > 0 )
	              str += this.eAbbr[1];
	            break;
	          case 'c': // Month, numeric (0..12)
	            str += d.getMonth()+1;
	            break;
	          case 'd': // Day of the month, numeric (00..31)
	            t = d.getDate();
	            if ( t < 10 ) str += '0';
	            str += String(t);
	            break;
	          case 'D': // Day of the month with English suffix (0th, 1st,...)
	            t = String(d.getDate());
	            str += t;
	            if ( ( t.length == 2 ) && ( t.charAt(0) == '1' ) )
	              str += 'th';
	            else
	            {
	              switch ( t.charAt( t.length-1 ) )
	              {
	                case '1': str += 'st'; break;
	                case '2': str += 'nd'; break;
	                case '3': str += 'rd'; break;
	                default: str += 'th'; break;
	              }
	            }
	            break;
	          case 'E': // era string (from eAbbr[], BCE, CE, BC or AD) (NON-MYSQL)
	            str += this.eAbbr[ (d.getFullYear()<0) ? 0 : 1 ];
	            break;
	          case 'e': // Day of the month, numeric (0..31)
	            str += d.getDate();
	            break;
	          case 'H': // Hour (00..23)
	            t = d.getHours();
	            if ( t < 10 ) str += '0';
	            str += String(t);
	            break;
	          case 'h': // Hour (01..12)
	          case 'I': // Hour (01..12)
	            t = d.getHours() % 12;
	            if ( t == 0 )
	              str += '12';
	            else
	            {
	              if ( t < 10 ) str += '0';
	              str += String(t);
	            }
	            break;
	          case 'i': // Minutes, numeric (00..59)
	            t = d.getMinutes();
	            if ( t < 10 ) str += '0';
	            str += String(t);
	            break;
	          case 'k': // Hour (0..23)
	            str += d.getHours();
	            break;
	          case 'l': // Hour (1..12)
	            t = d.getHours() % 12;
	            if ( t == 0 )
	              str += '12';
	            else
	              str += String(t);
	            break;
	          case 'M': // Month name (January..December)
	            str += this.mNames[ d.getMonth() ];
	            break;
	          case 'm': // Month, numeric (00..12)
	            t = d.getMonth() + 1;
	            if ( t < 10 ) str += '0';
	            str += String(t);
	            break;
	          case 'p': // AM or PM
	            str += ( ( d.getHours() < 12 ) ? 'AM' : 'PM' );
	            break;
	          case 'r': // Time, 12-hour (hh:mm:ss followed by AM or PM)
	            t = d.getHours() % 12;
	            if ( t == 0 )
	              str += '12:';
	            else
	            {
	              if ( t < 10 ) str += '0';
	              str += String(t) + ':';
	            }
	            t = d.getMinutes();
	            if ( t < 10 ) str += '0';
	            str += String(t) + ':';
	            t = d.getSeconds();
	            if ( t < 10 ) str += '0';
	            str += String(t);
	            str += ( ( d.getHours() < 12 ) ? 'AM' : 'PM' );
	            break;
	          case 'S': // Seconds (00..59)
	          case 's': // Seconds (00..59)
	            t = d.getSeconds();
	            if ( t < 10 ) str += '0';
	            str += String(t);
	            break;
	          case 'T': // Time, 24-hour (hh:mm:ss)
	            t = d.getHours();
	            if ( t < 10 ) str += '0';
	            str += String(t) + ':';
	            t = d.getMinutes();
	            if ( t < 10 ) str += '0';
	            str += String(t) + ':';
	            t = d.getSeconds();
	            if ( t < 10 ) str += '0';
	            str += String(t);
	            break;
	          case 'W': // Weekday name (Sunday..Saturday)
	            str += this.dNames[ d.getDay() ];
	            break;
	          case 'w': // Day of the week (0=Sunday..6=Saturday)
	            str += d.getDay();
	            break;
	          case 'Y': // Year, numeric, four digits (negative if before 0001)
	            str += AnyTime.pad(d.getFullYear(),4);
	            break;
	          case 'y': // Year, numeric (two digits, negative if before 0001)
	            t = d.getFullYear() % 100;
	            str += AnyTime.pad(t,2);
	            break;
	          case 'Z': // Year, numeric, four digits, unsigned (NON-MYSQL)
	            str += AnyTime.pad(Math.abs(d.getFullYear()),4);
	            break;
	          case 'z': // Year, numeric, variable length, unsigned (NON-MYSQL)
	            str += Math.abs(d.getFullYear());
	            break;
	          case '%': // A literal '%' character
	            str += '%';
	            break;
	          case '#': // signed timezone offset in minutes
	        	t = ( _offAl != Number.MIN_VALUE ) ? _offAl :
	        		( _offF == Number.MIN_VALUE ) ? (0-d.getTimezoneOffset()) : _offF;
	        	if ( t >= 0 )
	        		str += '+';
	        	str += t;
	        	break;
	          case '@': // timezone offset label
		        t = ( _offAl != Number.MIN_VALUE ) ? _offAl :
		        	( _offF == Number.MIN_VALUE ) ? (0-d.getTimezoneOffset()) : _offF;
		        if ( AnyTime.utcLabel && AnyTime.utcLabel[t] )
		        {
		          if ( ( _offFSI > 0 ) && ( _offFSI < AnyTime.utcLabel[t].length ) )
		            str += AnyTime.utcLabel[t][_offFSI];
		          else
		            str += AnyTime.utcLabel[t][0];
		          break;
		        }
		        str += 'UTC';
		        ch = ':'; // drop through for offset formatting
	          case '+': // signed, 4-digit timezone offset in hours and minutes
	          case '-': // signed, 3-or-4-digit timezone offset in hours and minutes
	          case ':': // signed 4-digit timezone offset with colon delimiter
	          case ';': // signed 3-or-4-digit timezone offset with colon delimiter
		        t = ( _offAl != Number.MIN_VALUE ) ? _offAl :
		        		( _offF == Number.MIN_VALUE ) ? (0-d.getTimezoneOffset()) : _offF;
		        if ( t < 0 )
		          str += '-';
		        else
		          str += '+';
		        t = Math.abs(t);
		        str += ((ch=='+')||(ch==':')) ? AnyTime.pad(Math.floor(t/60),2) : Math.floor(t/60);
		        if ( (ch==':') || (ch==';') )
		          str += ':';
		        str += AnyTime.pad(t%60,2);
		        break;
	          case 'f': // Microseconds (000000..999999)
	          case 'j': // Day of year (001..366)
	          case 'U': // Week (00..53), where Sunday is the first day of the week
	          case 'u': // Week (00..53), where Monday is the first day of the week
	          case 'V': // Week (01..53), where Sunday is the first day of the week; used with %X
	          case 'v': // Week (01..53), where Monday is the first day of the week; used with %x
	          case 'X': // Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V
	          case 'x': // Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v
	            throw '%'+ch+' not implemented by AnyTime.Converter';
	          default: // for any character not listed above
	            str += this.fmt.substr(f,2);
	        } // switch ( this.fmt.charAt(f+1) )
	        f++;
	      } // else
	    } // for ( var f = 0 ; f < _flen ; f++ )
	    return str;
	    
	}; // AnyTime.Converter.format()
		  
	//-------------------------------------------------------------------------
	//  AnyTime.Converter.getUtcParseOffsetCaptured() returns the UTC offset
	//  last captured by a parsed string (or assumed by utcParseOffsetAssumed).
	//  It returns Number.MIN_VALUE if this object was not constructed with
	//  the utcParseOffsetCapture option set to true, or if an offset was not
	//  specified by the last parsed string or utcParseOffsetAssumed.
	//-------------------------------------------------------------------------
	
	this.getUtcParseOffsetCaptured = function()
	{
	    return _offCap;
	};
	
	//-------------------------------------------------------------------------
	//  AnyTime.Converter.getUtcParseOffsetCaptured() returns the UTC offset
	//  last captured by a parsed string (or assumed by utcParseOffsetAssumed).
	//  It returns Number.MIN_VALUE if this object was not constructed with
	//  the utcParseOffsetCapture option set to true, or if an offset was not
	//  specified by the last parsed string or utcParseOffsetAssumed.
	//-------------------------------------------------------------------------
	
	this.getUtcParseOffsetSubIndex = function()
	{
	    return _offPSI;
	};
	
	//-------------------------------------------------------------------------
	//  AnyTime.Converter.parse() returns a Date initialized from a specified
	//  string, using the format passed to AnyTime.Converter().
	//
	//  Method parameter:
	//
	//    str - the String object to be converted
	//-------------------------------------------------------------------------
	
	this.parse = function( str )
	{
		_offCap = _offP;
		_offPSI = (-1);
	    var era = 1;
	    var time = new Date();
	    var slen = str.length;
	    var s = 0;
	    var tzSign = 1, tzOff = _offP;
	    var i, matched, sub, sublen, temp;
	    for ( var f = 0 ; f < _flen ; f++ )
	    {
	      if ( this.fmt.charAt(f) == '%' )
	      {
			var ch = this.fmt.charAt(f+1);
	        switch ( ch )
	        {
	          case 'a': // Abbreviated weekday name (Sun..Sat)
	            matched = false;
	            for ( sublen = 0 ; s + sublen < slen ; sublen++ )
	            {
	              sub = str.substr(s,sublen);
	              for ( i = 0 ; i < 12 ; i++ )
	                if ( this.dAbbr[i] == sub )
	                {
	                  matched = true;
	                  s += sublen;
	                  break;
	                }
	              if ( matched )
	                break;
	            } // for ( sublen ... )
	            if ( ! matched )
	              throw 'unknown weekday: '+str.substr(s);
	            break;
	          case 'B': // BCE string (eAbbr[0]), only if needed. (NON-MYSQL)
	            sublen = this.eAbbr[0].length;
	            if ( ( s + sublen <= slen ) && ( str.substr(s,sublen) == this.eAbbr[0] ) )
	            {
	              era = (-1);
	              s += sublen;
	            }
	            break;
	          case 'b': // Abbreviated month name (Jan..Dec)
	            matched = false;
	            for ( sublen = 0 ; s + sublen < slen ; sublen++ )
	            {
	              sub = str.substr(s,sublen);
	              for ( i = 0 ; i < 12 ; i++ )
	                if ( this.mAbbr[i] == sub )
	                {
	                  time.setMonth( i );
	                  matched = true;
	                  s += sublen;
	                  break;
	                }
	              if ( matched )
	                break;
	            } // for ( sublen ... )
	            if ( ! matched )
	              throw 'unknown month: '+str.substr(s);
	            break;
	          case 'C': // CE string (eAbbr[1]), only if needed. (NON-MYSQL)
	            sublen = this.eAbbr[1].length;
	            if ( ( s + sublen <= slen ) && ( str.substr(s,sublen) == this.eAbbr[1] ) )
	              s += sublen; // note: CE is the default era
	            break;
	          case 'c': // Month, numeric (0..12)
	            if ( ( s+1 < slen ) && this.dAt(str,s+1) )
	            {
	              time.setMonth( (Number(str.substr(s,2))-1)%12 );
	              s += 2;
	            }
	            else
	            {
	              time.setMonth( (Number(str.substr(s,1))-1)%12 );
	              s++;
	            }
	            break;
	          case 'D': // Day of the month with English suffix (0th,1st,...)
	            if ( ( s+1 < slen ) && this.dAt(str,s+1) )
	            {
	              time.setDate( Number(str.substr(s,2)) );
	              s += 4;
	            }
	            else
	            {
	              time.setDate( Number(str.substr(s,1)) );
	              s += 3;
	            }
	            break;
	          case 'd': // Day of the month, numeric (00..31)
	            time.setDate( Number(str.substr(s,2)) );
	            s += 2;
	            break;
	          case 'E': // era string (from eAbbr[]) (NON-MYSQL)
	            sublen = this.eAbbr[0].length;
	            if ( ( s + sublen <= slen ) && ( str.substr(s,sublen) == this.eAbbr[0] ) )
	            {
	              era = (-1);
	              s += sublen;
	            }
	            else if ( ( s + ( sublen = this.eAbbr[1].length ) <= slen ) && ( str.substr(s,sublen) == this.eAbbr[1] ) )
	              s += sublen; // note: CE is the default era
	            else
	              throw 'unknown era: '+str.substr(s);
	            break;
	          case 'e': // Day of the month, numeric (0..31)
	            if ( ( s+1 < slen ) && this.dAt(str,s+1) )
	            {
	              time.setDate( Number(str.substr(s,2)) );
	              s += 2;
	            }
	            else
	            {
	              time.setDate( Number(str.substr(s,1)) );
	              s++;
	            }
	            break;
	          case 'f': // Microseconds (000000..999999)
	            s += 6; // SKIPPED!
	            break;
	          case 'H': // Hour (00..23)
	            time.setHours( Number(str.substr(s,2)) );
	            s += 2;
	            break;
	          case 'h': // Hour (01..12)
	          case 'I': // Hour (01..12)
	            time.setHours( Number(str.substr(s,2)) );
	            s += 2;
	            break;
	          case 'i': // Minutes, numeric (00..59)
	            time.setMinutes( Number(str.substr(s,2)) );
	            s += 2;
	            break;
	          case 'k': // Hour (0..23)
	            if ( ( s+1 < slen ) && this.dAt(str,s+1) )
	            {
	              time.setHours( Number(str.substr(s,2)) );
	              s += 2;
	            }
	            else
	            {
	              time.setHours( Number(str.substr(s,1)) );
	              s++;
	            }
	            break;
	          case 'l': // Hour (1..12)
	            if ( ( s+1 < slen ) && this.dAt(str,s+1) )
	            {
	              time.setHours( Number(str.substr(s,2)) );
	              s += 2;
	            }
	            else
	            {
	              time.setHours( Number(str.substr(s,1)) );
	              s++;
	            }
	            break;
	          case 'M': // Month name (January..December)
	            matched = false;
	            for (sublen=_shortMon ; s + sublen <= slen ; sublen++ )
	            {
	              if ( sublen > _longMon )
	                break;
	              sub = str.substr(s,sublen);
	              for ( i = 0 ; i < 12 ; i++ )
	              {
	                if ( this.mNames[i] == sub )
	                {
	                  time.setMonth( i );
	                  matched = true;
	                  s += sublen;
	                  break;
	                }
	              }
	              if ( matched )
	                break;
	            }
	            break;
	          case 'm': // Month, numeric (00..12)
	            time.setMonth( (Number(str.substr(s,2))-1)%12 );
	            s += 2;
	            break;
	          case 'p': // AM or PM
	            if ( str.charAt(s) == 'P' )
	            {
	              if ( time.getHours() == 12 )
	                time.setHours(0);
	              else
	                time.setHours( time.getHours() + 12 );
	            }
	            s += 2;
	            break;
	          case 'r': // Time, 12-hour (hh:mm:ss followed by AM or PM)
	            time.setHours(Number(str.substr(s,2)));
	            time.setMinutes(Number(str.substr(s+3,2)));
	            time.setSeconds(Number(str.substr(s+6,2)));
	            if ( str.substr(s+8,1) == 'P' )
	            {
	              if ( time.getHours() == 12 )
	                time.setHours(0);
	              else
	                time.setHours( time.getHours() + 12 );
	            }
	            s += 10;
	            break;
	          case 'S': // Seconds (00..59)
	          case 's': // Seconds (00..59)
	            time.setSeconds(Number(str.substr(s,2)));
	            s += 2;
	            break;
	          case 'T': // Time, 24-hour (hh:mm:ss)
	            time.setHours(Number(str.substr(s,2)));
	            time.setMinutes(Number(str.substr(s+3,2)));
	            time.setSeconds(Number(str.substr(s+6,2)));
	            s += 8;
	            break;
	          case 'W': // Weekday name (Sunday..Saturday)
	            matched = false;
	            for (sublen=_shortDay ; s + sublen <= slen ; sublen++ )
	            {
	              if ( sublen > _longDay )
	                break;
	              sub = str.substr(s,sublen);
	              for ( i = 0 ; i < 7 ; i++ )
	              {
	                if ( this.dNames[i] == sub )
	                {
	                  matched = true;
	                  s += sublen;
	                  break;
	                }
	              }
	              if ( matched )
	                break;
	            }
	            break;
	          case 'Y': // Year, numeric, four digits, negative if before 0001
	            i = 4;
	            if ( str.substr(s,1) == '-' )
	              i++;
	            time.setFullYear(Number(str.substr(s,i)));
	            s += i;
	            break;
	          case 'y': // Year, numeric (two digits), negative before baseYear
	            i = 2;
	            if ( str.substr(s,1) == '-' )
	              i++;
	            temp = Number(str.substr(s,i));
	            if ( typeof(this.baseYear) == 'number' )
	            	temp += this.baseYear;
	            else if ( temp < 70 )
	            	temp += 2000;
	            else
	            	temp += 1900;
	            time.setFullYear(temp);
	            s += i;
	            break;
	          case 'Z': // Year, numeric, four digits, unsigned (NON-MYSQL)
	            time.setFullYear(Number(str.substr(s,4)));
	            s += 4;
	            break;
	          case 'z': // Year, numeric, variable length, unsigned (NON-MYSQL)
	            i = 0;
	            while ( ( s < slen ) && this.dAt(str,s) )
	              i = ( i * 10 ) + Number(str.charAt(s++));
	            time.setFullYear(i);
	            break;
	          case '#': // signed timezone offset in minutes.
	            if ( str.charAt(s++) == '-' )
	            	tzSign = (-1);
	            for ( tzOff = 0 ; ( s < slen ) && (String(i=Number(str.charAt(s)))==str.charAt(s)) ; s++ )
	            	tzOff = ( tzOff * 10 ) + i;
	            tzOff *= tzSign;
	            break;
	          case '@': // timezone label
	        	_offPSI = (-1);
	        	if ( AnyTime.utcLabel )
	        	{
		            matched = false;
		            for ( tzOff in AnyTime.utcLabel )
		            {
		            	for ( i = 0 ; i < AnyTime.utcLabel[tzOff].length ; i++ )
		            	{
		            		sub = AnyTime.utcLabel[tzOff][i];
		            		sublen = sub.length;
		            		if ( ( s+sublen <= slen ) && ( str.substr(s,sublen) == sub ) )
		            		{
		            			matched = true;
		            			break;
		            		}
		            	}
	            		if ( matched )
	            			break;
		            }
		            if ( matched )
		            {
		            	_offPSI = i;
		            	tzOff = Number(tzOff);
		            	break; // case
		            }
	        	}
	        	if ( ( s+9 < slen ) || ( str.substr(s,3) != "UTC" ) )
                    throw 'unknown time zone: '+str.substr(s);
	        	s += 3;
	            ch = ':'; // drop through for offset parsing
	          case '-': // signed, 3-or-4-digit timezone offset in hours and minutes
	          case '+': // signed, 4-digit timezone offset in hours and minutes
	          case ':': // signed 4-digit timezone offset with colon delimiter
	          case ';': // signed 3-or-4-digit timezone offset with colon delimiter
	            if ( str.charAt(s++) == '-' )
	            	tzSign = (-1);
	            tzOff = Number(str.charAt(s));
	            if ( (ch=='+')||(ch==':')||((s+3<slen)&&(String(Number(str.charAt(s+3)))!==str.charAt(s+3))) )
	            	tzOff = (tzOff*10) + Number(str.charAt(++s));
                tzOff *= 60;
	        	if ( (ch==':') || (ch==';') )
	        		s++; // skip ":" (assumed)
	        	tzOff = ( tzOff + Number(str.substr(++s,2)) ) * tzSign;
	        	s += 2;
		        break;
	          case 'j': // Day of year (001..366)
	          case 'U': // Week (00..53), where Sunday is the first day of the week
	          case 'u': // Week (00..53), where Monday is the first day of the week
	          case 'V': // Week (01..53), where Sunday is the first day of the week; used with %X
	          case 'v': // Week (01..53), where Monday is the first day of the week; used with %x
	          case 'w': // Day of the week (0=Sunday..6=Saturday)
	          case 'X': // Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V
	          case 'x': // Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v
	            throw '%'+this.fmt.charAt(f+1)+' not implemented by AnyTime.Converter';
	          case '%': // A literal '%' character
	          default: // for any character not listed above
		        throw '%'+this.fmt.charAt(f+1)+' reserved for future use';
	            break;
	        }
	        f++;
	      } // if ( this.fmt.charAt(f) == '%' )
	      else if ( this.fmt.charAt(f) != str.charAt(s) )
	        throw str + ' is not in "' + this.fmt + '" format';
	      else
	        s++;
	    } // for ( var f ... )
	    if ( era < 0 )
	      time.setFullYear( 0 - time.getFullYear() );
		if ( tzOff != Number.MIN_VALUE )
		{
	       if ( _captureOffset )
	    	 _offCap = tzOff;
	       else
	    	 time.setTime( ( time.getTime() - (tzOff*60000) ) - (time.getTimezoneOffset()*60000) );
		}
		
	    return time;
	    
	}; // AnyTime.Converter.parse()
	
	//-------------------------------------------------------------------------
	//  AnyTime.Converter.setUtcFormatOffsetAlleged()  sets the offset from 
    //  UTC, in minutes, to claim that a Date object represents during
	//  formatting, even though it is formatted using local time.  This merely
	//  reports the alleged offset when a timezone specifier (%#, %+, %-, %:,
	//  %; or %@) is encountered in the format string--it does not otherwise
	//  affect the date/time value.  This primarily exists so AnyTime.picker
	//  can edit the time as specified (without conversion to local time) and
	//  then convert the edited time to a different time zone (as selected
	//  using the picker).  This method returns the previous value, if any,
	//  set by the utcFormatOffsetAlleged option, or a previous call to
	//  setUtcFormatOffsetAlleged(), or Number.MIN_VALUE if no offset was
	//  previously-alleged.  Call this method with Number.MIN_VALUE to cancel
	//  any prior value.  Note that if a format offset is alleged, any offset
	//  specified by option utcFormatOffsetImposed is ignored.
	//-------------------------------------------------------------------------
	
	this.setUtcFormatOffsetAlleged = function( offset )
	{
		var prev = _offAl;
	    _offAl = offset;
	    return prev;
	};
	
	//-------------------------------------------------------------------------
	//  AnyTime.Converter.setUtcFormatOffsetSubIndex() sets the sub-index
	//  to choose from the AnyTime.utcLabel array of arrays when formatting
	//  a Date using the %@ specifier.  For more information, see option
	//  AnyTime.Converter.utcFormatOffsetSubIndex.  This primarily exists so
	//  AnyTime.picker can specify the Time Zone label selected using the
	//  picker).  This method returns the previous value, if any, set by the
	//  utcFormatOffsetSubIndex option, or a previous call to
	//  setUtcFormatOffsetAlleged(), or (-1) if no sub-index was previously-
	//  chosen.  Call this method with (-1) to cancel any prior value.
	//-------------------------------------------------------------------------
	
	this.setUtcFormatOffsetSubIndex = function( subIndex )
	{
		var prev = _offFSI;
	    _offFSI = subIndex;
	    return prev;
	};
	
	//-------------------------------------------------------------------------
	//	AnyTime.Converter construction code:
	//-------------------------------------------------------------------------
	  
	(function(_this)
	{
	  	var i;
		
		options = jQuery.extend(true,{},options||{});
		
	  	if ( options.baseYear )
			_this.baseYear = Number(options.baseYear);
		
	  	if ( options.format )
			_this.fmt = options.format;
		
	  	_flen = _this.fmt.length;
		
	  	if ( options.dayAbbreviations )
	  		_this.dAbbr = $.makeArray( options.dayAbbreviations );
		
	  	if ( options.dayNames )
	  	{
	  		_this.dNames = $.makeArray( options.dayNames );
	  		_longDay = 1;
	  		_shortDay = 1000;
	  		for ( i = 0 ; i < 7 ; i++ )
	  		{
				var len = _this.dNames[i].length;
				if ( len > _longDay )
					_longDay = len;
				if ( len < _shortDay )
					_shortDay = len;
	  		}
	  	}
		
	  	if ( options.eraAbbreviations )
	  		_this.eAbbr = $.makeArray(options.eraAbbreviations);
		
	  	if ( options.monthAbbreviations )
	  		_this.mAbbr = $.makeArray(options.monthAbbreviations);
		
	  	if ( options.monthNames )
	  	{
	  		_this.mNames = $.makeArray( options.monthNames );
	  		_longMon = 1;
	  		_shortMon = 1000;
	  		for ( i = 0 ; i < 12 ; i++ )
	  		{
	  			var len = _this.mNames[i].length;
	  			if ( len > _longMon )
					_longMon = len;
	  			if ( len < _shortMon )
	  				_shortMon = len;
	  		}
	  	}
		
	  	if ( typeof options.utcFormatOffsetImposed != "undefined" )
	  		_offF = options.utcFormatOffsetImposed;

	  	if ( typeof options.utcParseOffsetAssumed != "undefined" )
	  		_offP = options.utcParseOffsetAssumed;
		
	  	if ( options.utcParseOffsetCapture )
	  		_captureOffset = true;
		
	})(this); // AnyTime.Converter construction

}; // AnyTime.Converter = 

//=============================================================================
//  AnyTime.noPicker()
//
//  Removes the date/time entry picker attached to a specified text field.
//=============================================================================

AnyTime.noPicker = function( id )
{
	if ( __pickers[id] )
	{
		__pickers[id].cleanup();
		delete __pickers[id];
	}
};

//=============================================================================
//  AnyTime.picker()
//
//  Creates a date/time entry picker attached to a specified text field.
//  Instead of entering a date and/or time into the text field, the user
//  selects legal combinations using the picker, and the field is auto-
//  matically populated.  The picker can be incorporated into the page
//	"inline", or used as a "popup" that appears when the text field is
//  clicked and disappears when the picker is dismissed. Ajax can be used
//  to send the selected value to a server to approve or veto it.
//
//  To create a picker, simply include the necessary files in an HTML page
//  and call the function for each date/time input field.  The following
//  example creates a popup picker for field "foo" using the default
//  format, and a second date-only (no time) inline (always-visible)
//  Ajax-enabled picker for field "bar":
//
//    <link rel="stylesheet" type="text/css" href="anytime.css" />
//    <script type="text/javascript" src="jquery.js"></script>
//    <script type="text/javascript" src="anytime.js"></script>
//    <input type="text" id="foo" tabindex="1" value="1967-07-30 23:45" />
//    <input type="text" id="bar" tabindex="2" value="01/06/90" />
//    <script type="text/javascript">
//      AnyTime.picker( "foo" );
//      AnyTime.picker( "bar", { placement:"inline", format: "%m/%d/%y",
//								ajaxOptions { url: "/some/server/page/" } } );
//    </script>
//
//  The appearance of the picker can be extensively modified using CSS styles.
//  A default appearance can be achieved by the "anytime.css" stylesheet that
//  accompanies this script.  The default style looks better in browsers other
//  than Internet Explorer (before IE8) because older versions of IE do not
//  properly implement the CSS box model standard; however, it is passable in
//  Internet Explorer as well.
//
//  Method parameters:
//
//  id - the "id" attribute of the textfield to associate with the
//    AnyTime.picker object.  The AnyTime.picker will attach itself
//    to the textfield and manage its value.
//
//  options - an object (associative array) of optional parameters that
//    override default behaviors.  The supported options are:
//
//    ajaxOptions - options passed to jQuery's $.ajax() method whenever
//      the user dismisses a popup picker or selects a value in an inline
//      picker.  The input's name (or ID) and value are passed to the
//      server (appended to ajaxOptions.data, if present), and the
//      "success" handler sets the input's value to the responseText.
//      Therefore, the text returned by the server must be valid for the
//      input'sdate/time format, and the server can approve or veto the
//      value chosen by the user. For more information, see:
//      http://docs.jquery.com/Ajax.
//      If ajaxOptions.success is specified, it is used instead of the
//      default "success" behavior.
//
//    askEra - if true, buttons to select the era are shown on the year
//        selector popup, even if format specifier does not include the
//        era.  If false, buttons to select the era are NOT shown, even
//        if the format specifier includes ther era.  Normally, era buttons
//        are only shown if the format string specifies the era.
//
//    askSecond - if false, buttons for number-of-seconds are not shown
//        even if the format includes seconds.  Normally, the buttons
//        are shown if the format string includes seconds.
//
//    earliest - String or Date object representing the earliest date/time
//        that a user can select.  For best results if the field is only
//        used to specify a date, be sure to set the time to 00:00:00.
//        If a String is used, it will be parsed according to the picker's
//        format (see AnyTime.Converter.format()).
//
//    firstDOW - a value from 0 (Sunday) to 6 (Saturday) stating which
//      day should appear at the beginning of the week.  The default is 0
//      (Sunday).  The most common substitution is 1 (Monday).  Note that
//      if custom arrays are specified for AnyTime.Converter's dayAbbreviations
//      and/or dayNames options, they should nonetheless begin with the
//      value for Sunday.
//
//    hideInput - if true, the <input> is "hidden" (the picker appears in 
//      its place). This actually sets the border, height, margin, padding
//      and width of the field as small as possivle, so it can still get focus.
//      If you try to hide the field using traditional techniques (such as
//      setting "display:none"), the picker will not behave correctly.
//
//    labelDayOfMonth - the label for the day-of-month "buttons".
//      Can be any HTML!  If not specified, "Day of Month" is assumed.
//
//    labelDismiss - the label for the dismiss "button" (if placement is
//      "popup"). Can be any HTML!  If not specified, "X" is assumed.
//
//    labelHour - the label for the hour "buttons".
//      Can be any HTML!  If not specified, "Hour" is assumed.
//
//    labelMinute - the label for the minute "buttons".
//      Can be any HTML!  If not specified, "Minute" is assumed.
//
//    labelMonth - the label for the month "buttons".
//      Can be any HTML!  If not specified, "Month" is assumed.
//
//    labelTimeZone - the label for the UTC offset (timezone) "buttons".
//      Can be any HTML!  If not specified, "Time Zone" is assumed.
//
//    labelSecond - the label for the second "buttons".
//      Can be any HTML!  If not specified, "Second" is assumed.
//      This option is ignored if askSecond is false!
//
//    labelTitle - the label for the "title bar".  Can be any HTML!
//      If not specified, then whichever of the following is most
//      appropriate is used:  "Select a Date and Time", "Select a Date"
//      or "Select a Time", or no label if only one field is present.
//
//    labelYear - the label for the year "buttons".
//      Can be any HTML!  If not specified, "Year" is assumed.
//
//    latest - String or Date object representing the latest date/time
//        that a user can select.  For best results if the field is only
//        used to specify a date, be sure to set the time to 23:59:59.
//        If a String is used, it will be parsed according to the picker's
//        format (see AnyTime.Converter.format()).
//
//    placement - One of the following strings:
//
//      "popup" = the picker appears above its <input> when the input
//        receives focus, and disappears when it is dismissed.  This is
//        the default behavior.
//
//      "inline" = the picker is placed immediately after the <input>
//        and remains visible at all times.  When choosing this placement,
//        it is best to make the <input> invisible and use only the
//        picker to select dates.  The <input> value can still be used
//        during form submission as it will always reflect the current
//        picker state.
//
//        WARNING: when using "inline" and XHTML and including a day-of-
//        the-month format field, the input may only appear where a <table>
//        element is permitted (for example, NOT within a <p> element).
//        This is because the picker uses a <table> element to arrange
//        the day-of-the-month (calendar) buttons.  Failure to follow this
//        advice may result in an "unknown error" in Internet Explorer.
//
//    The following additional options may be specified; see documentation
//    for AnyTime.Converter (above) for information about these options:
//
//      baseYear
//      dayAbbreviations
//      dayNames
//      eraAbbreviations
//      format
//      monthAbbreviations
//      monthNames
//
//  Other behavior, such as how to format the values on the display
//  and which "buttons" to include, is inferred from the format string.
//=============================================================================

AnyTime.picker = function( id, options )
{
	//  Create a new private object instance to manage the picker,
	//  if one does not already exist.
	
    if ( __pickers[id] )
    	throw 'Cannot create another AnyTime picker for "'+id+'"';

	var _this = null;

	__pickers[id] =
	{
		//  private members
		
		twelveHr: false,
		ajaxOpts: null,		// options for AJAX requests
		denyTab: true,      // set to true to stop Opera from tabbing away
		askEra: false,		// prompt the user for the era in yDiv?
		cloak: null,		// cloak div
		conv: null,			// AnyTime.Converter
	  	bMinW: 0,			// min width of body div
	  	bMinH: 0,			// min height of body div
	  	dMinW: 0,    		// min width of date div
	  	dMinH: 0,			// min height of date div
		div: null,			// picker div
	  	dB: null,			// body div
	  	dD: null,			// date div
	  	dY: null,			// years div
	  	dMo: null,			// months div
	  	dDoM: null,			// date-of-month table
	  	hDoM: null,			// date-of-month heading
	  	hMo: null,			// month heading
	  	hTitle: null,		// title heading
	  	hY: null,			// year heading
	  	dT: null,			// time div
	  	dH: null,			// hours div
	  	dM: null,			// minutes div
	  	dS: null,			// seconds div
	  	dO: null,           // offset (time zone) div
		earliest: null,		// earliest selectable date/time
		fBtn: null,			// button with current focus
		fDOW: 0,			// index to use as first day-of-week
	    hBlur: null,        // input handler
	    hClick: null,       // input handler
	    hFocus: null,       // input handler
	    hKeydown: null,     // input handler
	    hKeypress: null,    // input handler
		id: null,			// picker ID
		inp: null,			// input text field
		latest: null,		// latest selectable date/time
		lastAjax: null,		// last value submitted using AJAX
		lostFocus: false,	// when focus is lost, must redraw
		lX: 'X',			// label for dismiss button
		lY: 'Year',			// label for year
		lO: 'Time Zone',    // label for UTC offset (time zone)
		oBody: null,        // UTC offset selector popup
		oConv: null,        // AnyTime.Converter for offset display
		oCur: null,         // current-UTC-offset button
		oDiv: null,			// UTC offset selector popup
		oLab: null,			// UTC offset label
		oListMinW: 0,       // min width of offset list element
		oMinW: 0,           // min width of UTC offset element
		oSel: null,         // select (plus/minus) UTC-offset button
		offMin: Number.MIN_VALUE, // current UTC offset in minutes
		offSI: -1,          // current UTC label sub-index (if any)
		offStr: "",         // current UTC offset (time zone) string
		pop: true,			// picker is a popup?
		time: null,			// current date/time
	  	tMinW: 0,			// min width of time div
	  	tMinH: 0,			// min height of time div
		url: null,			// URL to submit value using AJAX
	  	wMinW: 0,			// min width of picker
	  	wMinH: 0,			// min height of picker
		yAhead: null,		// years-ahead button
		y0XXX: null,		// millenium-digit-zero button (for focus)
		yCur: null,			// current-year button
		yDiv: null,			// year selector popup
		yLab: null,			// year label
		yNext: null,		// next-year button
		yPast: null,		// years-past button
		yPrior: null,		// prior-year button

		//---------------------------------------------------------------------
		//  .initialize() initializes the picker instance.
		//---------------------------------------------------------------------

		initialize: function( id )
		{
			_this = this;

			this.id = 'AnyTime--'+id;

			options = jQuery.extend(true,{},options||{});
		  	options.utcParseOffsetCapture = true;
		  	this.conv = new AnyTime.Converter(options);

		  	if ( options.placement )
		  	{
		  		if ( options.placement == 'inline' )
		  			this.pop = false;
		  		else if ( options.placement != 'popup' )
		  			throw 'unknown placement: ' + options.placement;
		  	}

		  	if ( options.ajaxOptions )
		  	{
		  		this.ajaxOpts = jQuery.extend( {}, options.ajaxOptions );
		        if ( ! this.ajaxOpts.success )
		        	this.ajaxOpts.success = function(data,status) { _this.inp.val(data); };
		  	}
		    
		  	if ( options.earliest )
		  	{
		  		if ( typeof options.earliest.getTime == 'function' )
		  			this.earliest = options.earliest.getTime();
		  		else
		  			this.earliest = this.conv.parse( options.earliest.toString() );
		  	}

		  	if ( options.firstDOW )
		  	{
		  		if ( ( options.firstDOW < 0 ) || ( options.firstDOW > 6 ) )
		  			throw new Exception('illegal firstDOW: ' + options.firstDOW); 
		  		this.fDOW = options.firstDOW;
		  	}

		  	if ( options.latest )
		  	{
		  		if ( typeof options.latest.getTime == 'function' )
		  			this.latest = options.latest.getTime();
		  		else
		  			this.latest = this.conv.parse( options.latest.toString() );
		  	}

		  	this.lX = options.labelDismiss || 'X';
		  	this.lY = options.labelYear || 'Year';
		  	this.lO = options.labelTimeZone || 'Time Zone';

		  	//  Infer what we can about what to display from the format.

		  	var i;
		  	var t;
		  	var lab;
		  	var shownFields = 0;
		  	var format = this.conv.fmt;

		  	if ( typeof options.askEra != 'undefined' )
		  		this.askEra = options.askEra;
		  	else
		  		this.askEra = (format.indexOf('%B')>=0) || (format.indexOf('%C')>=0) || (format.indexOf('%E')>=0);
		  	var askYear = (format.indexOf('%Y')>=0) || (format.indexOf('%y')>=0) || (format.indexOf('%Z')>=0) || (format.indexOf('%z')>=0);
		  	var askMonth = (format.indexOf('%b')>=0) || (format.indexOf('%c')>=0) || (format.indexOf('%M')>=0) || (format.indexOf('%m')>=0);
		  	var askDoM = (format.indexOf('%D')>=0) || (format.indexOf('%d')>=0) || (format.indexOf('%e')>=0);
		  	var askDate = askYear || askMonth || askDoM;
		  	this.twelveHr = (format.indexOf('%h')>=0) || (format.indexOf('%I')>=0) || (format.indexOf('%l')>=0) || (format.indexOf('%r')>=0);
		  	var askHour = this.twelveHr || (format.indexOf('%H')>=0) || (format.indexOf('%k')>=0) || (format.indexOf('%T')>=0);
		  	var askMinute = (format.indexOf('%i')>=0) || (format.indexOf('%r')>=0) || (format.indexOf('%T')>=0);
		  	var askSec = ( (format.indexOf('%r')>=0) || (format.indexOf('%S')>=0) || (format.indexOf('%s')>=0) || (format.indexOf('%T')>=0) );
		  	if ( askSec && ( typeof options.askSecond != 'undefined' ) )
		  		askSec = options.askSecond;
		  	var askOff = ( (format.indexOf('%#')>=0) || (format.indexOf('%+')>=0) || (format.indexOf('%-')>=0) || (format.indexOf('%:')>=0) || (format.indexOf('%;')>=0) || (format.indexOf('%<')>=0) || (format.indexOf('%>')>=0) || (format.indexOf('%@')>=0) );
		  	var askTime = askHour || askMinute || askSec || askOff;

		  	if ( askOff )
			  	this.oConv = new AnyTime.Converter( { format: options.formatUtcOffset || 
			  		format.match(/\S*%[-+:;<>#@]\S*/g).join(' ') } );

		  	//  Create the picker HTML and add it to the page.
		  	//  Popup pickers will be moved to the end of the body
		  	//  once the entire page has loaded.

		  	this.inp = $('#'+id);
		  	this.div = $( '<div class="AnyTime-win AnyTime-pkr ui-widget ui-widget-content ui-corner-all" style="width:0;height:0" id="' + this.id + '" aria-live="off"/>' );
		    this.inp.after(this.div);
		  	this.wMinW = this.div.outerWidth(!$.browser.safari);
		  	this.wMinH = this.div.AnyTime_height(true);
		  	this.hTitle = $( '<h5 class="AnyTime-hdr ui-widget-header ui-corner-top"/>' ); 
		  	this.div.append( this.hTitle );
		  	this.dB = $( '<div class="AnyTime-body" style="width:0;height:0"/>' );
		  	this.div.append( this.dB );
		  	this.bMinW = this.dB.outerWidth(true);
		  	this.bMinH = this.dB.AnyTime_height(true);

		  	if ( options.hideInput )
		        this.inp.css({border:0,height:'1px',margin:0,padding:0,width:'1px'});
		  	
		  	//  Add dismiss box to title (if popup)

		  	var t = null;
		  	var xDiv = null;
		  	if ( this.pop )
		  	{
		  		xDiv = $( '<div class="AnyTime-x-btn ui-state-default">'+this.lX+'</div>' );
		  		this.hTitle.append( xDiv );
		  		xDiv.click(function(e){_this.dismiss(e);});
		  	}

		  	//  date (calendar) portion

		  	var lab = '';
		  	
		  	if ( askDate )
		  	{
			  this.dD = $( '<div class="AnyTime-date" style="width:0;height:0"/>' );
			  this.dB.append( this.dD );
		  	  this.dMinW = this.dD.outerWidth(true);
		  	  this.dMinH = this.dD.AnyTime_height(true);

		      if ( askYear )
		      {
		    	  this.yLab = $('<h6 class="AnyTime-lbl AnyTime-lbl-yr">' + this.lY + '</h6>');
		    	  this.dD.append( this.yLab );

		          this.dY = $( '<ul class="AnyTime-yrs ui-helper-reset" />' );
		          this.dD.append( this.dY );

		          this.yPast = this.btn(this.dY,'&lt;',this.newYear,['yrs-past'],'- '+this.lY);
		          this.yPrior = this.btn(this.dY,'1',this.newYear,['yr-prior'],'-1 '+this.lY);
		          this.yCur = this.btn(this.dY,'2',this.newYear,['yr-cur'],this.lY);
		          this.yCur.removeClass('ui-state-default');
		          this.yCur.addClass('AnyTime-cur-btn ui-state-default ui-state-highlight');

		          this.yNext = this.btn(this.dY,'3',this.newYear,['yr-next'],'+1 '+this.lY);
		          this.yAhead = this.btn(this.dY,'&gt;',this.newYear,['yrs-ahead'],'+ '+this.lY);
		          
		          shownFields++;

		      } // if ( askYear )

		      if ( askMonth )
		      {
		    	  lab = options.labelMonth || 'Month';
		    	  this.hMo = $( '<h6 class="AnyTime-lbl AnyTime-lbl-month">' + lab + '</h6>' );
		    	  this.dD.append( this.hMo );
		    	  this.dMo = $('<ul class="AnyTime-mons" />');
		    	  this.dD.append(this.dMo);
		    	  for ( i = 0 ; i < 12 ; i++ )
		    	  {
		    		  var mBtn = this.btn( this.dMo, this.conv.mAbbr[i], 
			    			function( event )
			    			{
			    				var elem = $(event.target);
			    			    if ( elem.hasClass("AnyTime-out-btn") )
			    			    	return;
			    				var mo = event.target.AnyTime_month;
			    				var t = new Date(this.time.getTime());
			    				if ( t.getDate() > __daysIn[mo] )
			    					t.setDate(__daysIn[mo])
			    				t.setMonth(mo);
			    				this.set(t);
			    			    this.upd(elem);
			    			},
			    			['mon','mon'+String(i+1)], lab+' '+this.conv.mNames[i] );
		    		  mBtn[0].AnyTime_month = i;
		    	  }
		    	  shownFields++;
		      }

		      if ( askDoM )
		      {
		    	lab = options.labelDayOfMonth || 'Day of Month';
		        this.hDoM = $('<h6 class="AnyTime-lbl AnyTime-lbl-dom">' + lab + '</h6>' );
		      	this.dD.append( this.hDoM );
		        this.dDoM =  $( '<table border="0" cellpadding="0" cellspacing="0" class="AnyTime-dom-table"/>' );
		        this.dD.append( this.dDoM );
		        t = $( '<thead class="AnyTime-dom-head"/>' );
		        this.dDoM.append(t);
		        var tr = $( '<tr class="AnyTime-dow"/>' );
		        t.append(tr);
		        for ( i = 0 ; i < 7 ; i++ )
		          tr.append( '<th class="AnyTime-dow AnyTime-dow'+String(i+1)+'">'+this.conv.dAbbr[(this.fDOW+i)%7]+'</th>' );

		        var tbody = $( '<tbody class="AnyTime-dom-body" />' );
		        this.dDoM.append(tbody);
		        for ( var r = 0 ; r < 6 ; r++ )
		        {
		          tr = $( '<tr class="AnyTime-wk AnyTime-wk'+String(r+1)+'"/>' );
		          tbody.append(tr);
		          for ( i = 0 ; i < 7 ; i++ )
		        	  this.btn( tr, 'x',
		        		function( event )
		        		{
		        			var elem = $(event.target);
		        		    if ( elem.hasClass("AnyTime-out-btn") )
		        		    	return;
		        			var dom = Number(elem.html());
		        			if ( dom )
		        			{
		        				var t = new Date(this.time.getTime());
		        				t.setDate(dom);
		        				this.set(t);
		        				this.upd(elem);
		        			}
		        		},
		        		['dom'], lab );
		        }
		        shownFields++;

		      } // if ( askDoM )

		    } // if ( askDate )

		    //  time portion

		    if ( askTime )
		    {
		      this.dT = $('<div class="AnyTime-time" style="width:0;height:0" />');
		      this.dB.append(this.dT);
		  	  this.tMinW = this.dT.outerWidth(true);
		  	  this.tMinH = this.dT.AnyTime_height(true);

		      if ( askHour )
		      {
		        this.dH = $('<div class="AnyTime-hrs"/>');
		        this.dT.append(this.dH);

		        lab = options.labelHour || 'Hour';
		        this.dH.append( $('<h6 class="AnyTime-lbl AnyTime-lbl-hr">'+lab+'</h6>') );
		        var amDiv = $('<ul class="AnyTime-hrs-am"/>');
		        this.dH.append( amDiv );
		        var pmDiv = $('<ul class="AnyTime-hrs-pm"/>');
		        this.dH.append( pmDiv );

		        for ( i = 0 ; i < 12 ; i++ )
		        {
		          if ( this.twelveHr )
		          {
		            if ( i == 0 )
		              t = '12am';
		            else
		              t = String(i)+'am';
		          }
		          else
		            t = AnyTime.pad(i,2);

		          this.btn( amDiv, t, this.newHour,['hr','hr'+String(i)],lab+' '+t);

		          if ( this.twelveHr )
		          {
		            if ( i == 0 )
		              t = '12pm';
		            else
		              t = String(i)+'pm';
		          }
		          else
		            t = i+12;

		          this.btn( pmDiv, t, this.newHour,['hr','hr'+String(i+12)],lab+' '+t);
		        }

				shownFields++;
				
		      } // if ( askHour )

		      if ( askMinute )
		      {
		        this.dM = $('<div class="AnyTime-mins"/>');
		        this.dT.append(this.dM);

		        lab = options.labelMinute || 'Minute';
		        this.dM.append( $('<h6 class="AnyTime-lbl AnyTime-lbl-min">'+lab+'</h6>') );
		        var tensDiv = $('<ul class="AnyTime-mins-tens"/>');
		        this.dM.append(tensDiv);

		        for ( i = 0 ; i < 6 ; i++ )
		          this.btn( tensDiv, i, 
		        		  function( event )
		        		  {
		        		      var elem = $(event.target);
		        			  if ( elem.hasClass("AnyTime-out-btn") )
		        			    	return;
		        		      var t = new Date(this.time.getTime());
		        		      t.setMinutes( (Number(elem.text())*10) + (this.time.getMinutes()%10) );
		        		      this.set(t);
		        		      this.upd(elem);
		        		  },
		        		  ['min-ten','min'+i+'0'], lab+' '+i+'0' );
		        for ( ; i < 12 ; i++ )
			          this.btn( tensDiv, '&#160;', $.noop, ['min-ten','min'+i+'0'], lab+' '+i+'0' ).addClass('AnyTime-min-ten-btn-empty ui-state-default ui-state-disabled');

		        var onesDiv = $('<ul class="AnyTime-mins-ones"/>');
		        this.dM.append(onesDiv);
		        for ( i = 0 ; i < 10 ; i++ )
		          this.btn( onesDiv, i, 
		    		  function( event )
		    		  {
		    		      var elem = $(event.target);
		    			  if ( elem.hasClass("AnyTime-out-btn") )
		    			    	return;
		    		      var t = new Date(this.time.getTime());
		    		      t.setMinutes( (Math.floor(this.time.getMinutes()/10)*10)+Number(elem.text()) );
		    		      this.set(t);
		    		      this.upd(elem);  
		    		  },
		    		  ['min-one','min'+i], lab+' '+i );
		        for ( ; i < 12 ; i++ )
			          this.btn( onesDiv, '&#160;', $.noop, ['min-one','min'+i+'0'], lab+' '+i ).addClass('AnyTime-min-one-btn-empty ui-state-default ui-state-disabled');

				shownFields++;

		      } // if ( askMinute )

		      if ( askSec )
		      {
		        this.dS = $('<div class="AnyTime-secs"/>');
		        this.dT.append(this.dS);
		        lab = options.labelSecond || 'Second';
		        this.dS.append( $('<h6 class="AnyTime-lbl AnyTime-lbl-sec">'+lab+'</h6>') );
		        var tensDiv = $('<ul class="AnyTime-secs-tens"/>');
		        this.dS.append(tensDiv);

		        for ( i = 0 ; i < 6 ; i++ )
		          this.btn( tensDiv, i,
		    		  function( event )
		    		  {
		    		      var elem = $(event.target);
		    			  if ( elem.hasClass("AnyTime-out-btn") )
		    			    	return;
		    		      var t = new Date(this.time.getTime());
		    		      t.setSeconds( (Number(elem.text())*10) + (this.time.getSeconds()%10) );
		    		      this.set(t);
		    		      this.upd(elem);
		    		  },
		    		  ['sec-ten','sec'+i+'0'], lab+' '+i+'0' );
		        for ( ; i < 12 ; i++ )
			          this.btn( tensDiv, '&#160;', $.noop, ['sec-ten','sec'+i+'0'], lab+' '+i+'0' ).addClass('AnyTime-sec-ten-btn-empty ui-state-default ui-state-disabled');

		        var onesDiv = $('<ul class="AnyTime-secs-ones"/>');
		        this.dS.append(onesDiv);
		        for ( i = 0 ; i < 10 ; i++ )
		          this.btn( onesDiv, i,
		    		  function( event )
		    		  {
		    		      var elem = $(event.target);
		    			  if ( elem.hasClass("AnyTime-out-btn") )
		    			    	return;
		    		      var t = new Date(this.time.getTime());
		    		      t.setSeconds( (Math.floor(this.time.getSeconds()/10)*10) + Number(elem.text()) );
		    		      this.set(t);
		    		      this.upd(elem);
		    		  },
		    		  ['sec-one','sec'+i], lab+' '+i );
		        for ( ; i < 12 ; i++ )
			          this.btn( onesDiv, '&#160;', $.noop, ['sec-one','sec'+i+'0'], lab+' '+i ).addClass('AnyTime-sec-one-btn-empty ui-state-default ui-state-disabled');

				shownFields++;

		      } // if ( askSec )

		      if ( askOff )
		      {
		    	this.dO = $('<div class="AnyTime-offs" />');
		        this.dT.append(this.dO);
			  	this.oMinW = this.dO.outerWidth(true);
		        
		    	this.oLab = $('<h6 class="AnyTime-lbl AnyTime-lbl-off">' + this.lO + '</h6>');
		    	this.dO.append( this.oLab );
		        
		    	var offDiv = $('<ul class="AnyTime-off-list ui-helper-reset" />');
		        this.dO.append(offDiv);
		        
		        this.oCur = this.btn(offDiv,'',this.newOffset,['off','off-cur'],lab);
		        this.oCur.removeClass('ui-state-default');
		        this.oCur.addClass('AnyTime-cur-btn ui-state-default ui-state-highlight');
		        this.oCur.css({overflow:"hidden"});

			  	this.oSel = this.btn(offDiv,'&#177;',this.newOffset,['off','off-select'],'+/- '+this.lO);
			  	this.oListMinW = this.oCur.outerWidth(true)+this.oSel.outerWidth(true);

				shownFields++;
		      }
		      
		    } // if ( askTime )

		    //  Set the title.  If a title option has been specified, use it.
		    //  Otherwise, determine a worthy title based on which (and how many)
		    //  format fields have been specified.

		    if ( options.labelTitle )
		      this.hTitle.append( options.labelTitle );
		    else if ( shownFields > 1 )
		      this.hTitle.append( 'Select a '+(askDate?(askTime?'Date and Time':'Date'):'Time') );
		    else
		      this.hTitle.append( 'Select' );


		    //  Initialize the picker's date/time value.

		    try
		    {
		      this.time = this.conv.parse(this.inp.val());
		      this.offMin = this.conv.getUtcParseOffsetCaptured();
		      this.offSI = this.conv.getUtcParseOffsetSubIndex();
		    }
		    catch ( e )
		    {
		      this.time = new Date();
		    }
		    this.lastAjax = this.time;


		    //  If this is a popup picker, hide it until needed.

		    if ( this.pop )
		    {
		      this.div.hide();
		      if ( __iframe )
		        __iframe.hide();
		      this.div.css('position','absolute');
		    }
			
		    //  Setup event listeners for the input and resize listeners for
		    //  the picker.  Add the picker to the instances list (which is used
		    //  to hide pickers if the user clicks off of them).

		    this.inp.blur( this.hBlur =
		    	function(e)
		    	{
		    		_this.inpBlur(e);

		    	} );
		    
		    this.inp.click( this.hClick =
		    	function(e)
		    	{
		    		
	    			_this.showPkr(e);
	    			this.select();
		    	} );
		    
		    this.inp.focus( this.hFocus =
		    	function(e)
		    	{
		    		if ( _this.lostFocus )
		    			_this.showPkr(e);
		    		_this.lostFocus = false;
		    		} );
		    
		    this.inp.keydown( this.hKeydown =
		    	function(e)
		    	{
		    		_this.key(e);
		    	} );
		    /*
		    this.inp.keypress( this.hKeypress =
			    	function(e)
			    	{
			    		if ( $.browser.opera && _this.denyTab )
			    			e.preventDefault();
			    	} );
			  */  
		    this.div.click( 
				function(e)
				{
					_this.lostFocus = false;
					_this.inp.focus();
					
				} );
		    
		    $(window).resize( 
		    	function(e)
		    	{
		    		_this.pos(e);
		    	} );
		    
		    if ( __initialized )
		    	this.onReady();

		}, // initialize()


		//---------------------------------------------------------------------
		//  .ajax() notifies the server of a value change using Ajax.
		//---------------------------------------------------------------------

		ajax: function()
		{
		    if ( this.ajaxOpts && ( this.time.getTime() != this.lastAjax.getTime() ) )
		    {
		      try
		      {
		    	var opts = jQuery.extend( {}, this.ajaxOpts );
		        if ( typeof opts.data == 'object' )
		        	opts.data[this.inp[0].name||this.inp[0].id] = this.inp.val();
		        else
		        {
		        	var opt = (this.inp[0].name||this.inp[0].id) + '=' + encodeURI(this.inp.val());
		        	if ( opts.data )
		        		opts.data += '&' + opt;
		        	else
		        		opts.data = opt;
		        }
		        $.ajax( opts );
		        this.lastAjax = this.time;
		      }
		      catch( e )
		      {
		      }
		    }
		    return;
		
		}, // .ajax()

		//---------------------------------------------------------------------
		//  .askOffset() is called by this.newOffset() when the UTC offset or
		//  +- selection button is clicked.
		//---------------------------------------------------------------------

		askOffset: function( event )
		{
		    if ( ! this.oDiv )
		    {
		      this.makeCloak();
		
		      this.oDiv = $('<div class="AnyTime-win AnyTime-off-selector ui-widget ui-widget-content ui-corner-all" style="position:absolute" />');
		      this.div.append(this.oDiv);
		
		      // the order here (HDR,BODY,XDIV,TITLE) is important for width calcluation:
		      var title = $('<h5 class="AnyTime-hdr AnyTime-hdr-off-selector ui-widget-header ui-corner-top" />');
		      this.oDiv.append( title );
		      this.oBody = $('<div class="AnyTime-body AnyTime-body-off-selector" style="overflow:auto;white-space:nowrap" />');
		      this.oDiv.append( this.oBody );
		      var oBHS = this.oBody.AnyTime_height(true); // body spacing
		      var oBWS = this.oBody.AnyTime_width(true);
		      var oTWS = title.AnyTime_width(true);
		      
		      var xDiv = $('<div class="AnyTime-x-btn ui-state-default">'+this.lX+'</div>');
		      title.append(xDiv);
		      xDiv.click(function(e){_this.dismissODiv(e);});
		      title.append( this.lO );
			  if ( __msie6 || __msie7 ) // IE bugs!
				  title.width(String(this.lO.length*0.8)+"em");
			  var oBW = title.AnyTime_width(true) - oBWS; // initial body width
		      
		      var cont = $('<ul class="AnyTime-off-off" />' );
		      var last = null;
		      this.oBody.append(cont);
		      var useSubIndex = (this.oConv.fmt.indexOf('%@')>=0);
		      var btnW = 0; // determine uniform button width
		      if ( AnyTime.utcLabel )
			      for ( var o = -720 ; o < 720 ; o++ )
			    	  if ( AnyTime.utcLabel[o] )
			    	  {
				        this.oConv.setUtcFormatOffsetAlleged(o);
				        for ( var i = 0; i < AnyTime.utcLabel[o].length; i++ )
				        {
				          this.oConv.setUtcFormatOffsetSubIndex(i);
				          last = this.btn( cont, this.oConv.format(this.time), this.newOPos, ['off-off'], o );
				          last[0].AnyTime_offMin = o;
				          last[0].AnyTime_offSI = i;
				          var w = last.width();
				          if ( w > btnW )
				        	  btnW = w;
				          if ( ! useSubIndex )
				        	  break; // for
				        }
			    	  }
			          
		      if ( last )
		    	  last.addClass('AnyTime-off-off-last-btn');
		      
		      // compute optimal width
		      
		      this.oBody.find('.AnyTime-off-off-btn').width(btnW); // set uniform button width
		      if ( last )
		      {
		          var lW = last.AnyTime_width(true);
		          if ( lW > oBW )
			          oBW = lW+1; // expand body to hold buttons
		      }
		      this.oBody.width(oBW);
		      oBW = this.oBody.AnyTime_width(true);
		      this.oDiv.width( oBW );		      
		      if ( __msie6 || __msie7 ) // IE bugs!
				  title.width( oBW - oTWS );

		      // compute optimal height
		      
		      var oH = this.oDiv.AnyTime_height(true);
		      var oHmax = this.div.height() * 0.75;
		      if ( oH > oHmax )
		      {
		    	  oH = oHmax;
		    	  this.oBody.height(oH-(title.AnyTime_height(true)+oBHS));
			      this.oBody.width(this.oBody.width()+20); // add nominal px for scrollbar 
			      this.oDiv.width(this.oDiv.width()+20); 
			      if ( __msie6 || __msie7 ) // IE bugs!
					  title.width( this.oBody.AnyTime_width(true) - oTWS );
		      }
			  if ( ! __msie7 ) // IE7 bug!
				  this.oDiv.height(String(oH)+'px');

		    } // if ( ! this.oDiv )
		    else
		    {
		      this.cloak.show();
		      this.oDiv.show();
		    }
		    this.pos(event);
		    this.updODiv(null);

		    var f = this.oDiv.find('.AnyTime-off-off-btn.AnyTime-cur-btn:first');
		    if ( ! f.length )
		    	f = this.oDiv.find('.AnyTime-off-off-btn:first');
		    this.setFocus( f );
		
		}, // .askOffset()

		//---------------------------------------------------------------------
		//  .askYear() is called by this.newYear() when the yPast or yAhead
		//  button is clicked.
		//---------------------------------------------------------------------

		askYear: function( event )
		{
		    if ( ! this.yDiv )
		    {
		      this.makeCloak();
		
		      this.yDiv = $('<div class="AnyTime-win AnyTime-yr-selector ui-widget ui-widget-content ui-corner-all" style="position:absolute" />');
		      this.div.append(this.yDiv);
		
		      var title = $('<h5 class="AnyTime-hdr AnyTime-hdr-yr-selector ui-widget-header ui-corner-top" />');
		      this.yDiv.append( title );
		
		      var xDiv = $('<div class="AnyTime-x-btn ui-state-default">'+this.lX+'</div>');
		      title.append(xDiv);
		      xDiv.click(function(e){_this.dismissYDiv(e);});
		
		      title.append( this.lY );
		
		      var yBody = $('<div class="AnyTime-body AnyTime-body-yr-selector" />');
		      var yW = yBody.AnyTime_width(true);
		      var yH = 0;
		      this.yDiv.append( yBody );
		      
		      cont = $('<ul class="AnyTime-yr-mil" />' );
		      yBody.append(cont);
		      this.y0XXX = this.btn( cont, 0, this.newYPos,['mil','mil0'],this.lY+' '+0+'000');
		      for ( i = 1; i < 10 ; i++ )
		        this.btn( cont, i, this.newYPos,['mil','mil'+i],this.lY+' '+i+'000');
		      yW += cont.AnyTime_width(true);
		      if ( yH < cont.AnyTime_height(true) )
		    	  yH = cont.AnyTime_height(true);
		
			  cont = $('<ul class="AnyTime-yr-cent" />' );
		      yBody.append(cont);
		      for ( i = 0 ; i < 10 ; i++ )
		        this.btn( cont, i, this.newYPos,['cent','cent'+i],this.lY+' '+i+'00');
		      yW += cont.AnyTime_width(true);
		      if ( yH < cont.AnyTime_height(true) )
		    	  yH = cont.AnyTime_height(true);

		      cont = $('<ul class="AnyTime-yr-dec" />');
		      yBody.append(cont);
		      for ( i = 0 ; i < 10 ; i++ )
		        this.btn( cont, i, this.newYPos,['dec','dec'+i],this.lY+' '+i+'0');
		      yW += cont.AnyTime_width(true);
		      if ( yH < cont.AnyTime_height(true) )
		    	  yH = cont.AnyTime_height(true);
		
		      cont = $('<ul class="AnyTime-yr-yr" />');
		      yBody.append(cont);
		      for ( i = 0 ; i < 10 ; i++ )
		        this.btn( cont, i, this.newYPos,['yr','yr'+i],this.lY+' '+i );
		      yW += cont.AnyTime_width(true);
		      if ( yH < cont.AnyTime_height(true) )
		    	  yH = cont.AnyTime_height(true);
		
		      if ( this.askEra )
		      {
		        cont = $('<ul class="AnyTime-yr-era" />' );
		        yBody.append(cont);
		
		        this.btn( cont, this.conv.eAbbr[0],
		        		function( event )
		        		{
	  		      			var t = new Date(this.time.getTime());
		        			var year = t.getFullYear();
		        		    if ( year > 0 )
								t.setFullYear(0-year);
							this.set(t);
							this.updYDiv($(event.target));
		        		},
		        		['era','bce'], this.conv.eAbbr[0] );
		
		        this.btn( cont, this.conv.eAbbr[1],
		        		function( event )
		        		{
			      			var t = new Date(this.time.getTime());
		        			var year = t.getFullYear();
		        		    if ( year < 0 )
								t.setFullYear(0-year);
							this.set(t);
							this.updYDiv($(event.target));
		        		},
		        		['era','ce'], this.conv.eAbbr[1] );
		        
		        yW += cont.AnyTime_width(true);
		        if ( yH < cont.AnyTime_height(true) )
		        	yH = cont.AnyTime_height(true);

		      } // if ( this.askEra )

		      if ( $.browser.msie ) // IE8+ThemeUI bug!
		    	  yW += 1;
		      else if ( $.browser.safari ) // Safari small-text bug!
		    	  yW += 2;
			  yH += yBody.AnyTime_height(true);
			  yBody.css('width',String(yW)+'px');
			  if ( ! __msie7 ) // IE7 bug!
				  yBody.css('height',String(yH)+'px');
		      if ( __msie6 || __msie7 ) // IE bugs!
		    	  title.width(yBody.outerWidth(true));
		      yH += title.AnyTime_height(true);
		      if ( title.AnyTime_width(true) > yW )
		          yW = title.AnyTime_width(true);
		      this.yDiv.css('width',String(yW)+'px');
			  if ( ! __msie7 ) // IE7 bug!
				  this.yDiv.css('height',String(yH)+'px');
		
		    } // if ( ! this.yDiv )
		    else
		    {
		      this.cloak.show();
		      this.yDiv.show();
		    }
		    this.pos(event);
		    this.updYDiv(null);
		    this.setFocus( this.yDiv.find('.AnyTime-yr-btn.AnyTime-cur-btn:first') );
		
		}, // .askYear()

		//---------------------------------------------------------------------
		//  .inpBlur() is called when a picker's input loses focus to dismiss
		//  the popup.  A 1/3 second delay is necessary to restore focus if
		//	the div is clicked (shorter delays don't always work!)  To prevent
		//  problems cause by scrollbar focus (except in FF), focus is
		//  force-restored if the offset div is visible. 
		//---------------------------------------------------------------------
  
		inpBlur: function(event)
		{
			if ( this.oDiv && this.oDiv.is(":visible") )
			{
				_this.inp.focus();
				
				return;
			}
			this.lostFocus = true;
		    setTimeout(
		    	function()
		    	{ 
		    		if ( _this.lostFocus )
		    		{	
		    			_this.div.find('.AnyTime-focus-btn').removeClass('AnyTime-focus-btn ui-state-focus'); 
		    			if ( _this.pop )
		    				_this.dismiss(event);
		    			else
		    				_this.ajax();
		    		}
		    	}, 334 );
		},
		
		//---------------------------------------------------------------------
		//  .btn() is called by AnyTime.picker() to create a <div> element
		//  containing an <a> element.  The elements are given appropriate
		//  classes based on the specified "classes" (an array of strings).
		//	The specified "text" and "title" are used for the <a> element.
		//	The "handler" is bound to click events for the <div>, which will
		//	catch bubbling clicks from the <a> as well.  The button is
		//	appended to the specified parent (jQuery), and the <div> jQuery
		//	is returned.
		//---------------------------------------------------------------------
		
		btn: function( parent, text, handler, classes, title )
		{
			var tagName = ( (parent[0].nodeName.toLowerCase()=='ul')?'li':'td'); 
			var div$ = '<' + tagName +
			  				' class="AnyTime-btn';
			for ( var i = 0 ; i < classes.length ; i++ )
				div$ += ' AnyTime-' + classes[i] + '-btn';
			var div = $( div$ + ' ui-state-default">' + text + '</' + tagName + '>' );
			parent.append(div);
			div.AnyTime_title = title;
			
			div.click(
			    function(e)
			  	{
			      // bind the handler to the picker so "this" is correct
				  _this.tempFunc = handler;
				  _this.tempFunc(e);
			  	});
			div.dblclick(
				function(e)
				{ 					
					var elem = $(this);
					if ( elem.is('.AnyTime-off-off-btn') )
						_this.dismissODiv(e);
					else if ( elem.is('.AnyTime-mil-btn') || elem.is('.AnyTime-cent-btn') || elem.is('.AnyTime-dec-btn') || elem.is('.AnyTime-yr-btn') || elem.is('.AnyTime-era-btn') )
						_this.dismissYDiv(e);
					else if ( _this.pop )
						_this.dismiss(e); 
				});
		    return div;
		
		}, // .btn()
	
		//---------------------------------------------------------------------
		//  .cleanup() destroys the DOM events and elements associated with
		//  the picker so it can be deleted.
		//---------------------------------------------------------------------
	
		cleanup: function(event)
		{
			this.inp.unbind('blur',this.hBlur);
		    this.inp.unbind('click',this.hClick);
		    this.inp.unbind('focus',this.hFocus);
		    this.inp.unbind('keydown',this.hKeydown);
		    this.inp.unbind('keypress',this.hKeypress);
			this.div.remove();
		},
		
		//---------------------------------------------------------------------
		//  .dismiss() dismisses a popup picker.
		//---------------------------------------------------------------------
	
		dismiss: function(event)
		{
			this.ajax();
			this.div.hide();
			if ( __iframe )
				__iframe.hide();
			if ( this.yDiv )
				this.dismissYDiv();
			if ( this.oDiv )
				this.dismissODiv();
			this.lostFocus = true;
		},
	
		//---------------------------------------------------------------------
		//  .dismissODiv() dismisses the UTC offset selector popover.
		//---------------------------------------------------------------------
	
		dismissODiv: function(event)
		{
		    this.oDiv.hide();
		    this.cloak.hide();
			this.setFocus(this.oCur);
		},
	
		//---------------------------------------------------------------------
		//  .dismissYDiv() dismisses the date selector popover.
		//---------------------------------------------------------------------
	
		dismissYDiv: function(event)
		{
		    this.yDiv.hide();
		    this.cloak.hide();
			this.setFocus(this.yCur);
		},
	
		//---------------------------------------------------------------------
		//  .setFocus() makes a specified psuedo-button appear to get focus.
		//---------------------------------------------------------------------
		
		setFocus: function(btn)
		{
			if ( ! btn.hasClass('AnyTime-focus-btn') )
			{
				this.div.find('.AnyTime-focus-btn').removeClass('AnyTime-focus-btn ui-state-focus');
				this.fBtn = btn;
				btn.removeClass('ui-state-default ui-state-highlight');
				btn.addClass('AnyTime-focus-btn ui-state-default ui-state-highlight ui-state-focus');
			}
			if ( btn.hasClass('AnyTime-off-off-btn') )
			{
				var oBT = this.oBody.offset().top;
				var btnT = btn.offset().top;
				var btnH = btn.AnyTime_height(true);
				if ( btnT - btnH < oBT ) // move a page up
					this.oBody.scrollTop( btnT + this.oBody.scrollTop() - ( this.oBody.innerHeight() + oBT ) + ( btnH * 2 ) );
				else if ( btnT + btnH > oBT + this.oBody.innerHeight() ) // move a page down
					this.oBody.scrollTop( ( btnT + this.oBody.scrollTop() ) - ( oBT + btnH ) ); 
			}
		},
		  
		//---------------------------------------------------------------------
		//  .key() is invoked when a user presses a key while the picker's
		//	input has focus.  A psuedo-button is considered "in focus" and an
		//	appropriate action is performed according to the WAI-ARIA Authoring
		//	Practices 1.0 for datepicker from
		//  www.w3.org/TR/2009/WD-wai-aria-practices-20091215/#datepicker:
		//
		//  * LeftArrow moves focus left, continued to previous week.
		//  * RightArrow moves focus right, continued to next week.
		//  * UpArrow moves focus to the same weekday in the previous week.
		//  * DownArrow moves focus to same weekday in the next week.
		//  * PageUp moves focus to same day in the previous month.
		//  * PageDown moves focus to same day in the next month.
		//  * Shift+Page Up moves focus to same day in the previous year.
		//  * Shift+Page Down moves focus to same day in the next year.
		//  * Home moves focus to the first day of the month.
		//  * End moves focus to the last day of the month.
		//  * Ctrl+Home moves focus to the first day of the year.
		//  * Ctrl+End moves focus to the last day of the year.
		//  * Esc closes a DatePicker that is opened as a Popup.  
		//
		//  The following actions (for multiple-date selection) are NOT
		//	supported:
		//  * Shift+Arrow performs continous selection.  
		//  * Ctrl+Space multiple selection of certain days.
		//
		//  The authoring practices do not specify behavior for a time picker,
		//  or for month-and-year pickers that do not have a day-of-the-month,
		//  but AnyTime.picker uses the following behavior to be as consistent
		//  as possible with the defined datepicker functionality:
		//  * LeftArrow moves focus left or up to previous value or field.
		//  * RightArrow moves focus right or down to next value or field.
		//  * UpArrow moves focus up or left to previous value or field.
		//  * DownArrow moves focus down or right to next value or field 
		//  * PageUp moves focus to the current value in the previous units
		//    (for example, from ten-minutes to hours or one-minutes to
		//	  ten-minutes or months to years).
		//  * PageDown moves focus to the current value in the next units
		//    (for example, from hours to ten-minutes or ten-minutes to 
		//    one-minutes or years to months).
		//  * Home moves the focus to the first unit button.
		//  * End moves the focus to the last unit button.
		//
		//  In addition, Tab and Shift+Tab move between units (including to/
		//	from the Day-of-Month table) and also in/out of the picker.
		//
		//  Because AnyTime.picker sets a value as soon as the button receives
		//  focus, SPACE and ENTER are not needed (the WAI-ARIA guidelines use
		//  them to select a value.
		//---------------------------------------------------------------------
		
		key: function(event)
		{	return;
			var t = null;
			var elem = this.div.find('.AnyTime-focus-btn');
		    var key = event.keyCode || event.which;
		    this.denyTab = true;

		    if ( key == 16 ) // Shift
		    {
		    }
		    else if ( ( key == 10 ) || ( key == 13 ) || ( key == 27 ) ) // Enter & Esc
		    {
		      if ( this.oDiv && this.oDiv.is(':visible') )
		        this.dismissODiv(event);
		      else if ( this.yDiv && this.yDiv.is(':visible') )
			    this.dismissYDiv(event);
		      else if ( this.pop )
			    this.dismiss(event);
		    }
		    else if ( ( key == 33 ) || ( ( key == 9 ) && event.shiftKey ) ) // PageUp & Shift+Tab
		    {
		    	if ( this.fBtn.hasClass('AnyTime-off-off-btn') )
				{
		    		if ( key == 9 )
				        this.dismissODiv(event);
				}
		    	else if ( this.fBtn.hasClass('AnyTime-mil-btn') )
				{
		    		if ( key == 9 )
				        this.dismissYDiv(event);
				}
		    	else if ( this.fBtn.hasClass('AnyTime-cent-btn') )
					this.yDiv.find('.AnyTime-mil-btn.AnyTime-cur-btn').triggerHandler('click');
		    	else if ( this.fBtn.hasClass('AnyTime-dec-btn') )
					this.yDiv.find('.AnyTime-cent-btn.AnyTime-cur-btn').triggerHandler('click');
		    	else if ( this.fBtn.hasClass('AnyTime-yr-btn') )
					this.yDiv.find('.AnyTime-dec-btn.AnyTime-cur-btn').triggerHandler('click');
		    	else if ( this.fBtn.hasClass('AnyTime-era-btn') )
					this.yDiv.find('.AnyTime-yr-btn.AnyTime-cur-btn').triggerHandler('click');
		    	else if ( this.fBtn.parents('.AnyTime-yrs').length )
				{
					if ( key == 9 )
					{
						this.denyTab = false;
						return;
					}
				}
		    	else if ( this.fBtn.hasClass('AnyTime-mon-btn') )
				{
					if ( this.dY )
						this.yCur.triggerHandler('click');
					else if ( key == 9 )
					{
						this.denyTab = false;
						return;
					}
				}
		    	else if ( this.fBtn.hasClass('AnyTime-dom-btn') )
		    	{
		    		if ( ( key == 9 ) && event.shiftKey ) // Shift+Tab
					{
						this.denyTab = false;
						return;
					}
		    		else // PageUp
		    		{
			    		t = new Date(this.time.getTime());
				    	if ( event.shiftKey )
				    		t.setFullYear(t.getFullYear()-1);
				    	else
				    	{
				    		var mo = t.getMonth()-1;
		    				if ( t.getDate() > __daysIn[mo] )
		    					t.setDate(__daysIn[mo])
			    			t.setMonth(mo);
				    	}
			    		this.keyDateChange(t);
		    		}
		    	}
		    	else if ( this.fBtn.hasClass('AnyTime-hr-btn') )
				{
		    		t = this.dDoM || this.dMo;
					if ( t )
						t.AnyTime_clickCurrent();
					else if ( this.dY )
						this.yCur.triggerHandler('click');
					else if ( key == 9 )
					{
						this.denyTab = false;
						return;
					}
				}
		    	else if ( this.fBtn.hasClass('AnyTime-min-ten-btn') )
				{
		    		t = this.dH || this.dDoM || this.dMo;
					if ( t )
						t.AnyTime_clickCurrent();
					else if ( this.dY )
						this.yCur.triggerHandler('click');
					else if ( key == 9 )
					{
						this.denyTab = false;
						return;
					}
				}
		    	else if ( this.fBtn.hasClass('AnyTime-min-one-btn') )
					this.dM.AnyTime_clickCurrent();
		    	else if ( this.fBtn.hasClass('AnyTime-sec-ten-btn') )
				{
		    		if ( this.dM )
		    			t = this.dM.find('.AnyTime-mins-ones');
		    		else
		    			t = this.dH || this.dDoM || this.dMo;
					if ( t )
						t.AnyTime_clickCurrent();
					else if ( this.dY )
						this.yCur.triggerHandler('click');
					else if ( key == 9 )
					{
						this.denyTab = false;
						return;
					}
				}
		    	else if ( this.fBtn.hasClass('AnyTime-sec-one-btn') )
					this.dS.AnyTime_clickCurrent();
		    	else if ( this.fBtn.hasClass('AnyTime-off-btn') )
				{
		    		if ( this.dS )
		    			t = this.dS.find('.AnyTime-secs-ones');
		    		else if ( this.dM )
		    			t = this.dM.find('.AnyTime-mins-ones');
		    		else
		    			t = this.dH || this.dDoM || this.dMo;
					if ( t )
						t.AnyTime_clickCurrent();
					else if ( this.dY )
						this.yCur.triggerHandler('click');
					else if ( key == 9 )
					{
						this.denyTab = false;
						return;
					}
				}
			}
		    else if ( ( key == 34 ) || ( key == 9 ) ) // PageDown or Tab
		    {
		    	if ( this.fBtn.hasClass('AnyTime-mil-btn') )
					this.yDiv.find('.AnyTime-cent-btn.AnyTime-cur-btn').triggerHandler('click');
		    	else if ( this.fBtn.hasClass('AnyTime-cent-btn') )
					this.yDiv.find('.AnyTime-dec-btn.AnyTime-cur-btn').triggerHandler('click');
		    	else if ( this.fBtn.hasClass('AnyTime-dec-btn') )
					this.yDiv.find('.AnyTime-yr-btn.AnyTime-cur-btn').triggerHandler('click');
		    	else if ( this.fBtn.hasClass('AnyTime-yr-btn') )
		    	{
		    		t = this.yDiv.find('.AnyTime-era-btn.AnyTime-cur-btn');
					if ( t.length )
						t.triggerHandler('click');
					else if ( key == 9 )
						this.dismissYDiv(event);
		    	}
		    	else if ( this.fBtn.hasClass('AnyTime-era-btn') )
		    	{
		    		if ( key == 9 )
		    			this.dismissYDiv(event);
		    	}
		    	else if ( this.fBtn.hasClass('AnyTime-off-off-btn') )
		    	{
		    		if ( key == 9 )
		    			this.dismissODiv(event);
		    	}
		    	else if ( this.fBtn.parents('.AnyTime-yrs').length )
				{
		    		t = this.dDoM || this.dMo || this.dH || this.dM || this.dS || this.dO; 
					if ( t )
						t.AnyTime_clickCurrent();
					else if ( key == 9 )
					{
						this.denyTab = false;
						return;
					}
				}
		    	else if ( this.fBtn.hasClass('AnyTime-mon-btn') )
				{
		    		t = this.dDoM || this.dH || this.dM || this.dS || this.dO; 
					if ( t )
						t.AnyTime_clickCurrent();
					else if ( key == 9 )
					{
						this.denyTab = false;
						return;
					}
				}
		    	else if ( this.fBtn.hasClass('AnyTime-dom-btn') )
		    	{
		    		if ( key == 9 ) // Tab
		    		{
		        		t = this.dH || this.dM || this.dS || this.dO; 
		    			if ( t )
							t.AnyTime_clickCurrent();
		    			else
						{
							this.denyTab = false;
							return;
						}
		    		}
		    		else // PageDown
		    		{
			    		t = new Date(this.time.getTime());
				    	if ( event.shiftKey )
				    		t.setFullYear(t.getFullYear()+1);
				    	else
				    	{
				    		var mo = t.getMonth()+1;
		    				if ( t.getDate() > __daysIn[mo] )
		    					t.setDate(__daysIn[mo])
			    			t.setMonth(mo);
				    	}
			    		this.keyDateChange(t);
		    		}
		    	}
		    	else if ( this.fBtn.hasClass('AnyTime-hr-btn') )
				{
		    		t = this.dM || this.dS || this.dO; 
					if ( t )
						t.AnyTime_clickCurrent();
					else if ( key == 9 )
					{
						this.denyTab = false;
						return;
					}
				}
		    	else if ( this.fBtn.hasClass('AnyTime-min-ten-btn') )
		    		this.dM.find('.AnyTime-mins-ones .AnyTime-cur-btn').triggerHandler('click');
		    	else if ( this.fBtn.hasClass('AnyTime-min-one-btn') )
				{
					t = this.dS || this.dO;
					if ( t )
						t.AnyTime_clickCurrent();
					else if ( key == 9 )
					{
						this.denyTab = false;
						return;
					}
				}
		    	else if ( this.fBtn.hasClass('AnyTime-sec-ten-btn') )
		    		this.dS.find('.AnyTime-secs-ones .AnyTime-cur-btn').triggerHandler('click');
		    	else if ( this.fBtn.hasClass('AnyTime-sec-one-btn') )
				{
		    		if ( this.dO )
						this.dO.AnyTime_clickCurrent();
		    		else if ( key == 9 )
					{
						this.denyTab = false;
						return;
					}
				}
		    	else if ( this.fBtn.hasClass('AnyTime-off-btn') )
				{
		    		if ( key == 9 )
					{
						this.denyTab = false;
						return;
					}
				}
			}
		    else if ( key == 35 ) // END
		    {
		    	if ( this.fBtn.hasClass('AnyTime-mil-btn') || this.fBtn.hasClass('AnyTime-cent-btn') ||
				    this.fBtn.hasClass('AnyTime-dec-btn') || this.fBtn.hasClass('AnyTime-yr-btn') ||
				    this.fBtn.hasClass('AnyTime-era-btn') )
		    	{
		    		t = this.yDiv.find('.AnyTime-ce-btn');
		    		if ( ! t.length ) 
		    			t = this.yDiv.find('.AnyTime-yr9-btn');
		    		t.triggerHandler('click');
		    	}
		    	else if ( this.fBtn.hasClass('AnyTime-dom-btn') )
		    	{
		    		t = new Date(this.time.getTime());
					t.setDate(1);
		    		t.setMonth(t.getMonth()+1);
					t.setDate(t.getDate()-1);
			    	if ( event.ctrlKey )
			    		t.setMonth(11);
		    		this.keyDateChange(t);
		    	}
		    	else if ( this.dS )
					this.dS.find('.AnyTime-sec9-btn').triggerHandler('click');
		    	else if ( this.dM )
					this.dM.find('.AnyTime-min9-btn').triggerHandler('click');
				else if ( this.dH )
					this.dH.find('.AnyTime-hr23-btn').triggerHandler('click');
				else if ( this.dDoM )
					this.dDoM.find('.AnyTime-dom-btn-filled:last').triggerHandler('click');
				else if ( this.dMo )
					this.dMo.find('.AnyTime-mon12-btn').triggerHandler('click');
				else if ( this.dY )
					this.yAhead.triggerHandler('click');
		    }
		    else if ( key == 36 ) // HOME
		    {
		    	if ( this.fBtn.hasClass('AnyTime-mil-btn') || this.fBtn.hasClass('AnyTime-cent-btn') ||
				    this.fBtn.hasClass('AnyTime-dec-btn') || this.fBtn.hasClass('AnyTime-yr-btn') ||
				    this.fBtn.hasClass('AnyTime-era-btn') )
				{
		    		this.yDiv.find('.AnyTime-mil0-btn').triggerHandler('click');
		    	}
			    else if ( this.fBtn.hasClass('AnyTime-dom-btn') )
		    	{
		    		t = new Date(this.time.getTime());
					t.setDate(1);
			    	if ( event.ctrlKey )
			    		t.setMonth(0);
		    		this.keyDateChange(t);
		    	}
				else if ( this.dY )
					this.yCur.triggerHandler('click');
				else if ( this.dMo )
					this.dMo.find('.AnyTime-mon1-btn').triggerHandler('click');
				else if ( this.dDoM )
					this.dDoM.find('.AnyTime-dom-btn-filled:first').triggerHandler('click');
				else if ( this.dH )
					this.dH.find('.AnyTime-hr0-btn').triggerHandler('click');
		    	else if ( this.dM )
					this.dM.find('.AnyTime-min00-btn').triggerHandler('click');
		    	else if ( this.dS )
					this.dS.find('.AnyTime-sec00-btn').triggerHandler('click');
		    }
		    else if ( key == 37 ) // left arrow
		    {
		    	if ( this.fBtn.hasClass('AnyTime-dom-btn') )
		    		this.keyDateChange(new Date(this.time.getTime()-__oneDay));
		    	else
		    		this.keyBack();
		    }
		    else if ( key == 38 ) // up arrow
		    {
		    	if ( this.fBtn.hasClass('AnyTime-dom-btn') )
		    		this.keyDateChange(new Date(this.time.getTime()-(7*__oneDay)));
		    	else
		    		this.keyBack();
		    }
		    else if ( key == 39 ) // right arrow
		    {
		    	if ( this.fBtn.hasClass('AnyTime-dom-btn') )
		    		this.keyDateChange(new Date(this.time.getTime()+__oneDay));
		    	else
		    		this.keyAhead();
		    }
		    else if ( key == 40 ) // down arrow
		    {
		    	if ( this.fBtn.hasClass('AnyTime-dom-btn') )
		    		this.keyDateChange(new Date(this.time.getTime()+(7*__oneDay)));
		    	else
		    		this.keyAhead();
		    }
		    else if ( ( ( key == 86 ) || ( key == 118 ) ) && event.ctrlKey )
		    {
		    	this.inp.val("").change();
		    	var _this = this;
		    	setTimeout( function() { _this.showPkr(null); }, 100 );	
		    	return;
		    }
		    else
    			this.showPkr(null);

		    /*event.preventDefault();*/
		
		}, // .key()
	
		//---------------------------------------------------------------------
		//  .keyAhead() is called by #key when a user presses the right or
		//	down arrow.  It moves to the next appropriate button.
		//---------------------------------------------------------------------
		  
		keyAhead: function()
		{
		   	if ( this.fBtn.hasClass('AnyTime-mil9-btn') )
		   		this.yDiv.find('.AnyTime-cent0-btn').triggerHandler('click');
		   	else if ( this.fBtn.hasClass('AnyTime-cent9-btn') )
		   		this.yDiv.find('.AnyTime-dec0-btn').triggerHandler('click');
		   	else if ( this.fBtn.hasClass('AnyTime-dec9-btn') )
		   		this.yDiv.find('.AnyTime-yr0-btn').triggerHandler('click');
		   	else if ( this.fBtn.hasClass('AnyTime-yr9-btn') )
		   		this.yDiv.find('.AnyTime-bce-btn').triggerHandler('click');
		   	else if ( this.fBtn.hasClass('AnyTime-sec9-btn') )
		   		{}
		   	else if ( this.fBtn.hasClass('AnyTime-sec50-btn') )
		   		this.dS.find('.AnyTime-sec0-btn').triggerHandler('click');
		   	else if ( this.fBtn.hasClass('AnyTime-min9-btn') )
		   	{
		   		if ( this.dS )
		   			this.dS.find('.AnyTime-sec00-btn').triggerHandler('click');
		   	}
		   	else if ( this.fBtn.hasClass('AnyTime-min50-btn') )
		   		this.dM.find('.AnyTime-min0-btn').triggerHandler('click');
		   	else if ( this.fBtn.hasClass('AnyTime-hr23-btn') )
		   	{
		   		if ( this.dM )
		   			this.dM.find('.AnyTime-min00-btn').triggerHandler('click');
		   		else if ( this.dS )
		   			this.dS.find('.AnyTime-sec00-btn').triggerHandler('click');
		   	}
		   	else if ( this.fBtn.hasClass('AnyTime-hr11-btn') )
				this.dH.find('.AnyTime-hr12-btn').triggerHandler('click');
		   	else if ( this.fBtn.hasClass('AnyTime-mon12-btn') )
		   	{
		   		if ( this.dDoM )
		   			this.dDoM.AnyTime_clickCurrent();
		   		else if ( this.dH )
		   			this.dH.find('.AnyTime-hr0-btn').triggerHandler('click');
		   		else if ( this.dM )
		   			this.dM.find('.AnyTime-min00-btn').triggerHandler('click');
		   		else if ( this.dS )
		   			this.dS.find('.AnyTime-sec00-btn').triggerHandler('click');
		   	}
		   	else if ( this.fBtn.hasClass('AnyTime-yrs-ahead-btn') )
		   	{
		   		if ( this.dMo )
		   			this.dMo.find('.AnyTime-mon1-btn').triggerHandler('click');
		   		else if ( this.dH )
		   			this.dH.find('.AnyTime-hr0-btn').triggerHandler('click');
		   		else if ( this.dM )
		   			this.dM.find('.AnyTime-min00-btn').triggerHandler('click');
		   		else if ( this.dS )
		   			this.dS.find('.AnyTime-sec00-btn').triggerHandler('click');
		   	}
		   	else if ( this.fBtn.hasClass('AnyTime-yr-cur-btn') )
		        this.yNext.triggerHandler('click');
		   	else
				 this.fBtn.next().triggerHandler('click');
		
		}, // .keyAhead()
		
		  
		//---------------------------------------------------------------------
		//  .keyBack() is called by #key when a user presses the left or
		//	up arrow. It moves to the previous appropriate button.
		//---------------------------------------------------------------------
		  
		keyBack: function()
		{
		   	if ( this.fBtn.hasClass('AnyTime-cent0-btn') )
		   		this.yDiv.find('.AnyTime-mil9-btn').triggerHandler('click');
		   	else if ( this.fBtn.hasClass('AnyTime-dec0-btn') )
		   		this.yDiv.find('.AnyTime-cent9-btn').triggerHandler('click');
		   	else if ( this.fBtn.hasClass('AnyTime-yr0-btn') )
		   		this.yDiv.find('.AnyTime-dec9-btn').triggerHandler('click');
		   	else if ( this.fBtn.hasClass('AnyTime-bce-btn') )
			   		this.yDiv.find('.AnyTime-yr9-btn').triggerHandler('click');
		   	else if ( this.fBtn.hasClass('AnyTime-yr-cur-btn') )
		        this.yPrior.triggerHandler('click');
		   	else if ( this.fBtn.hasClass('AnyTime-mon1-btn') )
		   	{
		   		if ( this.dY )
		   			this.yCur.triggerHandler('click');
		   	}
		   	else if ( this.fBtn.hasClass('AnyTime-hr0-btn') )
		   	{
		   		if ( this.dDoM )
		   			this.dDoM.AnyTime_clickCurrent();
		   		else if ( this.dMo )
		   			this.dMo.find('.AnyTime-mon12-btn').triggerHandler('click');
		   		else if ( this.dY )
		   			this.yNext.triggerHandler('click');
		   	}
		   	else if ( this.fBtn.hasClass('AnyTime-hr12-btn') )
		   		 this.dH.find('.AnyTime-hr11-btn').triggerHandler('click');
		   	else if ( this.fBtn.hasClass('AnyTime-min00-btn') )
		   	{
		   		if ( this.dH )
		   			this.dH.find('.AnyTime-hr23-btn').triggerHandler('click');
		   		else if ( this.dDoM )
		   			this.dDoM.AnyTime_clickCurrent();
		   		else if ( this.dMo )
		   			this.dMo.find('.AnyTime-mon12-btn').triggerHandler('click');
		   		else if ( this.dY )
		   			this.yNext.triggerHandler('click');
		   	}
		   	else if ( this.fBtn.hasClass('AnyTime-min0-btn') )
		   		 this.dM.find('.AnyTime-min50-btn').triggerHandler('click');
		   	else if ( this.fBtn.hasClass('AnyTime-sec00-btn') )
		   	{
		   		if ( this.dM )
		   			this.dM.find('.AnyTime-min9-btn').triggerHandler('click');
		   		else if ( this.dH )
		   			this.dH.find('.AnyTime-hr23-btn').triggerHandler('click');
		   		else if ( this.dDoM )
		   			this.dDoM.AnyTime_clickCurrent();
		   		else if ( this.dMo )
		   			this.dMo.find('.AnyTime-mon12-btn').triggerHandler('click');
		   		else if ( this.dY )
		   			this.yNext.triggerHandler('click');
		   	}
		   	else if ( this.fBtn.hasClass('AnyTime-sec0-btn') )
		   		 this.dS.find('.AnyTime-sec50-btn').triggerHandler('click');
		   	else
				 this.fBtn.prev().triggerHandler('click');
		
		}, // .keyBack()
		
		//---------------------------------------------------------------------
		//  .keyDateChange() is called by #key when an direction key
		//	(arrows/page/etc) is pressed while the Day-of-Month calendar has
		//	focus. The current day is adjusted accordingly.
		//---------------------------------------------------------------------
		  
		keyDateChange: function( newDate )
		{
			if ( this.fBtn.hasClass('AnyTime-dom-btn') )
			{
				this.set(newDate);
				this.upd(null);
				this.setFocus( this.dDoM.find('.AnyTime-cur-btn') );
			}
		},
		  
		//---------------------------------------------------------------------
		//  .makeCloak() is called by .askOffset() and .askYear() to create
		//  a cloak div.
		//---------------------------------------------------------------------

		makeCloak: function()
		{
			if ( ! this.cloak )
			{
		      this.cloak = $('<div class="AnyTime-cloak" style="position:absolute" />');
		      this.div.append( this.cloak );
		      this.cloak.click(
		        function(e)
		        {
		        	if ( _this.oDiv && _this.oDiv.is(":visible") )
		        		_this.dismissODiv(e);
		        	else
		        		_this.dismissYDiv(e);
		        });
		    }
			else
		      this.cloak.show();
		},
		
		//---------------------------------------------------------------------
		//  .newHour() is called when a user clicks an hour value.
		//  It changes the date and updates the text field.
		//---------------------------------------------------------------------
		
		newHour: function( event )
		{
		    var h;
		    var t;
		    var elem = $(event.target);
		    if ( elem.hasClass("AnyTime-out-btn") )
		    	return;
		    if ( ! this.twelveHr )
		      h = Number(elem.text());
		    else
		    {
		      var str = elem.text();
		      t = str.indexOf('a');
		      if ( t < 0 )
		      {
		        t = Number(str.substr(0,str.indexOf('p')));
		        h = ( (t==12) ? 12 : (t+12) );
		      }
		      else
		      {
		        t = Number(str.substr(0,t));
		        h = ( (t==12) ? 0 : t );
		      }
		    }
		    t = new Date(this.time.getTime());
		    t.setHours(h);
		    this.set(t);
		    this.upd(elem);
		    
		}, // .newHour()
		
		//---------------------------------------------------------------------
		//  .newOffset() is called when a user clicks the UTC offset (timezone)
		//  (or +/- button) to shift the year.  It changes the date and updates
		//  the text field.
		//---------------------------------------------------------------------
		
		newOffset: function( event )
		{
		    if ( event.target == this.oSel[0] )
			    this.askOffset(event);
		    else
		    {
		      this.upd(this.oCur);
		    }
		},
		
		//---------------------------------------------------------------------
		//  .newOPos() is called internally whenever a user clicks an offset
		//  selection value.  It changes the date and updates the text field.
		//---------------------------------------------------------------------
		
		newOPos: function( event )
		{
		    var elem = $(event.target);
            this.offMin = elem[0].AnyTime_offMin;
            this.offSI = elem[0].AnyTime_offSI;
		    var t = new Date(this.time.getTime());
		    this.set(t);
		    this.updODiv(elem);
		
		}, // .newOPos()
		
		//---------------------------------------------------------------------
		//  .newYear() is called when a user clicks a year (or one of the
		//	"arrows") to shift the year.  It changes the date and updates the
		//	text field.
		//---------------------------------------------------------------------
		
		newYear: function( event )
		{
		    var elem = $(event.target);
		    if ( elem.hasClass("AnyTime-out-btn") )
		    	return;
		    var txt = elem.text();
		    if ( ( txt == '<' ) || ( txt == '&lt;' ) )
		      this.askYear(event);
		    else if ( ( txt == '>' ) || ( txt == '&gt;' ) )
		      this.askYear(event);
		    else
		    {
		      var t = new Date(this.time.getTime());
		      t.setFullYear(Number(txt));
		      this.set(t);
		      this.upd(this.yCur);
		    }
		},
		
		//---------------------------------------------------------------------
		//  .newYPos() is called internally whenever a user clicks a year
		//  selection value.  It changes the date and updates the text field.
		//---------------------------------------------------------------------
		
		newYPos: function( event )
		{
		    var elem = $(event.target);
		    if ( elem.hasClass("AnyTime-out-btn") )
		    	return;
		    
		    var era = 1;
		    var year = this.time.getFullYear();
		    if ( year < 0 )
		    {
		      era = (-1);
		      year = 0 - year;
		    }
		    year = AnyTime.pad( year, 4 );
		    if ( elem.hasClass('AnyTime-mil-btn') )
		      year = elem.html() + year.substring(1,4);
		    else if ( elem.hasClass('AnyTime-cent-btn') )
		      year = year.substring(0,1) + elem.html() + year.substring(2,4);
		    else if ( elem.hasClass('AnyTime-dec-btn') )
		      year = year.substring(0,2) + elem.html() + year.substring(3,4);
		    else
		      year = year.substring(0,3) + elem.html();
		    if ( year == '0000' )
		      year = 1;
		    var t = new Date(this.time.getTime());
		    t.setFullYear( era * year );
		    this.set(t);
		    this.updYDiv(elem);
		
		}, // .newYPos()
		
		//---------------------------------------------------------------------
		//  .onReady() initializes the picker after the page has loaded and,
		//  if IE6, after the iframe has been created.
		//---------------------------------------------------------------------
		
		onReady: function()
		{
			this.lostFocus = true;
			if ( ! this.pop )
				this.upd(null);
			else 
			{
				if ( this.div.parent() != document.body )
					this.div.appendTo( document.body );
			}
		},
		
		//---------------------------------------------------------------------
		//  .pos() positions the picker, such as when it is displayed or
		//	when the window is resized.
		//---------------------------------------------------------------------
		
		pos: function(event) // note: event is ignored but this is a handler
		{
		    if ( this.pop )
		    {
		      var off = this.inp.offset();
		      var bodyWidth = $(document.body).outerWidth(true);
		      var pickerWidth = this.div.outerWidth(true);
		      var left = off.left;
		      if ( left + pickerWidth > bodyWidth - 20 )
		        left = bodyWidth - ( pickerWidth + 20 );
		      var top = off.top - this.div.outerHeight(true);
		      if ( top < 0 )
		        top = off.top + this.inp.outerHeight(true);
		      this.div.css( { top: String(top)+'px', left: String(left<0?0:left)+'px' } );
		    }
		
		    var wOff = this.div.offset();

		    if ( this.oDiv && this.oDiv.is(":visible") )
		    {
		      var oOff = this.oLab.offset();
		      if ( this.div.css('position') == 'absolute' )
		      {
		    	  oOff.top -= wOff.top;
		          oOff.left = oOff.left - wOff.left;
		    	  wOff = { top: 0, left: 0 };
		      }
		      var oW = this.oDiv.AnyTime_width(true);
		      var wW = this.div.AnyTime_width(true);
		      if ( oOff.left + oW > wOff.left + wW )
		      {
		    	  oOff.left = (wOff.left+wW)-oW;
		    	  if ( oOff.left < 2 )
		    		  oOff.left = 2;
		      }

		      var oH = this.oDiv.AnyTime_height(true);
		      var wH = this.div.AnyTime_height(true);
		      oOff.top += this.oLab.AnyTime_height(true);
		      if ( oOff.top + oH > wOff.top + wH )
		    	  oOff.top = oOff.top - oH;
		      if ( oOff.top < wOff.top )
		    	  oOff.top = wOff.top;

		      this.oDiv.css( { top: oOff.top+'px', left: oOff.left+'px' } ) ;
		    }

		    else if ( this.yDiv && this.yDiv.is(":visible") )
		    {
		      var yOff = this.yLab.offset();
		      if ( this.div.css('position') == 'absolute' )
		      {
		    	  yOff.top -= wOff.top;
		          yOff.left = yOff.left - wOff.left;
		    	  wOff = { top: 0, left: 0 };
		      }
		      yOff.left += ( (this.yLab.outerWidth(true)-this.yDiv.outerWidth(true)) / 2 );
		      this.yDiv.css( { top: yOff.top+'px', left: yOff.left+'px' } ) ;
		    }

		    if ( this.cloak )
			  this.cloak.css( { 
		      	top: wOff.top+'px',
		      	left: wOff.left+'px',
		      	height: String(this.div.outerHeight(true)-2)+'px',
		    	width: String(this.div.outerWidth(!$.browser.safari)-2)+'px'
		    	} );
		
		}, // .pos()
		
		//---------------------------------------------------------------------
		//  .set() changes the current time.  It returns true if the new
		//	time is within the allowed range (if any).
		//---------------------------------------------------------------------
		
		set: function(newTime)
		{
		    var t = newTime.getTime();
		    if ( this.earliest && ( t < this.earliest ) )
		      this.time = new Date(this.earliest);
		    else if ( this.latest && ( t > this.latest ) )
		      this.time = new Date(this.latest);
		    else
		      this.time = newTime;
		},
		  
		//---------------------------------------------------------------------
		//  .showPkr() displays the picker and sets the focus psuedo-
		//	element. The current value in the input field is used to initialize
		//	the picker.
		//---------------------------------------------------------------------
		
		showPkr: function(event)
		{
			try
		    {
		      this.time = this.conv.parse(this.inp.val());
		      this.offMin = this.conv.getUtcParseOffsetCaptured();
		      this.offSI = this.conv.getUtcParseOffsetSubIndex();
		    }
		    catch ( e )
		    {
		      this.time = new Date();
		    }
		    this.set(this.time);
		    this.upd(null);
		    
		    fBtn = null;
		    var cb = '.AnyTime-cur-btn:first';
		    if ( this.dDoM )
		    	fBtn = this.dDoM.find(cb);
			else if ( this.yCur )
				fBtn = this.yCur;
			else if ( this.dMo )
				fBtn = this.dMo.find(cb);
			else if ( this.dH )
				fBtn = this.dH.find(cb);
			else if ( this.dM )
				fBtn = this.dM.find(cb);
			else if ( this.dS )
				fBtn = this.dS.find(cb);
		
		    this.setFocus(fBtn);
		    this.pos(event);
		
			//  IE6 doesn't float popups over <select> elements unless an
		    //	<iframe> is inserted between them!  So after the picker is
		    //	made visible, move the <iframe> behind it.
		    
		    if ( this.pop && __iframe )
		        setTimeout(
		        	function()
					{
						var pos = _this.div.offset();
						__iframe.css( {
						    height: String(_this.div.outerHeight(true)) + 'px',
						    left: String(pos.left) + 'px',
						    position: 'absolute',
						    top: String(pos.top) + 'px',
						    width: String(_this.div.outerWidth(true)) + 'px'
						    } );
						__iframe.show();
					}, 300 );
		
		}, // .showPkr()
		
		//---------------------------------------------------------------------
		//  .upd() updates the picker's appearance.  It is called after
		//	most events to make the picker reflect the currently-selected
		//	values. fBtn is the psuedo-button to be given focus.
		//---------------------------------------------------------------------
		
		upd: function(fBtn)
		{
		    var cmpLo = new Date(this.time.getTime());
		    cmpLo.setMonth(0,1);
		    cmpLo.setHours(0,0,0,0);
		    var cmpHi = new Date(this.time.getTime());
		    cmpHi.setMonth(11,31);
		    cmpHi.setHours(23,59,59,999);

		    //  Update year.
		
		    var current = this.time.getFullYear();
		    if ( this.earliest && this.yPast )
		    {
				  cmpHi.setYear(current-2);
			      if ( cmpHi.getTime() < this.earliest )
			    	  this.yPast.addClass('AnyTime-out-btn ui-state-disabled');
			      else
			    	  this.yPast.removeClass('AnyTime-out-btn ui-state-disabled');
		    }
		    if ( this.yPrior )
		    {
		      this.yPrior.text(AnyTime.pad((current==1)?(-1):(current-1),4));
		      if ( this.earliest )
		      {
				  cmpHi.setYear(current-1);
			      if ( cmpHi.getTime() < this.earliest )
			    	  this.yPrior.addClass('AnyTime-out-btn ui-state-disabled');
			      else
			    	  this.yPrior.removeClass('AnyTime-out-btn ui-state-disabled');
		      }
		    }
		    if ( this.yCur )
		      this.yCur.text(AnyTime.pad(current,4));
		    if ( this.yNext )
		    {
		      this.yNext.text(AnyTime.pad((current==-1)?1:(current+1),4));
		      if ( this.latest )
		      {
			      cmpLo.setYear(current+1);
			      if ( cmpLo.getTime() > this.latest )
			    	  this.yNext.addClass('AnyTime-out-btn ui-state-disabled');
			      else
			    	  this.yNext.removeClass('AnyTime-out-btn ui-state-disabled');
		      }
		    }
		    if ( this.latest && this.yAhead )
		    {
				  cmpLo.setYear(current+2);
			      if ( cmpLo.getTime() > this.latest )
			    	  this.yAhead.addClass('AnyTime-out-btn ui-state-disabled');
			      else
			    	  this.yAhead.removeClass('AnyTime-out-btn ui-state-disabled');
		    }
		    
		    //  Update month.
		
		    cmpLo.setFullYear( this.time.getFullYear() );
		    cmpHi.setFullYear( this.time.getFullYear() );
		    var i = 0;
		    current = this.time.getMonth();
		    $('#'+this.id+' .AnyTime-mon-btn').each(
		      function()
		      {
		    	cmpLo.setMonth(i);
				cmpHi.setDate(1);
		    	cmpHi.setMonth(i+1);
				cmpHi.setDate(0);
		        $(this).AnyTime_current( i == current,
		        		((!_this.earliest)||(cmpHi.getTime()>=_this.earliest)) &&
		        		((!_this.latest)||(cmpLo.getTime()<=_this.latest)) );
		        i++;
		      } );
		
		    //  Update days.
		
		    cmpLo.setMonth( this.time.getMonth() );
		    cmpHi.setMonth( this.time.getMonth(), 1 );
		    current = this.time.getDate();
		    var currentMonth = this.time.getMonth();
		    var dow1 = cmpLo.getDay();
		    if ( this.fDOW > dow1 )
		      dow1 += 7;
		    var wom = 0, dow=0;
		    $('#'+this.id+' .AnyTime-wk').each(
		      function()
		      {
		        dow = _this.fDOW;
		        $(this).children().each(
		          function()
		          {
		        	  if ( dow - _this.fDOW < 7 )
		        	  {
		        		  var td = $(this);
				          if ( ((wom==0)&&(dow<dow1)) || (cmpLo.getMonth()!=currentMonth) )
				          {
				            td.html('&#160;');
				            td.removeClass('AnyTime-dom-btn-filled AnyTime-cur-btn ui-state-default ui-state-highlight');
				            td.addClass('AnyTime-dom-btn-empty');
				            if ( wom ) // not first week
				            {
				            	if ( ( cmpLo.getDate() == 1 ) && ( dow != 0 ) )
				            		td.addClass('AnyTime-dom-btn-empty-after-filled');
				            	else
				            		td.removeClass('AnyTime-dom-btn-empty-after-filled');
				            	if ( cmpLo.getDate() <= 7 )
				            		td.addClass('AnyTime-dom-btn-empty-below-filled');
				            	else
				            		td.removeClass('AnyTime-dom-btn-empty-below-filled');
				                cmpLo.setDate(cmpLo.getDate()+1);
				                cmpHi.setDate(cmpHi.getDate()+1);
				            }
				            else // first week
				            {
				            	td.addClass('AnyTime-dom-btn-empty-above-filled');
				            	if ( dow == dow1 - 1 )
				            		td.addClass('AnyTime-dom-btn-empty-before-filled');
				            	else
				            		td.removeClass('AnyTime-dom-btn-empty-before-filled');
				            }
				            td.addClass('ui-state-default ui-state-disabled');
				          }
				          else
				          {
				        	i = cmpLo.getDate();
				            td.text(i);
				            td.removeClass('AnyTime-dom-btn-empty AnyTime-dom-btn-empty-above-filled AnyTime-dom-btn-empty-before-filled '+
				            				'AnyTime-dom-btn-empty-after-filled AnyTime-dom-btn-empty-below-filled ' +
				            				'ui-state-default ui-state-disabled');
				            td.addClass('AnyTime-dom-btn-filled ui-state-default');
				            td.AnyTime_current( i == current,
					        		((!_this.earliest)||(cmpHi.getTime()>=_this.earliest)) &&
					        		((!_this.latest)||(cmpLo.getTime()<=_this.latest)) );
				            cmpLo.setDate(i+1);
				            cmpHi.setDate(i+1);
				          }
		        	  }
		              dow++;
		          } );
		          wom++;
		      } );
		
		    //  Update hour.
		
		    cmpLo.setMonth( this.time.getMonth(), this.time.getDate() );
		    cmpHi.setMonth( this.time.getMonth(), this.time.getDate() );
		    var not12 = ! this.twelveHr;
		    var h = this.time.getHours();
		    $('#'+this.id+' .AnyTime-hr-btn').each(
		      function()
		      {
		    	var html = this.innerHTML;
		    	var i;
		    	if ( not12 )
		    		i = Number(html);
		    	else
		    	{
			    	i = Number(html.substring(0,html.length-2) );
		    		if ( html.charAt(html.length-2) == 'a' )
		    		{
		    			if ( i == 12 )
		    				i = 0;
		    		}
		    		else if ( i < 12 )
		    			i += 12;
		    	}
                cmpLo.setHours(i);
                cmpHi.setHours(i);
		        $(this).AnyTime_current( h == i,   
		        	((!_this.earliest)||(cmpHi.getTime()>=_this.earliest)) &&
		        		((!_this.latest)||(cmpLo.getTime()<=_this.latest)) );
		        cmpLo.setHours( cmpLo.getHours()+1 );
		      } );
		
		    //  Update minute.
		
		    cmpLo.setMonth( this.time.getMonth(), this.time.getDate() );
		    cmpLo.setHours( this.time.getHours(), 0 );
		    cmpHi.setMonth( this.time.getMonth(), this.time.getDate() );
		    cmpHi.setHours( this.time.getHours(), 9 );
		    var mi = this.time.getMinutes();
		    var tens = String(Math.floor(mi/10));
		    var ones = String(mi % 10);
		    $('#'+this.id+' .AnyTime-min-ten-btn:not(.AnyTime-min-ten-btn-empty)').each(
		      function()
		      {
		        $(this).AnyTime_current( this.innerHTML == tens,
		        		((!_this.earliest)||(cmpHi.getTime()>=_this.earliest)) &&
		        		((!_this.latest)||(cmpLo.getTime()<=_this.latest)) );
		        cmpLo.setMinutes( cmpLo.getMinutes()+10 );
		        cmpHi.setMinutes( cmpHi.getMinutes()+10 );
		      } );
		    cmpLo.setHours( this.time.getHours(), Math.floor(this.time.getMinutes()/10)*10 );
		    cmpHi.setHours( this.time.getHours(), Math.floor(this.time.getMinutes()/10)*10 );
		    $('#'+this.id+' .AnyTime-min-one-btn:not(.AnyTime-min-one-btn-empty)').each(
		      function()
		      {
		        $(this).AnyTime_current( this.innerHTML == ones,
		        		((!_this.earliest)||(cmpHi.getTime()>=_this.earliest)) &&
		        		((!_this.latest)||(cmpLo.getTime()<=_this.latest)) );
		        cmpLo.setMinutes( cmpLo.getMinutes()+1 );
		        cmpHi.setMinutes( cmpHi.getMinutes()+1 );
		      } );
		
		    //  Update second.
		
		    cmpLo.setMonth( this.time.getMonth(), this.time.getDate() );
		    cmpLo.setHours( this.time.getHours(), this.time.getMinutes(), 0 );
		    cmpHi.setMonth( this.time.getMonth(), this.time.getDate() );
		    cmpHi.setHours( this.time.getHours(), this.time.getMinutes(), 9 );
		    var mi = this.time.getSeconds();
		    var tens = String(Math.floor(mi/10));
		    var ones = String(mi % 10);
		    $('#'+this.id+' .AnyTime-sec-ten-btn:not(.AnyTime-sec-ten-btn-empty)').each(
		      function()
		      {
		        $(this).AnyTime_current( this.innerHTML == tens,
		        		((!_this.earliest)||(cmpHi.getTime()>=_this.earliest)) &&
		        		((!_this.latest)||(cmpLo.getTime()<=_this.latest)) );
		        cmpLo.setSeconds( cmpLo.getSeconds()+10 );
		        cmpHi.setSeconds( cmpHi.getSeconds()+10 );
		      } );
		    cmpLo.setMinutes( this.time.getMinutes(), Math.floor(this.time.getSeconds()/10)*10 );
		    cmpHi.setMinutes( this.time.getMinutes(), Math.floor(this.time.getSeconds()/10)*10 );
		    $('#'+this.id+' .AnyTime-sec-one-btn:not(.AnyTime-sec-one-btn-empty)').each(
		      function()
		      {
		        $(this).AnyTime_current( this.innerHTML == ones,
		        		((!_this.earliest)||(cmpHi.getTime()>=_this.earliest)) &&
		        		((!_this.latest)||(cmpLo.getTime()<=_this.latest)) );
		        cmpLo.setSeconds( cmpLo.getSeconds()+1 );
		        cmpHi.setSeconds( cmpHi.getSeconds()+1 );
		      } );

		    //  Update offset (time zone).

		    if ( this.oConv )
		    {
			    this.oConv.setUtcFormatOffsetAlleged(this.offMin);
			    this.oConv.setUtcFormatOffsetSubIndex(this.offSI);
			    var tzs = this.oConv.format(this.time);
			    this.oCur.html( tzs );
		    }

		    //	Set the focus element, then size the picker according to its
		    //	components, show the changes, and invoke Ajax if desired.
		    
		    if ( fBtn )
		    	this.setFocus(fBtn);
		
            this.conv.setUtcFormatOffsetAlleged(this.offMin);
		    this.conv.setUtcFormatOffsetSubIndex(this.offSI);
		    this.inp.val(this.conv.format(this.time)).change();
		    this.div.show();
		
		    var d, totH = 0, totW = 0, dYW = 0, dMoW = 0, dDoMW = 0;
		    if ( this.dY )
		    {
		    	totW = dYW = this.dY.outerWidth(true);
				totH = this.yLab.AnyTime_height(true) + this.dY.AnyTime_height(true);
		    }
		    if ( this.dMo )
		    {
		    	dMoW = this.dMo.outerWidth(true);
		    	if ( dMoW > totW )
		    		totW = dMoW;
		    	totH += this.hMo.AnyTime_height(true) + this.dMo.AnyTime_height(true);
		    }
		    if ( this.dDoM )
		    {
			    dDoMW = this.dDoM.outerWidth(true);
			    if ( dDoMW > totW )
			    	totW = dDoMW;
			    if ( __msie6 || __msie7 )
			    {
			    	if ( dMoW > dDoMW )
			    		this.dDoM.css('width',String(dMoW)+'px');
			    	else if ( dYW > dDoMW )
			    		this.dDoM.css('width',String(dYW)+'px');
			    }
			    totH += this.hDoM.AnyTime_height(true) + this.dDoM.AnyTime_height(true);
		    }
		    if ( this.dD )
		    {
		    	this.dD.css( { width:String(totW)+'px', height:String(totH)+'px' } );
		        totW += this.dMinW;
		        totH += this.dMinH;
		    }
		
		    var w = 0, h = 0, timeH = 0, timeW = 0;
		    if ( this.dH )
		    {
		    	w = this.dH.outerWidth(true);
		    	timeW += w + 1;
		    	h = this.dH.AnyTime_height(true);
		    	if ( h > timeH )
		    		timeH = h;
		    }
		    if ( this.dM )
		    {
		        w = this.dM.outerWidth(true);
		        timeW += w + 1;
		        h = this.dM.AnyTime_height(true);
		        if ( h > timeH )
		        	timeH = h;
		    }
		    if ( this.dS )
		    {
		        w = this.dS.outerWidth(true);
		        timeW += w + 1;
		        h = this.dS.AnyTime_height(true);
		        if ( h > timeH )
		        	timeH = h;
		    }
		    if ( this.dO )
		    {
		        w = this.oMinW;
		        if ( timeW < w+1 )
		        	timeW = w+1;
		        timeH += this.dO.AnyTime_height(true);
		    }
		    if ( this.dT )
		    {
		    	this.dT.css( { width:String(timeW)+'px', height:String(timeH)+'px' } );
		    	timeW += this.tMinW + 1;
		        timeH += this.tMinH;
		    	totW += timeW;
		    	if ( timeH > totH )
		    		totH = timeH;
			    if ( this.dO ) // stretch offset button if possible
			    {
			    	var dOW = this.dT.width()-(this.oMinW+1);
			    	this.dO.css({width:String(dOW)+"px"});
			    	this.oCur.css({width:String(dOW-(this.oListMinW+4))+"px"});
			    }
		    }
		    	
		    this.dB.css({height:String(totH)+'px',width:String(totW)+'px'});
		
		    totH += this.bMinH;
		    totW += this.bMinW;
		    totH += this.hTitle.AnyTime_height(true) + this.wMinH;
		    totW += this.wMinW;
		    if ( this.hTitle.outerWidth(true) > totW )
		        totW = this.hTitle.outerWidth(true); // IE quirk
		    this.div.css({height:String(totH)+'px',width:String(totW)+'px'});
		
		    if ( ! this.pop )
		      this.ajax();
		
		}, // .upd()
		
		//---------------------------------------------------------------------
		//  .updODiv() updates the UTC offset selector's appearance.  It is
		//	called after most events to make the picker reflect the currently-
		//	selected values. fBtn is the psuedo-button to be given focus.
		//---------------------------------------------------------------------
		
		updODiv: function(fBtn)
		{
            var cur, matched = false, def = null;
		    this.oDiv.find('.AnyTime-off-off-btn').each(
		      function()
		      {
		    	  if ( this.AnyTime_offMin == _this.offMin )
		    	  {
		    		  if ( this.AnyTime_offSI == _this.offSI )
		    			  $(this).AnyTime_current(matched=true,true);
		    		  else
		    	      {
		    			  $(this).AnyTime_current(false,true);
		    			  if ( def == null )
			    			  def = $(this);
		    	      }
		    	  }
		    	  else
	    			  $(this).AnyTime_current(false,true);
		      } );
		    if ( ( ! matched ) && ( def != null ) )
		    	def.AnyTime_current(true,true);
		
		    //  Show change
		
            this.conv.setUtcFormatOffsetAlleged(this.offMin);
            this.conv.setUtcFormatOffsetSubIndex(this.offSI);
		    this.inp.val(this.conv.format(this.time)).change();
		    this.upd(fBtn);
		
		}, // .updODiv()

		//---------------------------------------------------------------------
		//  .updYDiv() updates the year selector's appearance.  It is
		//	called after most events to make the picker reflect the currently-
		//	selected values. fBtn is the psuedo-button to be given focus.
		//---------------------------------------------------------------------
		
		updYDiv: function(fBtn)
		{
		    var i, legal;
			var era = 1;
		    var yearValue = this.time.getFullYear();
		    if ( yearValue < 0 )
		    {
		      era = (-1);
		      yearValue = 0 - yearValue;
		    }
		    yearValue = AnyTime.pad( yearValue, 4 );
		    var eY = _this.earliest && new Date(_this.earliest).getFullYear();
		    var lY = _this.latest && new Date(_this.latest).getFullYear();
	    
		    i = 0;
		    this.yDiv.find('.AnyTime-mil-btn').each(
		      function()
		      {
		    	legal = ( ((!_this.earliest)||(era*(i+(era<0?0:999))>=eY)) && ((!_this.latest)||(era*(i+(era>0?0:999))<=lY)) );
		        $(this).AnyTime_current( this.innerHTML == yearValue.substring(0,1), legal );
		        i += 1000;
		      } );

		    i = (Math.floor(yearValue/1000)*1000);
		    this.yDiv.find('.AnyTime-cent-btn').each(
		      function()
		      {
			    	legal = ( ((!_this.earliest)||(era*(i+(era<0?0:99))>=eY)) && ((!_this.latest)||(era*(i+(era>0?0:99))<=lY)) );
		        $(this).AnyTime_current( this.innerHTML == yearValue.substring(1,2), legal );
		        i += 100;
		      } );

		    i = (Math.floor(yearValue/100)*100);
		    this.yDiv.find('.AnyTime-dec-btn').each(
		      function()
		      {
			    	legal = ( ((!_this.earliest)||(era*(i+(era<0?0:9))>=eY)) && ((!_this.latest)||(era*(i+(era>0?0:9))<=lY)) );
		        $(this).AnyTime_current( this.innerHTML == yearValue.substring(2,3), legal );
		        i += 10;
		      } );

		    i = (Math.floor(yearValue/10)*10);
		    this.yDiv.find('.AnyTime-yr-btn').each(
		      function()
		      {
			    legal = ( ((!_this.earliest)||(era*i>=eY)) && ((!_this.latest)||(era*i<=lY)) );
		        $(this).AnyTime_current( this.innerHTML == yearValue.substring(3), legal );
		        i += 1;
	          } );
		    
		    this.yDiv.find('.AnyTime-bce-btn').each(
		      function()
		      {
		    	  $(this).AnyTime_current( era < 0, (!_this.earliest) || ( _this.earliest < 0 ) );
		      } );
		    this.yDiv.find('.AnyTime-ce-btn').each(
		      function()
		      {
		    	$(this).AnyTime_current( era > 0, (!_this.latest) || ( _this.latest > 0 ) );
		      } );
		
		    //  Show change
		
            this.conv.setUtcFormatOffsetAlleged(this.offMin);
            this.conv.setUtcFormatOffsetSubIndex(this.offSI);
		    this.inp.val(this.conv.format(this.time)).change();
		    this.upd(fBtn);
		
		} // .updYDiv()

	}; // __pickers[id] = ...
	__pickers[id].initialize(id);
	
} // AnyTime.picker = 

})(jQuery); // function($)...


