global_all_item_list_allow = true;

var timerIdLogin
var timerIdSettings
var timerIdLoginRecent
var timerIdSettingsRecent

var timerIdSaveColor

var zIndex = 20

$(document).ready(function() {
	
	item_name_txt="item description"
	their_name_txt="their name or email"
	
	$("#new_item_name").val(item_name_txt)
	$("#new_friend_email_or_name").val(their_name_txt)
	
	$("#new_item_name").click(function() {
		if (item_name_txt == this.value) this.value="";
	})
	
	$("#new_friend_email_or_name").click(function() {
		if (their_name_txt == this.value) this.value="";
	})
	
	$("#new_item_name").blur(function() {
		if (this.value=="") this.value = item_name_txt
	})
	
	$("#new_friend_email_or_name").blur(function() {
		if (this.value=="") this.value = their_name_txt
	})
	
	$("#new_friend_email_or_name").autocomplete("/ajax/user_search")
	
	$("#login_submit").attr("disabled", "true")
	
	initItemSubmitHTMLEvents()
	
	initSettingsAnimation()
	initSettingsHTML()
	verifySettingsForm()
	initMyItemsHTMLEvents($("#my_ious > .iou"))
	initEveryonesHTMLEvents($("#all_ious > .iou"))
	initLoginHTML()
	initHelpHTMLEvents()
	
	$("#settings_popup").css("opacity", 0)
	$("#login_popup").css("opacity", 0)
	$("#help_popup").css("opacity", 0)
	
	$("#initial_screen_off img.toggle").click(function() {
		$("#initial_screen").toggle()
		$("#initial_screen_off").toggle()
		$("#initial_screen_on").toggle()
	})
	
	$("#initial_screen_on img.toggle").click(function() {
		$("#initial_screen").toggle()
		$("#initial_screen_off").toggle()
		$("#initial_screen_on").toggle()
	})	
	
	setInterval("poll()",500)
	
})

function initItemSubmitHTMLEvents() {
	
	$("#item_whose_debt").click(function() {
		
		if ($("#item_whose_debt").text().indexOf("you") != -1) {
			this.firstChild.data = "they"
		} else {
			this.firstChild.data ="you"
		}
	})
	
	$("#add_form form").submit(function () { 
	
		var your_debt = $("#item_whose_debt").text().indexOf("you") != -1 ? true : false;
	
		var first_div = $("#my_ious > .iou:first")
		if (first_div.length > 0) {
			var high_id = first_div.attr("item_id")
			var before = true
		} else {
			first_div = $("#my_ious > h2")
			var before = false
		}
	
		if (item_name_txt == $('#new_item_name').val() || their_name_txt == $('#new_friend_email_or_name').val()) return false

		var postParam = { item_name: $('#new_item_name').val(),
						  your_debt: your_debt }
						
		if ($('#new_friend_user_id').val().length > 0 && $('#new_friend_select_value').val() == $('#new_friend_email_or_name').val()) {
			postParam.user_id = $('#new_friend_user_id').val()
		} else {
			postParam.friend_email_or_name = $('#new_friend_email_or_name').val()
		}
		
		if (high_id) {
			postParam.high_id = high_id
		} else {
			postParam.high_id = 0
		}
		
		buttCtx = $(this)
		
		var spinner = $(".spinner", buttCtx)
		spinner.css("display", "inline")
		
		$(".info", buttCtx).hide()
	
		$.post('/ajax/item_create', postParam, function(data, textStatus) {
			
			$("#initial_screen, #initial_screen_empty_items, #initial_screen_on").hide("fast")
			$("#initial_screen_off").show()
			
			var iouNode = $(data).css("display", "none")
	
			if (before) first_div.before(iouNode);
			else first_div.after(iouNode);
			
			iouNode.fadeIn("fast")		
		
			initMyItemsHTMLEvents(iouNode)
			
			item_id = parseInt(iouNode.attr("item_id"))
		
		 	if (!iouNode.attr("privacy")) {
				var insertedAllIou = false
				var allIou = $("#all_ious > div.iou").filter(function() {
					if (insertedAllIou) return
					var jqXThis = $(this)
					if (parseInt(jqXThis.attr("item_id")) < item_id) {
						var tmp = $(data).css("display", "none")
						jqXThis.before(tmp)
						tmp.fadeIn("fast")
						insertedAllIou = true
					}
				})
			}
			
			var notif_partial = $(".notified_partial", iouNode)
			
			var isAnon = $(".anon", notif_partial)
			
			if (isAnon.length == 0) {
			
				notif_partial.html("Notifying recipient: <span></span>")
				
				var animate = {} 
				animate.timerId = setTimeout(function(){animateDots(animate, $("span", notif_partial))}, 500);
				
				$.post('/ajax/notify', { item_id: item_id }, function(data, textStatus) {
					
					clearTimeout(animate.timerId)
					notif_partial.empty()
					notif_partial.append(data);
					
				})
				
			}
		
			if (!global_user_exists) {
			
				$.get('/ajax/user_identified', { }, function(data, textStatus) {
				
					$("#settings_partial").append(data);
					
					initSettingsHTML()
					verifySettingsForm()
					initHelpHTMLEvents()
					
					$("#settings_button_area").css( {display: "inline" })
					
					setTimeout(function() {
						$("#settings_button").click()
						timerIdSettings = setTimeout(function() {
							settingsButtonToggle()
						}, 3000)
					}, 1000)
					
				})
			}
		
			global_user_exists = true
		
			$("#new_item_name").val(item_name_txt)
			$("#new_friend_email_or_name").val(their_name_txt)
			
			spinner.css("display", "none")
			$(".info", buttCtx).css("display", "inline")
			
	    })
	
		return false;
	
	})
}

function initEveryonesItemsHTML() {
	
	var first_div = $("#all_ious > .iou:first")
	if (first_div.length > 0) {
		var high_id = first_div.attr("item_id")
		var before = true
	} else {
		first_div = $("#all_ious > h2")
		var before = false
	}

	$.post('/ajax/item_list', {
		everyones: ""
		}, function(data, textStatus) {
	
			if (before) first_div.before(data);
			else first_div.after(data);
	    })
}

function initMyItemsHTML() {
	
	var first_div = $("#my_ious > .iou:first")
	if (first_div.length > 0) {
		var high_id = first_div.attr("item_id")
		var before = true
	} else {
		first_div = $("#my_ious > h2")
		var before = false
	}

	$.post('/ajax/item_list', {
		my: ""
	}, function(data, textStatus) {
	
			if (before) first_div.before(data);
			else first_div.after(data);
			
			initMyItemsHTMLEvents($("#my_ious > .iou"))	
	    })
}

function settingsButtonToggle(parentNode) {
	
	if (timerIdSettings != null) clearTimeout(timerIdSettings)
	
	var dlg = $("#settings_popup")
	
	if (dlg.css("display") != "none" || (typeof parentNode == "undefined" || parentNode == null)) {
		
		hideDialog(dlg)
	} else {
		setPopupPosition(parentNode, dlg)
		showDialog(dlg)
		loginButtonToggle()	
		helpButtonToggle()	
	}
	
	timerIdSettingsRecent = setTimeout(function() { timerIdSettingsRecent = null }, 1500)
}

function initSettingsAnimation(unbind) {
	
	if (unbind) {
		
		$("#settings_button").unbind('click')
		$("#settings_button").unbind('mouseover')
		$("#settings_button").unbind('mouseout')
		$("#settings_popup").unbind('mouseover')
		$("#settings_popup").unbind('mouseout')
		
	} else {
	
		$("#settings_button").click(function() {
			if (timerIdSettingsRecent == null) { 
				settingsButtonToggle(this)
				clearTimeout(timerIdSettingsRecent)
				timerIdSettingsRecent = null
			}
		})
	
		$("#settings_button").mouseover(function() {
			if ($("#settings_popup").css("display") == "none") settingsButtonToggle(this)
		})
	
		$("#settings_button").mouseout(function() {
			timerIdSettings = setTimeout(function() {
				settingsButtonToggle()
			}, 1000)		
		})
	
		$("#settings_popup").mouseover(function() {
			if (timerIdSettings != null) clearTimeout(timerIdSettings)
			timerIdSettings = null
		})
	
		$("#settings_popup").mouseout(function() {
			timerIdSettings = setTimeout(function() {
				settingsButtonToggle()
			}, 800)
		})
	}
}

function initSettingsHTML() {
	
	$("#user_email").keypress(function(e) {
		if (onEmailEdit(e, this.value) && validatePasswords()) 
			$("#user_update_submit").removeAttr("disabled");
		else
			$("#user_update_submit").attr("disabled", "true");
	})
	
	$("#user_email").keyup(function(e) {
		if (onEmailEdit(null, this.value) && validatePasswords()) 
			$("#user_update_submit").removeAttr("disabled");
		else
			$("#user_update_submit").attr("disabled", "true");
	})	
	
	function validatePasswords() {

		if ($("#user_password_current").length > 0) {
			return ($("#user_password_new").val() == "" && $("#user_password_current").val() == "")
			 	|| onPasswordEdit(null, $("#user_password_new").val()) && onPasswordEdit(e, $("#user_password_current").val())
		} else if ($("#user_password").length > 0) {
			return onPasswordEdit(null, $("#user_password").val()) && $("#user_password").val() == $("#user_password_verify").val()
		} else {
			return true
		}
	}
	
	// user edit
	$("#user_password_current").keypress(function(e) {
		if (onPasswordEdit(e, this.value) && onEmailEdit(null, $("#user_email").val()) && onPasswordEdit(e, $("#user_password_new").val()))
			$("#user_update_submit").removeAttr("disabled");
		else
			$("#user_update_submit").attr("disabled", "true");
	})
	
	$("#user_password_new").keypress(function(e) {
		if (onPasswordEdit(e, this.value) && onEmailEdit(null, $("#user_email").val()) && onPasswordEdit(e, $("#user_password_current").val()))
			$("#user_update_submit").removeAttr("disabled");
		else
			$("#user_update_submit").attr("disabled", "true");
	})
	
	// user new
	$("#user_password").keypress(function(e) {
		if (onPasswordEdit(e, this.value, $("#user_password_verify").val()) && onEmailEdit(null, $("#user_email").val()))
			$("#user_update_submit").removeAttr("disabled");
		else
			$("#user_update_submit").attr("disabled", "true");
	})
	
	$("#user_password_verify").keypress(function(e) {
		if (onPasswordEdit(e, this.value, $("#user_password").val()) && onEmailEdit(null, $("#user_email").val()))
			$("#user_update_submit").removeAttr("disabled");
		else
			$("#user_update_submit").attr("disabled", "true");
	})
	
	$("#login_fb_submit_1").click(function() {
		location.href = "/facebook/auth"
	})
	
	$("#install_fb_submit_1").click(function() {
		location.href = facebook_base_what_io_url
	})
		
	$("#user_update_submit").click(function() {
		
		var buttCtx = this
		$(".spinner", buttCtx.parentNode).css("display", "inline")
		
		var postParams = { user_name: $('#user_name').val(),
							user_email: $('#user_email').val() }
							
		if ($('#user_password_current').val() != "" && $('#user_password').val() != "") {
			postParams.user_password_current = $('#user_password_current').val()
			postParams.user_password = $('#user_password').val()			
		}
		
		$.post('/ajax/user_identified_edit', postParams, function(data, textStatus) {
				
			$(".spinner", buttCtx.parentNode).css("display", "none")
				
			var jsData = eval("("+data+")")

			if (jsData.status) {
				
				$.get('/ajax/user_identified_login', { }, function(data, textStatus) {

						$("#login_partial").empty();
						$("#login_partial").append(data);
						initLoginHTML();
						$(".status", buttCtx.parentNode).css("display", "inline")		
						setTimeout(function() {
							settingsButtonToggle(null)
							$(".status", buttCtx.parentNode).css("display", "none")
						}, 1500)
				})
				
				global_user_loggedin = true
	
			} else {
			
				if (jsData.reason) {
					$(".msg", buttCtx.parentNode).text(jsData.reason)
				} else {
					$(".msg", buttCtx.parentNode).text("Try again!")
				}
				$(".msg", buttCtx.parentNode).css("display", "inline")					
			
				setTimeout(function() {
					$(".msg", buttCtx.parentNode).fadeOut("fast")
				}, 2000)
			}		
	    })
	})
}

function initEveryonesHTMLEvents(domIOUs) {
	
	domIOUs.each(function() {
		
		initCertificateHTMLEvents(this)
	})
}

function initMyItemsHTMLEvents(domIOUs) {
	
	domIOUs.each(function() {
		
		$(".fulfill_button", this).mouseover(function() {
			
			var iouNode = $(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode)
			if (iouNode.attr("fulfilled")) {
				$(this).removeClass("fulfill_button_on")
				$(this).addClass("fulfill_button_on_over")
			} else {
				$(this).removeClass("fulfill_button_off")
				$(this).addClass("fulfill_button_off_over")				
			}
		})
		
		$(".fulfill_button", this).mouseout(function() {
			var iouNode = $(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode)
			paintFulfilledButton(iouNode)
		})
		
		function paintFulfilledButton(iouNode) {
			
			if (iouNode.attr("fulfilled")) {
				$(".fulfill_button", iouNode).removeClass("fulfill_button_on_over") 
				$(".fulfill_button", iouNode).removeClass("fulfill_button_off_over") 
				$(".fulfill_button", iouNode).addClass("fulfill_button_on")
			} else {
				$(".fulfill_button", iouNode).removeClass("fulfill_button_on_over") 
				$(".fulfill_button", iouNode).removeClass("fulfill_button_off_over")			
				$(".fulfill_button", iouNode).addClass("fulfill_button_off")
			}
		}
				
		$(".fulfill_button", this).click(function() {
			
			var iouNode = $(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode)

            $.post('/ajax/item_fulfill_toggle', {
               list_id: iouNode.attr("item_id")
		    }, function(data, textStatus) {

				var jsData = eval("("+data+")")
				
				var allIou = $("#all_ious > div.iou[@item_id='" +iouNode.attr("item_id") + "']")
				
				if (jsData.fulfilled) {
					
					iouNode.attr("fulfilled", "true")
					paintFulfilledButton(iouNode)
									
					$("blockquote", iouNode).addClass("fulfilled")
					
					if (allIou.length > 0) {
						$("blockquote", allIou).addClass("fulfilled")
					}					
				}
				else { 
					
					iouNode.removeAttr("fulfilled")
					paintFulfilledButton(iouNode)
					
					$("blockquote", iouNode).removeClass("fulfilled")
					
					if (allIou.length > 0) {
						$("blockquote", allIou).removeClass("fulfilled")
					}								
				}
				
				if (iouNode.attr("active_facebook") && !iouNode.attr("privacy") && global_user_loggedin) {
					syncWithFacebook();
				}
		    })
		})
		
		$(".editable .name", this).click(function() {
			
			var jqThis = $(this)
			var iouNode = $(this.parentNode.parentNode.parentNode.parentNode)
			
			if ($("blockquote", iouNode).hasClass("fulfilled")) return;
			
			var inputFld = $("<input type=\"text\" orig_value=\"" + jqThis.text() + "\" value=\"" + jqThis.text() +"\">")
			jqThis.before(inputFld)
			jqThis.hide()
			inputFld.focus().keydown(function(e) {
				switch(e.keyCode) {
					case 13: // return
						inputFld.blur()
						break;
					default:
						break;
				}
			})
			
			inputFld.focus()
			
			inputFld.blur(function() {
				
				if (inputFld.val() != inputFld.attr("orig_value")) {

		            $.post('/ajax/item_update', {
		               list_id: iouNode.attr("item_id"),
					   item_name: inputFld.val()
				    }, function(data, textStatus) {
									
						var jsData = eval("(" + data + ")")
						jqThis.text(inputFld.val())
						jqThis.show()
						inputFld.remove()
						
						$(".date", iouNode).text("Edited: minutes ago")
						
						var allIou = $("#all_ious > div.iou[@item_id='" +iouNode.attr("item_id") + "']")
						if (allIou.length > 0) {
							allIou.before(iouNode.clone())
							allIou.remove()
						}	
						
						if (iouNode.attr("active_facebook") && !iouNode.attr("privacy") && global_user_loggedin) {
							syncWithFacebook();
						}
				    })
					
				} else {
					jqThis.text(inputFld.val())
					jqThis.show()
					inputFld.remove()
				}	
			})
		})
		
		$(".editable .user", this).click(function() {
			
			var jqThis = $(this)
			var iouNode = $(this.parentNode.parentNode.parentNode.parentNode)
			
			if ($("blockquote", iouNode).hasClass("fulfilled")) return;
			
			// var inputFld = $(".user input")
			// if (inputFld.length == 0)
			inputFld = $("<input type=\"text\" orig_value=\"" + jqThis.text() + "\" value=\"" + jqThis.text() +"\">")
			
			$(inputFld).autocomplete("/ajax/user_search", { inputClass: "ac_inputgray",
															resultsClass: "ac_resultsgray",
															loadingClass: "ac_loadinggray",
															overClass: "ac_overgray" })
			
			jqThis.before(inputFld)
			jqThis.hide()
			// inputFld.focus().keydown(function(e) {
			// 	switch(e.keyCode) {
			// 		case 13: // return
			// 			//inputFld.blur()
			// 			break;
			// 		default:
			// 			break;
			// 	}
			// })
			
			inputFld.focus()
			
			$('#new_friend_user_id').val("")
			
			$(inputFld).blur(function() {
				
				postParam = { list_id: iouNode.attr("item_id") }
				
				if (inputFld.attr("user_id")) {
					postParam.item_user_id = inputFld.attr("user_id")
				} else {
					postParam.item_user_name = inputFld.val()
				}
				
				if (inputFld.val() != inputFld.attr("orig_value") || inputFld.attr("user_id") ) {
		            $.post('/ajax/item_update', postParam, function(data, textStatus) {
				
						var jsData = eval("(" + data + ")")			
						jqThis.text(inputFld.val())
						jqThis.show()
						inputFld.remove()
						
						$(".date", iouNode).text("Edited: minutes ago")
						
						var allIou = $("#all_ious > div.iou[@item_id='" +iouNode.attr("item_id") + "']")
						if (allIou.length > 0) {
							allIou.before(iouNode.clone())
							allIou.remove()
						}
						
						if (iouNode.attr("active_facebook") && !iouNode.attr("privacy") && global_user_loggedin) {
							syncWithFacebook();
						}						
				    })
				} else {
					jqThis.text(inputFld.val())
					jqThis.show()
					inputFld.remove()
				}
			})
		})
		
		$(".privacy_button", this).mouseover(function() {
			
			var iouNode = $(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode)
			if (iouNode.attr("privacy")) {
				
				$(this).removeClass("privacy_button_off")
				$(this).addClass("privacy_button_off_over")
			} else {
				$(this).removeClass("privacy_button_on")
				$(this).addClass("privacy_button_on_over")				
			}
		})
		
		$(".privacy_button", this).mouseout(function() {
			var iouNode = $(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode)
			paintPrivacyButton(iouNode)
		})
		
		function paintPrivacyButton(iouNode) {
			
			if (iouNode.attr("privacy")) {
				
				$(".privacy_button", iouNode).removeClass("privacy_button_on_over") 
				$(".privacy_button", iouNode).removeClass("privacy_button_off_over")			
				$(".privacy_button", iouNode).addClass("privacy_button_off")
			} else {
				$(".privacy_button", iouNode).removeClass("privacy_button_on_over") 
				$(".privacy_button", iouNode).removeClass("privacy_button_off_over") 
				$(".privacy_button", iouNode).addClass("privacy_button_on")
			}
		}		
		
		$(".privacy_button", this).click(function() {
			
			//alert("click")
			
			var iouNode = $(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode)
			
			if (iouNode.attr("privacy")) {
				iouNode.removeAttr("privacy")
				var checkedVal = false
			} else {
				iouNode.attr("privacy", "true")
				var checkedVal = true
			}
			
			var itemId = parseInt(iouNode.attr("item_id"))
			
			$.post('/ajax/item_update', {
	           list_id: itemId,
			   item_privacy: checkedVal
			}, function (data, textStatus) {
				
				var allIou = $("#all_ious > div.iou[@item_id='" +iouNode.attr("item_id") + "']")
				
				function copyIouNode(jqXThis, iouNode) {
					var tmp = iouNode.clone()
					tmp.css("display", "none")
					jqXThis.before(tmp)
					tmp.show("fast")
					insertedAllIou = true
					tmp.next().before(iouNode.next().clone())
				}
				
				paintPrivacyButton(iouNode);
				
				if (allIou.length > 0 && checkedVal) {
					
					allIou.hide("fast", function() { allIou.remove(); })
					
				} else if (!checkedVal){
					
					var insertedAllIou = false
					allIou = $("#all_ious > div.iou").filter(function() {
						if (insertedAllIou) return
						var jqXThis = $(this)
						if (parseInt(jqXThis.attr("item_id")) < itemId) {
							insertedAllIou = true
							copyIouNode(jqXThis, iouNode)
						}
					})
				}
				
				if (global_user_loggedin) {
					if (checkedVal) 
						syncWithFacebook(0)
					else 
						syncWithFacebook(0, itemId)
				}
			})
		})
		
		$(".delete_button", this).mouseover(function() {
			
			$(this).removeClass("delete_button_on")
			$(this).addClass("delete_button_on_over")				
		})
		
		$(".delete_button", this).mouseout(function() {
		
			$(this).removeClass("delete_button_on_over")
			$(this).addClass("delete_button_on")
		})
			
		$(".delete_button", this).click(function() {
			
			var iouNode = $(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode)

			if (confirm("Are you sure?")) {
	            $.post('/ajax/item_delete', {
	               list_id: iouNode.attr("item_id")
			    }, function(data, textStatus) {

					var allIou = $("#all_ious > div.iou[@item_id='" +iouNode.attr("item_id") + "']")
					iouNode.remove()
					allIou.remove()
					
					if (iouNode.attr("active_facebook") && !iouNode.attr("privacy") && global_user_loggedin) {
						syncWithFacebook(0)
					}
			    })
			}
		})	
		
		function saveColor(color, iouNode) {
			
			itemId = iouNode.attr("item_id")
			
			if (typeof timerIdSaveColor != "undefined" && timerIdSaveColor != null) clearTimeout(timerIdSaveColor)
			timerIdSaveColor = setTimeout(function() {
				$.post('/ajax/item_update', {
		           list_id: itemId,
				   color: color
				}, function(data, textStatus) {
					timerIdSaveColor = null
					if (iouNode.attr("active_facebook") && !iouNode.attr("privacy") && global_user_loggedin) {
						syncWithFacebook(0)
					}
				})
			}, 1000);
		}
		
		$(".colors.blue", this).click(function() {
			var iouNode = $(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode)
			var jqThis = $(".notepink,.notegreen,.noteyellow", iouNode)
			jqThis.removeClass("notepink")
			jqThis.removeClass("notegreen")
			jqThis.removeClass("noteyellow")			
			jqThis.addClass("noteblue")
			
			var iouBNode = $(".bottompink,.bottomgreen,.bottomyellow", iouNode)
			iouBNode.removeClass("bottompink")
			iouBNode.removeClass("bottomgreen")
			iouBNode.removeClass("bottomyellow")			
			iouBNode.addClass("bottomblue")	
			
			saveColor("blue", iouNode)
			
			var allIou = $("#all_ious > div.iou[@item_id='" +iouNode.attr("item_id") + "']")
			if (allIou.length > 0 && allIou.css("display") == "block") {
				allIou.before(iouNode.clone())
				allIou.remove()
			}
			
		})
		
		$(".colors.pink", this).click(function() {
			var iouNode = $(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode)
			var jqThis = $(".noteblue,.notegreen,.noteyellow", iouNode)
			jqThis.removeClass("noteblue")
			jqThis.removeClass("notegreen")	
			jqThis.removeClass("noteyellow")
			jqThis.addClass("notepink")
			
			var iouBNode = $(".bottomblue,.bottomgreen,.bottomyellow", iouNode)
			iouBNode.removeClass("bottomblue")
			iouBNode.removeClass("bottomgreen")
			iouBNode.removeClass("bottomyellow")
			iouBNode.addClass("bottompink")
			
			saveColor("pink", iouNode)
			
			var allIou = $("#all_ious > div.iou[@item_id='" +iouNode.attr("item_id") + "']")
			if (allIou.length > 0 && allIou.css("display") == "block") {
				allIou.before(iouNode.clone())
				allIou.remove()
			}			
		})
		
		$(".colors.green", this).click(function() {
			var iouNode = $(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode)
			var jqThis = $(".notepink,.noteblue,.noteyellow", iouNode)
			jqThis.removeClass("notepink")
			jqThis.removeClass("noteblue")
			jqThis.removeClass("noteyellow")			
			jqThis.addClass("notegreen")
			
			var iouBNode = $(".bottompink,.bottomblue,.bottomyellow", iouNode)
			iouBNode.removeClass("bottompink")
			iouBNode.removeClass("bottomblue")
			iouBNode.removeClass("bottomyellow")			
			iouBNode.addClass("bottomgreen")
			
			saveColor("green", iouNode)
			
			var allIou = $("#all_ious > div.iou[@item_id='" +iouNode.attr("item_id") + "']")
			if (allIou.length > 0 && allIou.css("display") == "block") {
				allIou.before(iouNode.clone())
				allIou.remove()
			}			
		})
		
		$(".colors.yellow", this).click(function() {
			var iouNode = $(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode)
			var jqThis = $(".notepink,.noteblue,.notegreen", iouNode)
			jqThis.removeClass("notepink")
			jqThis.removeClass("noteblue")
			jqThis.removeClass("notegreen")
			jqThis.addClass("noteyellow")
			
			var iouBNode = $(".bottompink,.bottomblue,.bottomgreen", iouNode)
			iouBNode.removeClass("bottompink")
			iouBNode.removeClass("bottomblue")
			iouBNode.removeClass("bottomgreen")
			iouBNode.addClass("bottomyellow")
			
			saveColor("yellow", iouNode)
			
			var allIou = $("#all_ious > div.iou[@item_id='" +iouNode.attr("item_id") + "']")
			if (allIou.length > 0 && allIou.css("display") == "block") {
				allIou.before(iouNode.clone())
				allIou.remove()
			}			
		})
		
		initCertificateHTMLEvents(this)
	})
}

function initCertificateHTMLEvents(iou) {
	 
	$(".certificate_button", iou).mouseover(function() {

	        $(this).removeClass("certificate_button_on")
	        $(this).addClass("certificate_button_on_over")
	})

	$(".certificate_button", iou).mouseout(function() {

	        $(this).removeClass("certificate_button_on_over")
	        $(this).addClass("certificate_button_on")
	})

	$(".certificate_button", iou).click(function() {

	        var iouNode = $(iou.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode)

	       location.href = "/main/pdf/" + $(iou).attr("item_id")
	})
}

function loginButtonToggle(parentNode) {
	
	if (timerIdLogin != null) clearTimeout(timerIdLogin)
	
	var dlg = $("#login_popup")
	
	if (dlg.css("display") != "none" || typeof parentNode == "undefined"){
		
		hideDialog(dlg)			
	} else {
	    // alert("parentNode.l" + parentNode.offsetLeft + " parentNode.t" + parentNode.offsetTop)
		setPopupPosition(parentNode, dlg)
		showDialog(dlg)
		settingsButtonToggle()
		helpButtonToggle()
	}
	
	timerIdLoginRecent = setTimeout(function() { timerIdLoginRecent = null }, 1500)
}

function initLoginHTML() {
	
	$("#login_button").click(function() {
		if (timerIdLoginRecent == null) { 
			loginButtonToggle(this)
			clearTimeout(timerIdLoginRecent)
			timerIdLoginRecent = null
		}
	})
	
	$("#login_button").mouseover(function() {
		if ($("#login_popup").css("display") == "none") loginButtonToggle(this);
	})
	
	$("#login_button").mouseout(function() {
		timerIdLogin = setTimeout(function() {
			loginButtonToggle()
		}, 600)		
	})

	$("#login_popup").mouseover(function() {
		if (timerIdLogin != null) clearTimeout(timerIdLogin)
		timerIdLogin = null
	})
	
	$("#login_popup").mouseout(function() {
		timerIdLogin = setTimeout(function() {
			loginButtonToggle()
		}, 800)
	})
	
	$("#logout_button").click(function() {
		
		$.post('/ajax/user_identified_logout', {}
		  , function(data, textStatus) {
			location.href = "/"
		})
	})
	
	$("#login_fb_submit_2").click(function() {
		top.location.href = "/facebook/auth"
	})
	
	$("#install_fb_submit_2").click(function() {
		top.location.href = facebook_base_what_io_url
	})	
	
	$("#login_user_email").keypress(function(e) {
		if (onEmailEdit(e, this.value) && onPasswordEdit(null, $("#login_user_password").val())) 
			$("#login_submit").removeAttr("disabled");
		else
			$("#login_submit").attr("disabled", "true");
	})
	
	$("#login_user_password").keypress(function(e) {
		if (onPasswordEdit(e, this.value) && onEmailEdit(null, $("#login_user_email").val()))
			$("#login_submit").removeAttr("disabled");
		else
			$("#login_submit").attr("disabled", "true");
	})
	
	var logged_in_user_name = $("#logged_in_user_name")
	while (logged_in_user_name.length > 0 && logged_in_user_name[0].offsetWidth > 192) {
		var name = $("#logged_in_user_name").text()
		$("#logged_in_user_name").text(name.substring(0, name.length - 6) + "...")
	}
	
	$("#login_create_account").click(function() {
		$("#settings_button").click()
	})
	
	$("#login_submit").click(function() {
				
		var buttCtx = this
		
		$(".spinner", buttCtx.parentNode).css("display", "inline")
		
		$.post('/ajax/user_identified_authenticate', {
			user_email: $('#login_user_email').val(),
			user_password: $('#login_user_password').val()
	    }, function(data, textStatus) {
	
			$(".info", buttCtx.parentNode).css("display", "inline")
			
			var jsData = eval("("+data+")")
			
			if (jsData.status) {
				
				$("#initial_screen, #initial_screen_empty_items").hide("fast")
				
				$("#my_ious > .iou").empty()
				initMyItemsHTML()
			
				$.get('/ajax/user_identified_login', { }, function(data, textStatus) {
				
					$("#login_partial").empty()
					$("#login_partial").append(data)
					initLoginHTML()
					
				})
			
				$.get('/ajax/user_identified', { }, function(data, textStatus) {
				
					$("#settings_partial").empty()
					$("#settings_partial").append(data)
					initSettingsHTML()
					
					$("#settings_button_area").css("display", "inline")
					
					verifySettingsForm()
				})
				
				loginButtonToggle()
				
				global_user_loggedin = true
				
			} else {
				
				$(".msg", buttCtx.parentNode).text("Incorrect login!")
				$(".msg", buttCtx.parentNode).css("display", "inline")
				
				setTimeout(function() {
					$(".msg", buttCtx.parentNode).fadeOut("fast")
				}, 2000)
				
			}
		})
	})
}

function verifySettingsForm() {
	
	if ($("#user_password_current").length > 0 && isRFC822ValidEmail($("#user_email").val())) {
		$("#user_update_submit").removeAttr("disabled");
	} else {
		$("#user_update_submit").attr("disabled", "true");
	}
}

function poll(){
	
	var x,y;
	if (self.pageYOffset) { // all except Explorer 
		x = self.pageXOffset;
		y = self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
		x = document.documentElement.scrollLeft;
		y = document.documentElement.scrollTop;
	}
	else if (document.body) { // all other Explorers
		x = document.body.scrollLeft;
		y = document.body.scrollTop;
	}

	if (getRemainingScroll() <= 1 && y != 0) {
		
		if (global_all_item_list_allow) {
			var last_div = $("#all_ious > .iou:last")
			if (last_div.length > 0 && ((typeof global_all_item_list_safe == 'undefined') || global_all_item_list_safe)) {
				var low_id = last_div.attr("item_id")
				
				global_item_list_safe = false;
	
				$.post('/ajax/item_list', {
					down_using_id: low_id
					}, function(data, textStatus) {
						if (data.length > 0) {
							jqData = $(data)
							initEveryonesHTMLEvents(jqData)
							last_div.next().after(jqData);
							if (last_div.next().next().length > 0) {
								var pos = findPos(last_div.next().next()[0])
								last_div.next().after("<div class=\"page_crease\" style=\"top: " + (pos[1] - 12) + "px; left: 0px\"></div>")
							}
						}
						
						global_all_item_list_safe = true;
				    })
			}
			
			var my_last_div = $("#my_ious > .iou:last")
			if (my_last_div.length > 0 && ((typeof global_my_item_list_safe == 'undefined') || global_my_item_list_safe)) {
				var low_id = my_last_div.attr("item_id")
	
				$.post('/ajax/item_list' + get_params, {
					down_and_self_using_id: low_id
					}, function(data, textStatus) {
						if (data.length > 0) {
							jqData = $(data)
							initMyItemsHTMLEvents(jqData)
							my_last_div.next().after(jqData);
							if (my_last_div.next().next().length > 0) {
								var pos = findPos(my_last_div.next().next()[0])
							}
						}
						
						global_my_item_list_safe = true;
				    })
			}
		}
		
		global_all_item_list_allow = false;	
				
	} else {
		global_all_item_list_allow = true;
	}
	return true;
}

//http://rosskendall.com/files/rfc822validemail.js.txt
function isRFC822ValidEmail(sEmail) {

  var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
  var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
  var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
  var sQuotedPair = '\\x5c[\\x00-\\x7f]';
  var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
  var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';
  var sDomain_ref = sAtom;
  var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
  var sWord = '(' + sAtom + '|' + sQuotedString + ')';
  var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
  var sLocalPart = sWord + '(\\x2e' + sWord + ')*';
  var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec
  var sValidEmail = '^' + sAddrSpec + '$'; // as whole string
  
  var reValidEmail = new RegExp(sValidEmail);
  
  if (reValidEmail.test(sEmail)) {
    return true;
  }
  
  return false;
}

function onEmailEdit(e, currentVal)  {

	if (e == null) return isRFC822ValidEmail(currentVal)
	var keys = getKeyChar(e);
	if (isDeleteCharacter(keys[0], e)) {
		return isRFC822ValidEmail(currentVal.substring(0, currentVal.length-1))
	} else if (isControlCharacter(keys[0], e)) {
	 	return (isRFC822ValidEmail(currentVal))
	} else {
		return (isRFC822ValidEmail(currentVal + keys[1]))
	}
}

function onPasswordEdit(e, currentVal, compareValue) {

	if (currentVal == null) {
		return false
	} else if (compareValue == null) {
		if (e == null) return currentVal.length >= 5
		var keys = getKeyChar(e);
		if (isDeleteCharacter(keys[0], e)) {
			return (currentVal.length - 1 >= 5)
		} else if (isControlCharacter(keys[0], e)) {
		 	return (currentVal.length >= 5)
		} else {
			return (currentVal.length >= 4)
		}
	} else {
		var keys = getKeyChar(e);
		if (isDeleteCharacter(keys[0], e)) {
			return currentVal.substring(0, currentVal.length-1) == compareValue
		} else if (isControlCharacter(keys[0], e)) {
		 	return currentVal == compareValue 
		} else {
			return currentVal + keys[1] == compareValue
		}
	}
}

function getKeyChar(e) {
	var key = !e || (!e.which && e.which != 0) ? window.event.keyCode : e.which;
	return [key, String.fromCharCode(key)];
}

function isControlCharacter(key, e) {
	return e.metaKey || e.ctrlKey || key == 63234 || key == 63235 || key == 63272 || key == 9 || key == 8 || key == 0;
}

function isDeleteCharacter(key, e) {
	return key == 8 || key == 46;
}