styles/client.js Script Source View


/// <reference path="jquery.mobile-1.0b1.min.js" />
/// <reference path="jquery-1.6.4.min.js" />
/// <reference path="json2.min.js" />

if($.browser.msie)window.location.href = "/eth/ie_not_supported.html";

//var WSROOT = "http://www.mytaglist.com/";
var WSROOT = "/";
//var WSROOT = "http://192.168.1.100/";
var VALID_EMAIL_REGEX = "^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\@[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$";
//var notificationRun = false;
var notificationQueue = new Array();
var taglist_cache = {};
var tagEventStates = { 0: ["Disarmed", "c"], 1: ["Armed", "a"], 2: ["Moved", "e"], 3: ["Opened", "e"], 4: ["Closed", "a"] };
var autoRetry = true;
var lastOffline = false;
var beep_looping = false;
function isMobile(){
	if(window.NC)return true;
	var ua = navigator.userAgent.toLowerCase();
	if (ua.indexOf("iphone") != -1 || ua.indexOf("ipod") != -1 || ua.indexOf("ipad") != -1 || ua.indexOf("android") != -1 || ua.indexOf("blackberry") != -1) {
		return true;
	}
	return false;
}
var device_transition = isMobile() ? "none" : "fade";
String.prototype.format = function () {
	var formatted = this;
	for (var i = 0; i < arguments.length; i++) {
		var regexp = new RegExp('\\{' + i + '\\}', 'gi');
		formatted = formatted.replace(regexp, arguments[i]);
	}
	return formatted;
};

function undeleteChoice(btn){
	var oldhtml = show_finding(btn, "Loading...");
	$.ajax({
		complete: function () { restore_finding(btn, oldhtml); },
		url: WSROOT + "ethClient.asmx/GetDeletedTagList",
		success: function(retval){
			if(retval.d.length==0){
				popup("No tag to undelete", btn);
			}else{
				$("#undeleteChoice").children().remove();
				var html = '<select id="_undeleteChoice" onchange="undelete($(this)); return false" data-native-menu="false"><option value="choose-one" data-placeholder="true">Choose a tag to undelete...</option>';
				for (var i = 0; i < retval.d.length; i++)
					html+=('<option value="{0}">{1} :{2}</option>').format(retval.d[i].slaveId, retval.d[i].name, UserFriendlyTimeSpanString( retval.d[i].deleted));
				html+="</select>";
				$(html).appendTo("#undeleteChoice").selectmenu().selectmenu("open");
			}
		}
	});
}

function NC_onPause() {
	if(getNextUpdate_xhr){
		getNextUpdate_xhr.abort();
		getNextUpdate_xhr=null;
	}
}
function NC_onResume() {
	//alert("NC_onResume");
	createTagList();
	//$("#indexPage").trigger("pageshow");
	/*if(!getNextUpdate_xhr){
		getNextUpdate();
	}*/
}
function popupMN(title, detail) {
	$("<div class='ui-error-debug ui-body-e'><h1>" + title + "</h1>" + detail + "</div>")
						.appendTo($.mobile.pageContainer)
						.delay((title.length+detail.length)*80).fadeOut(400, function () { $(this).remove(); });
//						.click(function () { $(this).fadeOut(400, function () { $(this).remove(); }) });
}
function MN_onMessage(payload) {
	popupMN(payload.alert, payload.detail);
	if(!getNextUpdate_xhr){
		var id = payload.slaveid;
		$.ajax({
			url: WSROOT + "ethClient.asmx/GetTagForSlaveId",
			data: "{slaveid: " + id + "}",
			success: function (retval, textStatus) {
				updateTag(retval.d);
			},
			error: function (xhr, textStatus, exception) {
				popup_error(xhr, btn);
			}
		});
	}
	//$("#indexPage").trigger("pagehide"); $("#indexPage").trigger("pageshow");
	//navigator.notification.vibrate(1200);
	//navigator.notification.beep(1);
}
var loginEmail;
function MN_onRegistered(event)			   // oldToken, newToken, type, phoneName
{
	event.phoneName = prompt("Please pick a name for this device: ", event.phoneName);
	//alert("MN_onRegistered " + JSON.stringify(event));
	$.ajax({
		url: WSROOT + "ethMobileNotifications.asmx/UpdateToken",
		data: JSON.stringify(event),
		success: function (retval) {
			window.NC.storeMNToken(loginEmail, event.newToken);
			alert("This device '" + event.phoneName + "' can now receive tag notifications.");
		},
		error: function (xhr, textStatus, exception) {
			popup_error(xhr, $.mobile.pageContainer);
			//var err = eval("(" + xhr.responseText + ")");
			//alert(err.Message + " " + err.StackTrace);
		}
	});
}
function MN_onUnregistered(event)      // oldToken, type
{
	//alert("MN_onRegistered " + JSON.stringify(event));
	$.ajax({
		url: WSROOT + "ethMobileNotifications.asmx/RemoveToken",
		data: JSON.stringify(event),
		error: function (xhr, textStatus, exception) {
			popupDebug(xhr, $.mobile.pageContainer);
		}
	});
	window.NC.clearMNToken(loginEmail);
}
function beep_once(vibrate_only) {
	if (window.NC) {
		window.NC.vibrate(1200);
		if (!vibrate_only)
			window.NC.beep();
		if (beep_looping) setTimeout(function () { beep_once(vibrate_only); }, 2000);
	} else {
		audioElement.volume = vibrate_only ? 0 : 1;
		audioElement.play();
	}
	return true;
}

//document.addEventListener("deviceready", function () { alert("deviceready"); }, false);
//document.addEventListener("pause", function () { alert("pause"); }, false);
//document.addEventListener("resume", function () { $("#indexPage").trigger("pagehide"); $("#indexPage").trigger("pageshow"); }, false);
//document.addEventListener("offline", function () { alert("offline"); }, false);
//document.addEventListener("online", function () { alert("online"); }, false);

$.fn.resetRoundedEdges = function () {
	if (this.length) {
		var set = this.children(":jqmData(role='collapsible')");
		set.find("a:eq(0), .ui-btn-inline:eq(0)").removeClass("ui-corner-tl ui-corner-tr ui-corner-bl ui-corner-br");
		set.jqmData("collapsible-last", false);

		set.first().find("a").eq(0).addClass("ui-corner-tl");
		set.first().find(".ui-btn-inline").eq(0).addClass("ui-corner-tr");
		set.last().find(".ui-btn-inline").eq(0).addClass("ui-corner-br");
		set.last().find("a").eq(0).addClass("ui-corner-bl");
		set.last().jqmData("collapsible-last", true);
	}
}

function popup(msg, btn) {
    if(btn!=null)
	    if (btn.offset().top < 0) btn = btn.parent();
	$("<div class='ui-error ui-overlay-shadow ui-body-e ui-corner-all'><h1>" + msg + "</h1></div>")
						.css(btn!=null?{ "top": btn.offset().top + 20  }:{"top": "40%", "left": "15%", "position": "fixed"})
						.appendTo($.mobile.pageContainer)
						.delay(2000).fadeOut(400, function () { $(this).remove(); });
//	.click(function () { $(this).fadeOut(400, function () { $(this).remove(); }) });
}

function popupDebug(xhr, btn) {
	if (btn.offset().top < 0) btn = btn.parent();
	var err = eval("(" + xhr.responseText + ")");
	$("<div class='ui-error-debug ui-body-e ui-corner-all'><h1>" + err.Message + "</h1>" + err.StackTrace + "</div>")
						.css({ "top": btn.offset().top + 75	 })
						.appendTo($.mobile.pageContainer)
						.click(function () { $(this).fadeOut(400, function () { $(this).remove(); }) });
}

function show_finding(btn, finding_label) {
	try {
		btn.button('disable');
	} catch (e) {
	try {
		btn.selectmenu('disable');
	} catch (e) {
		btn.attr('disabled', true);
	}
	}
	var btn_text = btn.parent().find(".ui-btn-text");
	var oldhtml = btn_text.html();
	btn_text[0].innerHTML = finding_label || "Finding...";
	var btn_icon = btn.parent().find(".ui-icon");
	btn_icon.data("old_class", btn_icon[0].className);
	//btn_icon[0].className = "ui-icon-gear";
	btn_icon.addClass("ui-icon-gear spin");
	return oldhtml;
}
function restore_finding(btn, oldhtml) {
	try {
		btn.button('enable');
	} catch (e) {
		try {
			btn.selectmenu('enable');
		} catch (e) {
			btn.attr('disabled', false);
		}
	}
	btn.parent().find(".ui-btn-text")[0].innerHTML = oldhtml;
	//btn.parent().find(".ui-icon").removeClass("ui-icon-gear spin");
	var btn_icon = btn.parent().find(".ui-icon");
	btn_icon[0].className = btn_icon.data("old_class");
}

$.ajaxSetup({
	type: "POST",
	contentType: "application/json; charset=utf-8",
	data: "{}",
	dataType: "json",
	xhrFields: {
		withCredentials: true
	},
	error: function (xhr, textStatus, exception) {
		try {
			popupDebug(xhr, $.mobile.pageContainer);
		} catch (e) {
			//popup("Unknown Error: " + xhr, $.mobile.pageContainer);
		}
	}
});

function popup_error(xhr, btn) {
	try {
		if(xhr.responseText.length>0){
			var err = eval("(" + xhr.responseText + ")");
			popup(err.Message, btn);
		}
		else if(xhr.statusText == "error"){
			popup("Network connection issue.", btn);
		}
		else{
			popup(xhr.statusText, btn);
		}
	} catch (e) {
		popup("Unknown Error: " + xhr, btn);
	}
}

function armit(btn, id) {
	var oldhtml = show_finding(btn);
	$.ajax({
		url: WSROOT + "ethClient.asmx/Arm",
		data: "{id: '" + id + "', door_mode_set_closed: true}",
		success: function (retval, textStatus) {
			updateTag(retval.d);
		},
		complete: function () { restore_finding(btn, oldhtml); },
		error: function (xhr, textStatus, exception) {
			popup_error(xhr, btn);
		}
	});
}
function disarmit(btn, id) {
	var oldhtml = show_finding(btn);
	$.ajax({
		url: WSROOT + "ethClient.asmx/Disarm",
		data: "{id: '" + id + "'}",
		success: function (retval, textStatus) {
			updateTag(retval.d);
		},
		complete: function () {
			restore_finding(btn, oldhtml);
		},
		error: function (xhr, textStatus, exception) {
			popup_error(xhr, btn);
		}
	});
}
function all_tag_action(btn, action) {
	var oldhtml = show_finding(btn);

	$.ajax({
		url: WSROOT + "ethClient.asmx/" + action,
		data: "{autoRetry: " + autoRetry + "}",
		complete: function () {
			restore_finding(btn, oldhtml);
		},
		success: function (retval, textStatus) {
			for (var i = 0; i < retval.d.length; i++) {
				updateTag(retval.d[i]);
			}
		},
		error: function (xhr, textStatus, exception) {
			popup_error(xhr, btn);
		}
	});
}

function UserFriendlyTimeSpanString(filetime) {
	var lastComm = new Date((filetime / 10000) - 11644473600000);
	var now = new Date();
	var diff = now.getTime() - lastComm.getTime() + serverTime2LocalTime;
	var daysDifference = Math.floor(diff / 1000 / 60 / 60 / 24);
	if (daysDifference >= 1) return daysDifference + " days ago";
	var hoursDifference = Math.floor(diff / 1000 / 60 / 60);
	if (hoursDifference >= 1) return hoursDifference + " hours ago";
	var minDifference = Math.floor(diff / 1000 / 60);
	if (minDifference >= 1) return minDifference + " min ago";
	else return Math.round(diff / 1000) + " sec ago";
}
function dBmToBars(dBm) {
	if (dBm <= -110) return 0;
	else if (dBm < -97) return 1;
	else if (dBm < -87) return 2;
	else if (dBm < -77) return 3;
	else if (dBm < -67) return 4;
	else return 5;
}
function setTheme(btn, theme) {
	btn.attr("data-theme", theme).removeClass("ui-btn-up-a ui-btn-up-b ui-btn-up-c ui-btn-up-d ui-btn-up-e ui-btn-hover-a ui-btn-hover-b ui-btn-hover-c ui-btn-hover-d ui-btn-hover-e")
			.addClass("ui-btn-up-" + theme);
}
/*function updateTagList(btn) {
	var oldhtml = show_finding(btn.children(0));
	$.ajax({
		url: WSROOT + "ethClient.asmx/UpdateAll",
		data: "{autoRetry: false}",
		success: function (retval, textStatus) {
			for (var i = 0; i < retval.d.length; i++) {
				updateTag(retval.d[i]);
			}
			restore_finding(btn.children(0), oldhtml);
		},
		error: function (xhr, textStatus, exception) {
			restore_finding(btn.children(0), oldhtml);
			popup_error(xhr, btn);
		}
	});
}
*/
function resetit(btn, id) {
	var oldhtml = show_finding(btn);
	$.ajax({
		url: WSROOT + "ethClient.asmx/ResetTag",
		data: "{id: '" + id + "'}",
		success: function (retval, textStatus) {
			updateTag(retval.d);
		},
		complete: function () { restore_finding(btn, oldhtml); },
		error: function (xhr, textStatus, exception) {
			popup_error(xhr, btn);
		}
	});
}
function reqPostback(btn, id) {
	var oldhtml = show_finding(btn);
	$.ajax({
		url: WSROOT + "ethClient.asmx/RequestImmediatePostback",
		data: "{id: '" + id + "'}",
		success: function (retval, textStatus) {
			updateTag(retval.d);
		},
		complete: function () { restore_finding(btn, oldhtml); },
		error: function (xhr, textStatus, exception) {
			popup_error(xhr, btn);
			//popupDebug(xhr, btn);
		}
	});
}
/*function togglelight(btn, id) {
	var oldhtml = show_finding(btn);
	if (oldhtml == "Light On") {
		$.ajax({
			url: WSROOT + "ethClient.asmx/LightOn",
			//data: "{id: '" + id + "', option: '" + $("input[@name=beep-top-" + id + "]:checked").val()  + "'}",
			data: "{id: '" + id + "', flash: false}",
			success: function (retval, textStatus) {
				restore_finding(btn, oldhtml);
				updateTag(retval.d);
			},
			error: function (xhr, textStatus, exception) {
				restore_finding(btn, "Light On");
				popup_error(xhr, btn);
			}
		});
	} else {
		$.ajax({
			url: WSROOT + "ethClient.asmx/LightOff",
			data: "{id: '" + id + "'}",
			success: function (retval, textStatus) {
				restore_finding(btn, "Light On");
				updateTag(retval.d);
			},
			error: function (xhr, textStatus, exception) {
				restore_finding(btn, oldhtml);
				popup_error(xhr, btn);
			}
		});
	}
}
*/

function togglebeep(btn, id) {
	var oldhtml = show_finding(btn);
	if (oldhtml == "Beep") {
		$.ajax({
			url: WSROOT + "ethClient.asmx/Beep",
			//data: "{id: '" + id + "', option: '" + $("input[@name=beep-top-" + id + "]:checked").val()  + "'}",
			data: "{id: '" + id + "', beepDuration: '" + $("#beep-opt-" + id).val() + "'}",
			success: function (retval, textStatus) {
				restore_finding(btn, oldhtml);
				updateTag(retval.d);
			},
			error: function (xhr, textStatus, exception) {
				restore_finding(btn, "Beep");
				popup_error(xhr, btn);
			}
		});
	} else if(oldhtml=="Stop Beep"){
		$.ajax({
			url: WSROOT + "ethClient.asmx/StopBeep",
			data: "{id: '" + id + "'}",
			success: function (retval, textStatus) {
				restore_finding(btn, "Beep");
				updateTag(retval.d);
			},
			error: function (xhr, textStatus, exception) {
				restore_finding(btn, oldhtml);
				popup_error(xhr, btn);
			}
		});
	}else if(oldhtml=="Migrate Setting"){
		$.ajax({
			url: WSROOT + "ethClient.asmx/RetryMigrateWirelessConfig",
			data: "{id: '" + id + "'}",
			success: function (retval, textStatus) {
				restore_finding(btn, "Beep");
				updateTag(retval.d);
			},
			error: function (xhr, textStatus, exception) {
				restore_finding(btn, oldhtml);
				popup_error(xhr, btn);
			}
		});
	}
}

var marks = new Array();
function validate(event) {
	var mark_id = event.target.name + "_mark";
	var mark = $("#" + mark_id);
	if (mark.length == 0)
		mark = $("<label for=" + event.target.name + " id=" + mark_id + "> </label>").insertAfter(event.target);

	if (event.data.match) {
		if (event.target.value == $(event.data.match).val()) {
			mark.removeClass().addClass("ok");
		} else {
			mark.removeClass().addClass("error");
			popup(event.data.message, $(event.target));
		}
	} else {
		if ((new RegExp(event.data.regex)).test(event.target.value)) {
			if (event.data.remote) {
				$.ajax({
					url: WSROOT + event.data.remote,
					data: "{" + event.target.name + ": '" + event.target.value + "'}",
					success: function (retval, textStatus) {
						mark.removeClass().addClass("ok");
					},
					error: function (xhr, textStatus, exception) {
						mark.removeClass().addClass("error");
						popup_error(xhr, $(event.target));
					}
				});
			} else
				mark.removeClass().addClass("ok");

		} else {
			mark.removeClass().addClass("error");
			popup(event.data.message, $(event.target));
		}
	}
}

$("#indexPage").live("pageinit", function () {
	$("#updateInterval").change(function () {
		var btn = $(this);
		var oldhtml = show_finding(btn, "Configuring...");
		$.ajax({
			complete: function () { restore_finding(btn, oldhtml); },
			error: function (xhr, textStatus, exception) { popup_error(xhr, btn); },
			url: WSROOT + "ethClient.asmx/SetPostbackInterval",
			data: "{sec:" + $(this).val() + ",autoRetry: true}",
			success: function (retval, textStatus) {
				for (var i = 0; i < retval.d.length; i++) {
					updateTag(retval.d[i]);
				}
			}
		});
	});
});

var serverTime2LocalTime = 0;

var updateSecIntervalID = 0;

/*
$("#indexPage").live("pagebeforecreate", function () {
	var ua = navigator.userAgent.toLowerCase();
	if (ua.indexOf("iphone") != -1 || ua.indexOf("ipod") != -1 || ua.indexOf("ipad") != -1) {
		$("#indexPage").attr("data-title", "My Tag List");
	}
});
$("#optionPage").live("pagebeforecreate", function () {
	var ua = navigator.userAgent.toLowerCase();
	if (ua.indexOf("iphone") != -1 || ua.indexOf("ipod") != -1) {
		$.each([$("#send_email_to_group"), $("#send_email_oor_group")], function (i, o) {
			var lb = o.children("label").eq(0);
			lb.hide(); o.attr("placeholder", lb.text().replace(":", ""));
		});

	}
});
*/

$("#indexPage").live("pagecreate", function () {

	//onDeviceReady();
	//document.addEventListener("deviceready", onDeviceReady, false);
	//$.mobile.defaultPageTransition = 'none';
	//$.mobile.defaultDialogTransition = 'none';
	//$.mobile.loadingMessage = false;

	document.body.addEventListener("online", function () {
		NC_onResume();
	}, false);

	updateSecIntervalID = setInterval(function () {

		$.each(taglist_cache, function (id, tag) { updateAgoString(tag); });
		/*		if (navigator.network != null) {
		var ns = navigator.network.connection.type;
		$("#networkStatus").text(ns);
		if (ns == Connection.UNKNOWN || ns == Connection.NONE) {
		if (!lastOffline) {
		lastOffline = true;
		$("#indexPage").trigger("pagehide");
		alert("gone offline");
		}
		} else {
		if (lastOffline) {
		lastOffline = false;
		$("#indexPage").trigger("pageshow");
		alert("gone online");
		}
		}
		}
		*/
	}, 2000);

	//	clearInterval(updateSecIntervalID);

});

$("#indexPage").live('pagehide', function () {
	
	if(getNextUpdate_xhr){
		getNextUpdate_xhr.abort();
		getNextUpdate_xhr=null;
	}
});


$("#indexPage").live('pageshow', function () {
	$.ajax({ url: WSROOT + "ethAccount.asmx/GetLoginEmail", 
		error: function(){
			/*$.mobile.changePage("signin.html", { transition: "slidedown" });*/ location.replace("signin.html");
		},
		success: function (retval, textStatus) {
			
			loginEmail = retval.d;
			
			if (window.NC) { 
				window.NC.registerMN(loginEmail); 
			}

			if (serverTime2LocalTime == 0) {
				$.ajax({ url: WSROOT + "ethClient.asmx/GetServerTime2", 
					data:  "{tzo: " + (new Date()).getTimezoneOffset() + "}", 
					success: function (retval, textStatus) {
					var serverTime = new Date((retval.d / 10000) - 11644473600000);
					var now = new Date();
					serverTime2LocalTime = serverTime.getTime() - now.getTime();
				}
				});
			}

			createTagList();

			$.ajax({
				url: WSROOT + "ethClient.asmx/GetPostbackInterval",
				success: function (retval, textStatus) {
					$("#updateInterval").val(retval.d).selectmenu("refresh");
				}
			});
		}
	});
});


function SaveTagInfo(tag, btn) {
	var oldhtml = show_finding(btn, "Saving...");
	$.ajax({
		url: WSROOT + "ethClient.asmx/SaveTagInfo",
		data: JSON.stringify({ "tag": tag }),
		complete: function () { restore_finding(btn, oldhtml); },
		error: function (xhr, textStatus, exception) {
			popup_error(xhr, btn);
		}
	});
}
function pingTag(btn, tag) {
	var oldhtml = show_finding(btn, "Pinging...");
	$.ajax({
		complete: function () { restore_finding(btn, oldhtml); },
		url: WSROOT + "ethClient.asmx/PingTag",
		data: "{id: '" + tag.slaveId + "'}",
		success: function (retval, textStatus) {
			updateTag(retval.d);
		},
		error: function (xhr, textStatus, exception) {
			popup_error(xhr, btn);
		}
	});
}
function optionsChoice(btn, id){
	switch (btn.val()) {
		case "1":
			mnOptions(btn, id); break;
		case "2":
			oorOptions(btn, id); break;
		case "3":
			tempOptions(btn, id); break;
		case "4":
			msOptions(btn, id); break;
		case "10":
			messageOptions(btn,id); break;
		case "11":
			eventURLOptions(btn, id); break;
	}
}
function advanced(btn, id) {
	//alert(btn.val());
	var tag = taglist_cache[id];
	var newname = null;
	switch (btn.val()) {
		case "0":
			//pingTag(btn, tag);
			reqPostback(btn, tag.slaveId);
			break;
		case "1":
			newname = prompt("New tag name:", tag.name);
			if (newname) {
				tag.name = newname;
				updateTag(tag);
				SaveTagInfo(tag, btn);
			}
			break;
		case "2":
			newname = prompt("Tag comment:", tag.comment);
			if (newname) {
				tag.comment = newname;
				updateTag(tag);
				SaveTagInfo(tag, btn);
			}
			break;
		case "3":
			var oldhtml = show_finding(btn, "Unassociating...");
			$.ajax({
				complete: function () { restore_finding(btn, oldhtml); },
				url: WSROOT + "ethClient.asmx/UnassociateTag",
				data: "{id: '" + id + "'}",
				success: function (retval, textStatus) {
					var tag = retval.d;
					if (tag.alive) {
						$("#collapsible-" + tag.slaveId).remove();
						$("#taglist").resetRoundedEdges();
					} else {
					

						btn.simpledialog({ mode: 'bool',
							prompt: "Tag failed to respond to unassociation request. Did the tag start flashing?", useModal: true, forceInput: true, cleanOnClose: true,
							'buttons': {
								'Yes (remove from list)': { click: function () {
									
									if(getNextUpdate_xhr){
										getNextUpdate_xhr.abort();
										getNextUpdate_xhr=null;
									}

									$.ajax({ url: WSROOT + "ethClient.asmx/DeleteTag",
										data: "{id: " + tag.slaveId + "}", 
										complete: function(){
											getNextUpdate();
										}
									});
									$("#collapsible-" + tag.slaveId).remove();
									$("#taglist").resetRoundedEdges();
								}, icon: "forward"
								},
								'No (do not remove)': { click: function () {
									//$.mobile.changePage("#indexPage", {transition: "slidedown"}, true);
								}, icon: "back"
								}
							}
						});

					}
				},
				error: function (xhr, textStatus, exception) {
					popup_error(xhr, btn);
				}
			});
			break;

		case "4":
			tag.migrationPending = !tag.migrationPending;
			updateTag(tag);
			SaveTagInfo(tag, btn);
			break;

		case "5":
			if (window["localStorage"] != null) {
				localStorage["mytaglist.stats.slaveid"]=tag.slaveId;
				location.replace("stats.html");
			}else{
				location.replace("stats.html?" + tag.slaveId);
			}
			break;

		case "51":
			if (window["localStorage"] != null) {
				localStorage["mytaglist.stats.slaveid"]=tag.slaveId;
				location.replace("tempStats.html");
			}else
				location.replace("tempStats.html?" + tag.slaveId);
			break;

		case "6":
			var oldhtml = show_finding(btn, "Resetting...");
			$.ajax({
				complete: function () { restore_finding(btn, oldhtml); },
				url: WSROOT + "ethClient.asmx/SoftwareResetTag",
				data: "{id: '" + id + "'}",
				success: function (retval, textStatus) {
					updateTag(retval.d);
				},
				complete: function () { restore_finding(btn, oldhtml); },
				error: function (xhr, textStatus, exception) {
					popup_error(xhr, btn);
				}
			});
			break;
		case "7":
			var oldhtml = show_finding(btn, "Finding...");
			$.ajax({
				url: WSROOT + "ethClient.asmx/LightOn",
				data: "{id: '" + id + "', flash: false}",
				success: function (retval, textStatus) {
					updateTag(retval.d);
				},
				complete: function () { restore_finding(btn, oldhtml); },
				error: function (xhr, textStatus, exception) {
					popup_error(xhr, btn);
				}
			});
			break;
		case "8":
			var oldhtml = show_finding(btn, "Finding...");
			$.ajax({
				url: WSROOT + "ethClient.asmx/LightOff",
				data: "{id: '" + id + "'}",
				success: function (retval, textStatus) {
					updateTag(retval.d);
				},
				complete: function () { restore_finding(btn, oldhtml); },
				error: function (xhr, textStatus, exception) {
					popup_error(xhr, btn);
				}
			});
			break;

	}
	return true;
}
function updateAgoString(tag){
	try{
		var agostring = UserFriendlyTimeSpanString(tag.lastComm);
		$("#lasttalk-" + tag.slaveId).text(agostring);
	}catch(e){}
}

var audioElement = document.createElement('audio');
audioElement.type = "audio/wav";
audioElement.src = 'styles/beep.wav';
//audioElement.setAttribute('src', 'styles/beep.wav');
//document.appendChild(audioElement);
audioElement.load();

var is_open = document.createElement('audio'); is_open.src = WSROOT+'eth/styles/is_open.mp3';
var is_closed = document.createElement('audio'); is_closed.src = WSROOT+'eth/styles/is_closed.mp3';
var is_out_of_range = document.createElement('audio'); is_out_of_range.src = WSROOT+'eth/styles/is_out_of_range.mp3'; 
var has_moved = document.createElement('audio'); has_moved.src = WSROOT+'eth/styles/has_moved.mp3';
var temp_normal = document.createElement('audio'); temp_normal.src = WSROOT+'eth/styles/returned_to_normal_temperature.mp3';
var temp_toohigh = document.createElement('audio'); temp_toohigh.src = WSROOT+'eth/styles/exceeded_upper_temp_limit.mp3';
var temp_toolow = document.createElement('audio'); temp_toolow.src = WSROOT+'eth/styles/exceeded_lower_temp_limit.mp3';

function play_tagname(uuid, suffix) {
	if (window.NC) {
		window.NC.playTwoMediaUrl(WSROOT+"eth/audio/"+ uuid + ".mp3", suffix.src);
	}else{
		var tagMp3 = document.createElement('audio');
		tagMp3.src = "audio/" + uuid + ".mp3";
		tagMp3.type = "audio/mpeg";
		tagMp3.volume = 1;
		tagMp3.load();
	//	alert(tagMp3.src + " " + suffix.src);
		tagMp3.addEventListener('ended', function () { suffix.load(); suffix.type = "audio/mpeg"; suffix.volume = 1; suffix.play(); }, false);
		tagMp3.play();
	}
	return true;
}
function beep_oor(vibrate_only){
	return beep_once(vibrate_only);
}
function start_beep(vibrate_only) {
	beep_looping = true;
	audioElement.addEventListener('ended', function () { if (beep_looping) beep_once(vibrate_only); }, false);
	beep_once(vibrate_only);
	//beep_loop_id = setInterval(function () { beep_once(vibrate_only); }, 2000);
	return true;
}
function stop_beep(){
	beep_looping = false;
	return true;
}
function start_process_notification_queue() {
	if (notificationQueue.length == 0) return;
	var tag = notificationQueue[0];

	eval(tag.notificationJS);
	setTimeout(function () {
		$.ajax({
			url: WSROOT + "ethClient.asmx/ClearNotificationJSFor",
			data: JSON.stringify({ "slaveid": tag.slaveId }),
			//complete: function () {				notificationRun = false; 			}
		});
		notificationQueue.shift();
		start_process_notification_queue();
	}, 5000);
}
function updateTag(tag) {

	var isMsTag = (tag.tagType == 12 || tag.tagType == 22);
	
	var oldTag = taglist_cache[tag.slaveId];
	taglist_cache[tag.slaveId] = tag;
	tag._updated=true;

	if ($("#tagtitle-" + tag.slaveId).length == 0) {
		createTag(tag);
		$("#taglist").resetRoundedEdges();
		return;
	}

	var tag_status = tag.OutOfRange? "(Out of range)" : isMsTag?"("+tagEventStates[tag.eventState][0]+")":"";
	if(tag.tempEventState==2)tag_status += " (Temp. too high)";
	else if(tag.tempEventState==3)tag_status += " (Temp. too low)";

	var ageText = UserFriendlyTimeSpanString(tag.lastComm);
	var tag_theme = (tag.tempEventState==2 || tag.OutOfRange)? "e" : (tag.tempEventState==3?"b":tagEventStates[tag.eventState][1]);

	try {
		if(tag.image_md5==null && oldTag.image_md5!=null){
			$("#tag-pic-" + tag.slaveId).hide();
		}
		else if(tag.image_md5 !== oldTag.image_md5)
		{			
			$("#tag-pic-" + tag.slaveId).css("background", "url('/eth/tags/"+tag.uuid+".jpg?" + (new Date()).getTime() +"')").show();  
			//$("#tag-pic-" + tag.slaveId).css("background", "url('/eth/tags/"+tag.uuid+".jpg')").show();  
		}

		if (tag.eventState==2) {			// moved
			$("#resetbtn-" + tag.slaveId).parent().show();
		} else {
			$("#resetbtn-" + tag.slaveId).parent().hide();
		}

		setTheme($("#tagtitle-" + tag.slaveId).find("a:eq(0)").find(".ui-btn").andSelf(), tag_theme);
		//if (tag.tagType != 22) {
		var btn1 = $("#beepbtn-" + tag.slaveId).parent();
		var btn2 = $("#alt-beepbtn-" + tag.slaveId).parent();
		var btn3 = $("#main-beepbtn-" + tag.slaveId).parent();
		if(tag.migrationPending){
			btn1.find(".ui-btn-text")[0].innerHTML = "Migrate Setting";	btn1.find(".ui-icon").removeClass("ui-icon-search ui-icon-plus").addClass("ui-icon-refresh");	setTheme(btn1, "e");
			btn2.find(".ui-btn-text")[0].innerHTML = "Stop Beep";	btn2.find(".ui-icon").removeClass("ui-icon-search ui-icon-plus").addClass("ui-icon-delete");
			btn3.show();
		}else{
			btn3.hide();
			if (tag.beeping) {
				btn1.find(".ui-btn-text")[0].innerHTML = "Stop Beep";	btn1.find(".ui-icon").removeClass("ui-icon-search ui-icon-refresh").addClass("ui-icon-delete");	setTheme(btn1, "b");
				btn2.find(".ui-btn-text")[0].innerHTML = "Beep";	btn2.find(".ui-icon").removeClass("ui-icon-search ui-icon-plus").addClass("ui-icon-delete");
			} else {
				btn1.find(".ui-btn-text")[0].innerHTML = "Beep";	btn1.find(".ui-icon").removeClass("ui-icon-delete ui-icon-refresh").addClass("ui-icon-search");	setTheme(btn1, "c");
				btn2.find(".ui-btn-text")[0].innerHTML = "Stop Beep";	btn2.find(".ui-icon").removeClass("ui-icon-search ui-icon-plus").addClass("ui-icon-delete");
			}
			var beepopt = $("#beep-opt-" + tag.slaveId);
			if (beepopt.val() != tag.beepDurationDefault) {
				beepopt.val(tag.beepDurationDefault).selectmenu("refresh");
			}
		}
		/*} else {
			if (tag.lit) {
				$("#lightbtn-" + tag.slaveId).parent().find(".ui-btn-text")[0].innerHTML = "Light Off";
				$("#alt-lightbtn-" + tag.slaveId).parent().find(".ui-btn-text")[0].innerHTML = "Light On";
				setTheme($("#lightbtn-" + tag.slaveId).parent(), "b");
			} else {
				$("#lightbtn-" + tag.slaveId).parent().find(".ui-btn-text")[0].innerHTML = "Light On";
				$("#alt-lightbtn-" + tag.slaveId).parent().find(".ui-btn-text")[0].innerHTML = "Light Off";
				setTheme($("#lightbtn-" + tag.slaveId).parent(), "c");
			}
		}*/
		updateAgoString(tag);

		$("#tagbat-" + tag.slaveId).text(Math.round(100.0 * tag.batteryRemaining));    //Math.round(100.0 * ((tag.batteryVolt - 2.3) / 0.85)));
		$("#tagcomment-" + tag.slaveId).text(tag.comment);
		$("#tagname-" + tag.slaveId).text(tag.name + " " + tag_status); // + " "  + tag.solarVolt+"Ga ");
		$("#signal-text-" + tag.slaveId).text(tag.signaldBm > -100 ? Math.round(tag.signaldBm) + "dBm" : "No Signal");

		$("#tag-temp-" + tag.slaveId).html(tag.temperature ? Math.round(tag.temperature) + "°C/"+Math.round(tag.temperature*9/5+32) + "°F" : "N/A");
		/*if (tag.tagType==22) {
			$("#tag-temp-" + tag.slaveId).html(tag.temperature ? Math.round(tag.temperature) + "" : "N/A");
			$("#tag-solarstat-" + tag.slaveId).text(tag.solarVolt ? (tag.solarVolt >= tag.batteryVolt ? ", Charging" : ", On battery") : "");
		}*/

		var advchoice = $("#advanced-choice-" + tag.slaveId);
		var mt = tag.migrationPending ? "Use new wireless setting" : "Use old wireless setting";
		var mt_dom = advchoice.find("option")[4];
		if (mt_dom.innerHTML != mt) {
			mt_dom.innerHTML = mt;
			advchoice.selectmenu("refresh", true);
		}
		$("#signal-icon-" + tag.slaveId).removeClass().addClass("ui-icon-signal-" + dBmToBars(tag.signaldBm));

		if (tag.notificationJS != null && tag.notificationJS!="null" && tag.notificationJS.length>0) {
			notificationQueue.push(tag);
			if (notificationQueue.length == 1) {
				start_process_notification_queue();
			}
		}

} catch (e) {

	debugger;

	alert(e);
	
	}
}
var anyMs = false;
function createTag(tag) {
	var isMsTag = (tag.tagType == 12 || tag.tagType == 22);
	if (isMsTag) anyMs = true;

	var tag_status = tag.OutOfRange ? "(Out of range)" : isMsTag?"("+tagEventStates[tag.eventState][0]+")":"";
	if(tag.tempEventState==2)tag_status += " (Temp. too high)";
	else if(tag.tempEventState==3)tag_status += " (Temp. too low)";

	var ageText = UserFriendlyTimeSpanString(tag.lastComm);
	var tag_theme = (tag.tempEventState==2 || tag.OutOfRange)? "e" : (tag.tempEventState==3?"b":tagEventStates[tag.eventState][1]);

	var html = ('<div id="collapsible-{3}" data-role="collapsible" data-theme="{0}"><h3 id=tagtitle-{3}><span id=tagname-{3}>{1} {2}</span></h3><h3><span id=signal-icon-{3} class=ui-icon-signal-{4}></span></h3>')
							.format(tag_theme, tag.name, tag_status, tag.slaveId, dBmToBars(tag.signaldBm));

	html += ('<div class="column pic ui-shadow" id="tag-pic-{0}" style="{1} background-image: url({3}eth/tags/{2}.jpg)"></div>').format(tag.slaveId, tag.image_md5==null?'display:none;':'', tag.uuid,WSROOT);
//if (tag.tagType != 22) {
	html += ('<button data-inline=1 id="beepbtn-{0}" data-corners=0 data-shadow=0 data-theme="{2}" onclick="togglebeep($(this), {0}); return false;"  data-icon={3}>{1}</button>')
						.format(tag.slaveId, tag.migrationPending? "Migrate Setting" : (tag.beeping ? "Stop Beep" : "Beep"), 
						tag.migrationPending? "e" : (tag.beeping ? "b" : "c"), tag.migrationPending?"refresh":(tag.beeping?"delete":"search"));
	if(tag.migrationPending){
		html += ('<button data-inline=1 id="main-beepbtn-{0}" data-theme="b" onclick="togglebeep($(this), {0}); return false;"  data-icon=search>Beep</button>').format(tag.slaveId);
	}else{
		html += ('<button data-inline=1 data-hide=1 id="main-beepbtn-{0}" data-theme="b" onclick="togglebeep($(this), {0}); return false;"  data-icon=search>Beep</button>').format(tag.slaveId);
	}
	if (isMsTag) {
		html += ('<select data-inline=1 name="beep-opt-{0}" id="beep-opt-{0}"><option value=1001 selected>Until moved</option><option value=5>For 5 seconds</option><option value=10>For 10 seconds</option><option value=15>For 15 seconds</option><option value=20>For 20 seconds</option><option value=30>For 30 seconds</option><option value=1000>Until stopped</option></select>')
							.format(tag.slaveId);
	}
	else {
		html += ('<select data-inline=1 name="beep-opt-{0}" id="beep-opt-{0}"><option value=5>For 5 seconds</option><option value=10>For 10 seconds</option><option value=15 selected>For 15 seconds</option><option value=20>For 20 seconds</option><option value=30>For 30 seconds</option><option value=1000>Until stopped</option></select>')
							.format(tag.slaveId);
	}
	if(tag.migrationPending){
		html += ('<button data-inline=1 id="alt-beepbtn-{0}" data-theme="c" onclick="togglebeep($(this), {0}); return false;"  data-icon=delete>Stop Beep</button>').format(tag.slaveId);
	}else{
		html += ('<button data-inline=1 id="alt-beepbtn-{0}" data-theme="c" onclick="togglebeep($(this), {0}); return false;"  data-icon={2}>{1}</button>')
					.format(tag.slaveId, tag.beeping ? "Beep" : "Stop Beep", tag.beeping?"search":"delete");
	}
	/*}
	else {
		html += ('<button data-inline=1 id="lightbtn-{0}" data-corners=0 data-shadow=0 data-theme="{2}" onclick="togglelight($(this), {0}); return false;"  data-icon=search>{1}</button>')
							.format(tag.slaveId, tag.lit ? "Light Off" : "Light On", tag.lit ? "b" : "c");
		html += ('<button data-inline=1 id="alt-lightbtn-{0}" data-theme="c" onclick="togglelight($(this), {0}); return false;"  data-icon=delete>{1}</button>').format(tag.slaveId, tag.lit ? "Light On" : "Light Off");
		html += ('<button data-inline=1 id="read-stat-btn-{0}" data-theme="c" onclick="reqPostback($(this), {0}); return false;"  data-icon=refresh>Refresh Stats</button>').format(tag.slaveId);
	}*/

	if (isMsTag) {
		if (tag.eventState == 2)  // moved
		{
			html += ('<button data-inline=1 id="resetbtn-{0}" data-icon=delete data-theme="c" onclick="resetit($(this), {0}); return false;" >Reset</button>').format(tag.slaveId);
		}
		else {
			html += ('<button data-hide=1 data-inline=1 id="resetbtn-{0}" data-icon=delete data-theme="c" onclick="resetit($(this), {0}); return false;" >Reset</button>').format(tag.slaveId);
		}
		html += ('<button data-inline=1 id="armbtn-{0}" data-icon=star data-theme="a" onclick="armit($(this), {0}); return false;" >Arm motion sensor</button><button data-inline=1 id="disarmbtn-{0}" data-icon=grid data-theme="c" onclick="disarmit($(this), {0}); return false;" >Disarm </button>')
								.format(tag.slaveId);
		html+=('<select data-inline=1 data-toptext="Options..." onchange="optionsChoice($(this), {0}); return false;" id="options-choice-{0}" data-native-menu="false" data-icon="gear"><option value="4">Motion Sensor...</option><option value="3">Temperature...</option><option value="2">Out of Range...</option><option value="10">Customize Message...</option><option value="1">Phones...</option><option value="11">URL Calling...</option></select>').format(tag.slaveId);
	} else {
		html+=('<select data-inline=1 data-toptext="Options..." onchange="optionsChoice($(this), {0}); return false;" id="options-choice-{0}" data-native-menu="false" data-icon="gear"><option value="3">Temperature...</option><option value="2">Out of Range...</option><option value="10">Customize Message...</option><option value="1">Phones...</option><option value="11">URL Calling...</option></select>').format(tag.slaveId);
	}
	html+=('<select data-inline=1 data-toptext="More..." onchange="advanced($(this), {0}); return false;" id="advanced-choice-{0}" data-native-menu="false" data-icon="arrow-r">').format(tag.slaveId);
	html += '<option value="0">Ping Tag</option><option value="1">Change Tag name</option><option value="2">Edit Tag comment</option><option value="3">Unassociate</option><option value="4">'
	     + (tag.migrationPending? "Use new wireless setting" : "Use old wireless setting") + '</option>' + (isMsTag?'<option value="5">Door Statistics</option>':'') + 
		 '<option value="51">Temperature Statistics</option><option value="6">Reset States</option><option value="7">Ligth On<option><option value="8">Light Off</option></select>';

	//html += ('<button data-inline=1 id="advancedbtn-{0}" data-icon=arrow-r data-iconpos="right" data-theme="c" onclick="advanced($(this), {0}); return false;" >Advanced</button>')
	//							.format(tag.slaveId);

	html += ('<table class="ui-btn table-detail"><tr><td style="width:40%; word-wrap: break-word"><span id=tagcomment-{0}>{1}</span></td><td>Battery: <b><span id=tagbat-{0}>{2}</span>% left</b>,  Signal: <b><span id=signal-text-{0}>{3}</span></b>, Updated <b><span id=lasttalk-{0}>{4}</span></b>')
							.format(tag.slaveId, tag.comment, Math.round(100.0 * tag.batteryRemaining)/*Math.round(100.0 * ((tag.batteryVolt - 2.3) / 0.85))*/, tag.signaldBm > -100 ? Math.round(tag.signaldBm) + "dBm" : "No Signal", ageText);
	html += (',Temperature: <b><span id=tag-temp-{0}>{1}</span></b></span>')
							.format(tag.slaveId, tag.temperature?Math.round(tag.temperature)+"°C/"+Math.round(tag.temperature*9/5+32) + "°F" :"N/A");
	/*if (tag.tagType==22) {
		html += (',Temperature: <b><span id=tag-temp-{0}>{1}</span><span id=tag-solarstat-{0}>{2}</span></b></span>')
							.format(tag.slaveId, tag.temperature?Math.round(tag.temperature)+"":"N/A", tag.solarVolt?(tag.solarVolt >= tag.batteryVolt ? ", Charging" : ", On battery"):"");
	}*/
	html += '.</td></tr></table></div>';
	$(html).appendTo("#taglist").trigger('create');
	$("#collapsible-"+tag.slaveId).collapsible();

	if (tag.notificationJS != null && tag.notificationJS!="null" && tag.notificationJS.length>0) {
		notificationQueue.push(tag);
		if (notificationQueue.length == 1) {
			start_process_notification_queue();
		}
	}
}

var buttonsCreated =false;
function createTagList() {
	$.ajax({
		url: WSROOT + "ethClient.asmx/GetTagList",
		success: function (retval, textStatus) {
			
			for (var i = 0; i < retval.d.length; i++) {
				updateTag(retval.d[i]);
			}
			$.each(taglist_cache, function (id, tag) { 
				if(tag){
					if(!tag._updated){
						$("#collapsible-"+tag.slaveId).remove();
						$("#taglist").resetRoundedEdges();
						delete taglist_cache[id];
					}
					tag._updated = false;
				}
			});
			
			if (!buttonsCreated) {
				$("#taglist").resetRoundedEdges();
				/*var html = '<button id=stopbeepallbtn data-inline=1 data-icon=delete data-theme="b" onclick="all_tag_action($(this), \'StopBeepAll\'); return false;" >Stop Beep All</button>';
				if (anyMs) {
					html += '<button id=armallbtn data-inline=1 data-icon=star data-theme="a" onclick="all_tag_action($(this), \'ArmAll\'); return false;" >Arm All</button><button data-inline=1 id=disarmallbtn data-icon=grid data-theme="c" onclick="all_tag_action($(this), \'DisarmAll\'); return false;" >Disarm All</button>';
				}
				//html+='<button id=migratebtn data-inline=1 data-icon=gear data-theme="d" onclick="migrateConfig($(this)); return false;">Wireless Setting</button>';
				html+='<select data-inline=1 data-toptext="Settings..." onchange="globalSettings($(this)); return false" id="global-settings" data-native-menu="false" data-icon="gear"><option value="1">Account...</option><option value="2">Wireless...</option></select>';

				$("<div id='globalBtns'/>").html(html).insertAfter("#taglist");
				$("#globalBtns").trigger('create');*/
				buttonsCreated = true;
			}
			//if (!window.NC) getNextUpdate();			// do comet only for PC interface
			getNextUpdate();
		},
		error: function (xhr, textStatus, exception) {
			//popupDebug(xhr, btn);
			popup_error(xhr, btn);
		}
	});
}

var getNextUpdate_xhr=null;
function getNextUpdate() {
	if(getNextUpdate_xhr)return;

	getNextUpdate_xhr = $.ajax({
		url: WSROOT + "ethComet.asmx?op=GetNextUpdate",
		dataType: "xml",
		contentType: "text/xml; charset=\"utf-8\"",
		beforeSend: function (xhr) { xhr.setRequestHeader("SOAPAction", '"http://mytaglist.com/ethComet/GetNextUpdate"'); },
		data: '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><GetNextUpdate xmlns="http://mytaglist.com/ethComet" /></soap:Body></soap:Envelope>',
		error: function (xhr, textStatus, exception) {
			//popupDebug(xhr, $.mobile.pageContainer);
			if (textStatus != "abort" && xhr.responseText)
				popup_error(xhr, $.mobile.pageContainer);
			getNextUpdate_xhr=null;
		},
		success: function (retval, textStatus, xhr) {
			var result = $(xhr.responseXML).find('GetNextUpdateResult');
			if (result.length && result.attr("xsi:nil") != "true") {
				var tags = eval("(" + result.text() + ")");
				if (tags != null) {
					for (var i = 0; i < tags.length; i++)
						updateTag(tags[i]);
				}
			}
			getNextUpdate_xhr=null;
			getNextUpdate();
		}
	});

}
/*
$("#startconttx").click(function (event) {
	var btn = $(event.target);
	var oldhtml = show_finding(btn, "Starting PWM...");
	$.ajax({
		url: WSROOT + "ethClient.asmx/StartListen",
		//		url: WSROOT + "ethClient.asmx/StartContTX",
		complete: function () { restore_finding(btn, oldhtml); }
	});
});
$("#stopconttx").click(function (event) {
	var btn = $(event.target);
	var oldhtml = show_finding(btn, "Stopping...");
	$.ajax({
		url: WSROOT + "ethClient.asmx/StopListen",
		//		url: WSROOT + "ethClient.asmx/StopContTX",
		complete: function () { restore_finding(btn, oldhtml); }
	});
});
*/
$("a.optionSubmit").click(function (event) {
	var btn = $(event.target);
	var oldhtml = show_finding(btn, "Saving...");
	$(this).parent().parent().find("form").submit();
	restore_finding(btn, oldhtml);
});
	
$("a.logout").click(function (event) {
	var btn = $(event.target);
	var oldhtml = show_finding(btn, "Signing Off...");
	$.ajax({
		url: WSROOT + "ethClient.asmx/SignOut",
		success: function (retval, textStatus) {
			//$.mobile.changePage("signin.html", { transition: "slidedown" });
			location.replace("signin.html");
		},
		error: function (xhr, textStatus, exception) {
			restore_finding(btn, oldhtml);
			popup_error(xhr, btn);
		}
	});
});


$("#addnewPage").live('pagebeforeshow', function () {
	$("#namingform").hide();
	$("#foundInfo").hide();
});

var searchCancelled = true;
var searchBtnHtml;
$("#addnewPage").live('pagebeforehide', function () {
	if (!searchCancelled) {
		searchCancelled = true;
		restore_finding($("#searchbtn"), searchBtnHtml);
	}
});
var newTagInfo = null;
function continueSearch(btn) {
	$.ajax({
		url: WSROOT + "ethClient.asmx/ScanNewTag",
		data: "{timeout: 6000}",
		success: function (retval, textStatus) {
			if (retval.d != null) {

				newTagInfo = retval.d;

				$("#foundInfo_name")[0].innerHTML = (newTagInfo.description + " (ver. " + newTagInfo.version1 + ")");
				$("#foundInfo_signal")[0].innerHTML = (newTagInfo.signaldBm > -100 ? newTagInfo.signaldBm + "dBm" : "No Signal");
				$("#foundInfo_bat")[0].innerHTML = (Math.round(100.0 * retval.d.batteryRemaining)) + "% left";  //(Math.round(100.0 * ((retval.d.batteryVolt - 2.3) / 0.85)) + "% left");1
				$("#namingform").show();

				searchCancelled = true;
				restore_finding(btn, searchBtnHtml);

				$.ajax({ url: WSROOT + "ethClient.asmx/SuggestNewTagName",
					success: function (retval) { $("#addnew_name").val(retval.d); },
					error: function (xhr, textStatus, exception) {
						popup_error(xhr, btn);
					}
				});

			} else if (!searchCancelled) {
				continueSearch(btn);
			} else {
				restore_finding(btn, searchBtnHtml);
			}
		},
		error: function (xhr, textStatus, exception) {
			restore_finding(btn, searchBtnHtml);
			popup_error(xhr, btn);
		}
	});
}
$("#searchbtn").live("click", function (event) {
	event.preventDefault();
	searchCancelled = false;
	var btn = $(event.target);
	searchBtnHtml = show_finding(btn, "Searching...");
	continueSearch(btn);
});

$("#addnew_name").blur({ regex: "^\\S+", message: "Required" }, validate);
$("#namingform").live('submit', function (event) {
	event.preventDefault();
	$("#namingform input").trigger('blur');
	if ($("label.error").length == 0) {
		var btn = $("#associate_submitBtn");
		var oldhtml = show_finding(btn, "Associating...");
		var name = $('#addnew_name').val(); var comment = $('#addnew_comment').val();
		var data1 = JSON.stringify({ "name": name, "comment": comment, "taginfo": newTagInfo, "timeout": 6000 });
		$.ajax({
			url: WSROOT + "ethClient.asmx/AssociateNewTag",
			data: data1,
			success: function (retval, textStatus) {
				newTag = retval.d;
				if (!newTag.alive) {
					btn.simpledialog({ mode: 'bool', prompt: "Tag failed to respond to association request. Is the tag still flashing?", useModal: true, forceInput: true, cleanOnClose: true,
						'buttons': {
							'Yes (roll back)': { click: function () {
								$.ajax({ url: WSROOT + "ethClient.asmx/DeleteTag",
									data: "{id: " + newTag.slaveId + "}"
								});
							}, icon: "back"
							},
							'No (treat as done)': { click: function () {
								$.mobile.changePage("#indexPage", { transition: "none" }, true);
								
								updateTag(newTag);
								pingTag($("#advanced-choice-"+newTag.slaveId), newTag);
								
							}, icon: "forward"
							}
						}
					});
				} else {
					$.mobile.changePage("#indexPage", { transition: "none" }, true);

					updateTag(newTag);
					pingTag($("#advanced-choice-"+newTag.slaveId), newTag);
				}
			},
			complete: function () { restore_finding(btn, oldhtml); },
			error: function (xhr, textStatus, exception) {
				//popup_error(xhr, btn);
				popupDebug(xhr, btn);
			}
		});
	}
});

//$("#send_email_to").blur({ regex: VALID_EMAIL_REGEX, message: "Valid email address required for notification."}, validate);
//$("#send_email_to_oor").blur({ regex: VALID_EMAIL_REGEX, message: "Valid email address required for notification."}, validate);
$("#doormode").change(function () {
	if ($(this).val() === "1") {
		$("#thAngleGroup").show(); $("#non_door_mode_label").hide(); $("#door_mode_delay").parent().show(); $("#auto_reset_delay").parent().hide();
	} else {
		$("#thAngleGroup").hide(); $("#door_mode_delay").parent().hide(); $("#non_door_mode_label").show(); $("#auto_reset_delay").parent().show();
	}
});
$("#send_email").change(function () {
	if (this.checked) {
		$("#send_email_to_group").show();
		//if ($("#doormode").val()==="1") $("#send_email_on_close_group").show();
	} else { $("#send_email_to_group").hide(); /*$("#send_email_on_close_group").hide();*/ }
});
$("#send_tweet_ms").change(function () {	if (this.checked) {		$("#send_tweet_ms_group").show();	} else { $("#send_tweet_ms_group").hide();  }});
$("#send_email_oor").change(function () {	if (this.checked) {		$("#send_email_oor_group").show();	} else { $("#send_email_oor_group").hide();  }});
$("#send_tweet_oor").change(function () {	if (this.checked) {		$("#send_tweet_oor_group").show();	} else { $("#send_tweet_oor_group").hide();  }});
$("#send_email_temp").change(function () {	if (this.checked) {		$("#send_email_temp_group").show();	} else { $("#send_email_temp_group").hide();  }});
$("#send_tweet_temp").change(function () {	if (this.checked) {		$("#send_tweet_temp_group").show();	} else { $("#send_tweet_temp_group").hide();  }});

$("#enableTempEvent").change(function () {	if (this.checked) {		$("#tempEventGroup").show();	} else { $("#tempEventGroup").hide();  }});

$("#beep_at_pc").change(function () { if (this.checked) { $("#beep_at_pc_options").show(); } else { $("#beep_at_pc_options").hide(); } });
$("#beep_at_pc_oor").change(function () { if (this.checked) { $("#beep_at_pc_vibrate_oor_group").show(); } else { $("#beep_at_pc_vibrate_oor_group").hide(); } });
$("#beep_at_pc_temp").change(function () { if (this.checked) { $("#beep_at_pc_vibrate_temp_group").show(); } else { $("#beep_at_pc_vibrate_temp_group").hide(); } });

$("#beep_at_tag").change(function () { if (this.checked) { $("#beep_at_tag_options").show(); } else { $("#beep_at_tag_options").hide(); } });

$("#en_autoarm").change(function () { if (this.checked) { $("#autoarm_group").show(); } else { $("#autoarm_group").hide(); } });
/*
$("#en_autoarm2").change(function () { if (this.checked) { $("#autoarm_group2").show(); } else { $("#autoarm_group2").hide(); } });
$("#day1_sun").change(function () { if (this.checked)$("#day2_sun").attr("checked", false).checkboxradio("refresh");});
$("#day1_mon").change(function () { if (this.checked)$("#day2_mon").attr("checked", false).checkboxradio("refresh");});
$("#day1_tue").change(function () { if (this.checked)$("#day2_tue").attr("checked", false).checkboxradio("refresh");});
$("#day1_wed").change(function () { if (this.checked)$("#day2_wed").attr("checked", false).checkboxradio("refresh");});
$("#day1_thu").change(function () { if (this.checked)$("#day2_thu").attr("checked", false).checkboxradio("refresh");});
$("#day1_fri").change(function () { if (this.checked)$("#day2_fri").attr("checked", false).checkboxradio("refresh");});
$("#day1_sat").change(function () { if (this.checked)$("#day2_sat").attr("checked", false).checkboxradio("refresh");});
$("#day2_sun").change(function () { if (this.checked)$("#day1_sun").attr("checked", false).checkboxradio("refresh");});
$("#day2_mon").change(function () { if (this.checked)$("#day1_mon").attr("checked", false).checkboxradio("refresh");});
$("#day2_tue").change(function () { if (this.checked)$("#day1_tue").attr("checked", false).checkboxradio("refresh");});
$("#day2_wed").change(function () { if (this.checked)$("#day1_wed").attr("checked", false).checkboxradio("refresh");});
$("#day2_thu").change(function () { if (this.checked)$("#day1_thu").attr("checked", false).checkboxradio("refresh");});
$("#day2_fri").change(function () { if (this.checked)$("#day1_fri").attr("checked", false).checkboxradio("refresh");});
$("#day2_sat").change(function () { if (this.checked)$("#day1_sat").attr("checked", false).checkboxradio("refresh");});
*/

var msConfig = {email: null, send_email: false, sensitivity: 50, interval: 2, beep_pc: true, beep_pc_loop: false,
			beep_tag: false, beep_tag_autostop: true, door_mode: true, door_mode_delay: 0, door_mode_angle: 22.5,
			send_email_on_close: false, auto_reset_delay: -1, beep_pc_tts: true, mobile_notifications: [], 
			aa1_tod:0, ada1_tod:0, aa2_tod:0, ada2_tod:0,  aa1_en:false, aa2_en:false, aa1_dow:0, aa2_dow:0 , tzo:0
		};

function mnOptions(btn, id) {
	var oldhtml = show_finding(btn, "Loading...");
	$.ajax({
		complete: function () { restore_finding(btn, oldhtml); },
		url: WSROOT + "ethClient.asmx/LoadMobileNotificationConfig",
		data: "{id: '" + id + "'}",
		success: function (retval, textStatus) {
			if (retval.d != null) msConfig = retval.d;

			$.mobile.changePage($("#mnOptionPage"), { transition: device_transition, role: "dialog" });

			$("#mobileNotifications").children().remove();
			if (msConfig.mobile_notifications.length > 0) {
				var html = '<fieldset data-role="controlgroup"><legend>Enable notifications on:</legend>';
				for (var i = 0; i < msConfig.mobile_notifications.length; i++) {
					html += ('<input type="checkbox" name="mnc-{0}" id="mnc-{0}" class="custom" {1}/><label for="mnc-{0}">{2}</label>')
							.format(i, msConfig.mobile_notifications[i].disabled ? '' : 'checked="checked"', msConfig.mobile_notifications[i].name);
				}
				html += '</fieldset>';
				$(html).appendTo("#mobileNotifications");
				$("#mobileNotifications").trigger('create').show();
			} 

			$("#mnOptionForm").unbind("submit");
			$("#mnOptionForm").submit(function (event) {
				event.preventDefault();
				$("#mnOptionForm input:visible").trigger('blur');
				//if ($("label.error").length == 0) {
				var btn = $("#btnOptionSubmit_mn");
				var oldhtml = show_finding(btn, "Saving...");
				var applyAll = $("#applyAll_mn").is(":checked");
				
				for (var i = 0; i < msConfig.mobile_notifications.length; i++) {
					msConfig.mobile_notifications[i].disabled = $("#mnc-" + i).is(":checked") ? false : true;
				}

				$.ajax({
					url: WSROOT + "ethClient.asmx/SaveMobileNotificationConfig",
					data: JSON.stringify({ "id": id, "config": msConfig, "applyAll": applyAll }),
					complete: function () { restore_finding(btn, oldhtml); },
					success: function (retval, textStatus) {
						$.mobile.changePage("#indexPage", { transition: device_transition }, true);
						//location.hash = "#indexPage";
					},
					error: function (xhr, textStatus, exception) {
						popup_error(xhr, null);
					}
				});
				//}
			});
		},
		error: function (xhr, textStatus, exception) {
			popup_error(xhr, btn);
		}
	});
}

function msOptions(btn, id) {
	$(".msg_template").unbind("click");
	$(".msg_template").click(function(event){
		event.preventDefault();
		messageOptions($(this), id);
	});

	var oldhtml = show_finding(btn, "Loading...");
	$.ajax({
		complete: function () { restore_finding(btn, oldhtml); },
		url: WSROOT + "ethClient.asmx/LoadMotionSensorConfig",
		data: "{id: '" + id + "'}",
		success: function (retval, textStatus) {
			if (retval.d != null) msConfig = retval.d;

			$.mobile.changePage($("#msOptionPage"), { transition: device_transition, role: "dialog" });
			//$("#optionPage").dialog("open");
			$("#msOptionTitle").text("Motion Sensor Options for " + taglist_cache[id].name);

			$("#sensitivity").val(msConfig.sensitivity).slider("refresh");
			$("#responsiveness").val(msConfig.interval).selectmenu("refresh");
			$("#doormode").val(msConfig.door_mode ? "1" : "0").selectmenu("refresh").trigger("change");
			$("#thAngle").val(msConfig.door_mode_angle).selectmenu("refresh");
			$("#door_mode_delay").val(msConfig.door_mode_delay).selectmenu("refresh");
			$("#auto_reset_delay").val(msConfig.auto_reset_delay).selectmenu("refresh");
			$("#send_email").attr("checked", msConfig.send_email).checkboxradio("refresh").trigger("change");
			$("#send_tweet_ms").attr("checked", msConfig.send_tweet).checkboxradio("refresh").trigger("change");
			$("#send_email_to").val(msConfig.email || loginEmail);
			$("#send_email_on_close").attr("checked", msConfig.send_email_on_close).checkboxradio("refresh");
			$("#beep_at_pc").attr("checked", msConfig.beep_pc).checkboxradio("refresh").trigger("change");
			$("#beep_at_pc_loop").attr("checked", msConfig.beep_pc_loop).checkboxradio("refresh");
			$("#beep_at_pc_tts").attr("checked", msConfig.beep_pc_tts).checkboxradio("refresh");
			$("#beep_at_pc_vibrate").attr("checked", msConfig.beep_pc_vibrate).checkboxradio("refresh");
			$("#beep_at_tag").attr("checked", msConfig.beep_tag).checkboxradio("refresh").trigger("change");
			$("#beep_at_tag_autostop").attr("checked", msConfig.beep_tag_autostop).checkboxradio("refresh");
			
			$("#en_autoarm").attr("checked", msConfig.aa1_en).checkboxradio("refresh").trigger("change");
			//$("#en_autoarm2").attr("checked", msConfig.aa2_en).checkboxradio("refresh").trigger("change");
			$("#aa1_tod").val(msConfig.aa1_tod).selectmenu("refresh");
			//$("#aa2_tod").val(msConfig.aa2_tod).selectmenu("refresh");
			$("#ada1_tod").val(msConfig.ada1_tod).selectmenu("refresh");
			//$("#ada2_tod").val(msConfig.ada2_tod).selectmenu("refresh");
			$("#day1_sun").attr("checked", msConfig.aa1_dow&1?true:false).checkboxradio("refresh");
			$("#day1_mon").attr("checked", msConfig.aa1_dow&2?true:false).checkboxradio("refresh");
			$("#day1_tue").attr("checked", msConfig.aa1_dow&4?true:false).checkboxradio("refresh");
			$("#day1_wed").attr("checked", msConfig.aa1_dow&8?true:false).checkboxradio("refresh");
			$("#day1_thu").attr("checked", msConfig.aa1_dow&16?true:false).checkboxradio("refresh");
			$("#day1_fri").attr("checked", msConfig.aa1_dow&32?true:false).checkboxradio("refresh");
			$("#day1_sat").attr("checked", msConfig.aa1_dow&64?true:false).checkboxradio("refresh");
/*			$("#day2_sun").attr("checked", msConfig.aa2_dow&1?true:false).checkboxradio("refresh");
			$("#day2_mon").attr("checked", msConfig.aa2_dow&2?true:false).checkboxradio("refresh");
			$("#day2_tue").attr("checked", msConfig.aa2_dow&4?true:false).checkboxradio("refresh");
			$("#day2_wed").attr("checked", msConfig.aa2_dow&8?true:false).checkboxradio("refresh");
			$("#day2_thu").attr("checked", msConfig.aa2_dow&16?true:false).checkboxradio("refresh");
			$("#day2_fri").attr("checked", msConfig.aa2_dow&32?true:false).checkboxradio("refresh");
			$("#day2_sat").attr("checked", msConfig.aa2_dow&64?true:false).checkboxradio("refresh");
*/			
			//populateBtOptions(msConfig);

			$("#optionForm").unbind("submit");
			$("#optionForm").submit(function (event) {
				event.preventDefault();
				$("#optionForm input:visible").trigger('blur');
				//if ($("label.error").length == 0) {
				var btn2 = $("#btnOptionSubmit");
				var oldhtml2 = show_finding(btn2, "Saving...");
				var applyAll = $("#applyAll").is(":checked");

				msConfig.sensitivity = $("#sensitivity").val();
				msConfig.interval = $("#responsiveness").val();
				msConfig.door_mode = ($("#doormode").val() == 1 ? true : false);
				msConfig.door_mode_angle = $("#thAngle").val();
				msConfig.door_mode_delay = $("#door_mode_delay").val();
				msConfig.auto_reset_delay = $("#auto_reset_delay").val();

				msConfig.send_tweet = $("#send_tweet_ms").is(":checked");
				msConfig.send_email = $("#send_email").is(":checked");
				msConfig.email = $('#send_email_to').val();
				msConfig.send_email_on_close = $("#send_email_on_close").is(":checked");
				msConfig.beep_pc = $("#beep_at_pc").is(":checked");
				msConfig.beep_pc_loop = $("#beep_at_pc_loop").is(":checked");
				msConfig.beep_pc_tts = $("#beep_at_pc_tts").is(":checked");
				msConfig.beep_pc_vibrate = $("#beep_at_pc_vibrate").is(":checked");
				msConfig.beep_tag = $("#beep_at_tag").is(":checked");
				msConfig.beep_tag_autostop = $("#beep_at_tag_autostop").is(":checked");

				msConfig.aa1_en = $("#en_autoarm").is(":checked");
				//msConfig.aa2_en = $("#en_autoarm2").is(":checked");
				msConfig.aa1_tod = $("#aa1_tod").val();
				//msConfig.aa2_tod = $("#aa2_tod").val();
				msConfig.ada1_tod= $("#ada1_tod").val();
				//msConfig.ada2_tod = $("#ada2_tod").val();
				msConfig.aa1_dow = $("#day1_sun").is(":checked") + 2*$("#day1_mon").is(":checked") + 4*$("#day1_tue").is(":checked")
							+8*$("#day1_wed").is(":checked") + 16*$("#day1_thu").is(":checked") + 32*$("#day1_fri").is(":checked") + 64*$("#day1_sat").is(":checked");
				//msConfig.aa2_dow = $("#day2_sun").is(":checked") + 2*$("#day2_mon").is(":checked") + 4*$("#day2_tue").is(":checked")
				//			+8*$("#day2_wed").is(":checked") + 16*$("#day2_thu").is(":checked") + 32*$("#day2_fri").is(":checked") + 64*$("#day2_sat").is(":checked");
				msConfig.tzo =  (new Date()).getTimezoneOffset();

				$.ajax({
					complete: function () { restore_finding(btn2, oldhtml2); },
					url: WSROOT + "ethClient.asmx/SaveMotionSensorConfig",
					data: JSON.stringify({ "id": id, "config": msConfig, "applyAll": applyAll }),
					success: function (retval, textStatus) {
						$.mobile.changePage("#indexPage", { transition: device_transition }, true);
						//location.hash = "#indexPage";
					},
					error: function (xhr, textStatus, exception) {
						popup_error(xhr, null);
					}
				});
				//}
			});

		}
		/*error: function (xhr, textStatus, exception) {
		popup_error(xhr, btn);
		}*/
	});		
}


$("#msOptionPage").live("pagebeforecreate", function () {
	//var tzo =  (new Date()).getTimezoneOffset();
	for(var h=0;h<24;h++){
		for(var q=0;q<4;q++){
			var lit = (h>12?h-12:h)+":"+(q==0?"00":q*15)+(h>12?"PM":"AM");
			var min_utc = h*60+q*15; // + tzo;
			$('<option/>').attr('value', min_utc).text(lit).appendTo('#aa1_tod').clone().appendTo('#ada1_tod'); //.clone().appendTo('#aa2_tod').clone().appendTo('#ada2_tod');
		}
	}
});

var degC_min=-20, degC_max=85, degCmode=true;
function convertDegFToC(){
	var cal1=$('#tempcal');
	cal1.attr("min",degC_min).attr("max",degC_max).val(Math.round( (cal1.val()-32)*5/9) );
	var min1=$('#slider_min');
	min1.attr("min",degC_min).attr("max",degC_max).val(Math.round( (min1.val()-32)*5/9) );
	var max1=$('#slider_max');
	max1.attr("min",degC_min).attr("max",degC_max).val( Math.round((max1.val()-32)*5/9) );
}
$('#radio-degC').change(function(){
	if(!degCmode){
		convertDegFToC();
		degCmode=true;
	}
});
function convertDegCToF(){
	var cal1=$('#tempcal');
	cal1.attr("min",degC_min*9/5+32).attr("max",degC_max*9/5+32).val( Math.round(cal1.val()*9/5+32) ); //.slider("refresh");
	var min1=$('#slider_min');
	min1.attr("min",degC_min*9/5+32).attr("max",degC_max*9/5+32).val( Math.round(min1.val()*9/5+32) ); //.slider("refresh");
	var max1=$('#slider_max');
	max1.attr("min",degC_min*9/5+32).attr("max",degC_max*9/5+32).val( Math.round(max1.val()*9/5+32) ); //.slider("refresh");
}
$('#radio-degF').change(function(){
	if(degCmode){
		convertDegCToF();
		degCmode=false;
	}
});

$(".twitter_login").click(function(event){
	event.preventDefault();
	$(this).closest("form").trigger("submit");
	twitterLogin($(this));
});

function tempOptions(btn, id) {

	$(".msg_template").unbind("click");
	$(".msg_template").click(function(event){
		event.preventDefault();
		messageOptions($(this), id);
	});
	var tag = taglist_cache[id];
	var oldhtml = show_finding(btn, "Loading...");
	$.ajax({
		complete: function () { restore_finding(btn, oldhtml); },
		url: WSROOT + "ethClient.asmx/LoadTempSensorConfig",
		data: "{id: '" + id + "'}",
		success: function (retval, textStatus) {
			if (retval.d != null) msConfig = retval.d;

			$.mobile.changePage($("#tempOptionPage"), { transition: device_transition, role: "dialog" });
			$("#tempOptionTitle").text("Temperature Sensor Options for " + tag.name);

			$("#enableTempEvent").attr("checked", tag.tempEventState!=0).checkboxradio("refresh").trigger("change");
			
			$("#tempcal").val(tag.temperature).slider("refresh");
			$("#slider_min").val(msConfig.th_low).slider("refresh");
			$("#slider_max").val(msConfig.th_high).slider("refresh");
			if(!degCmode){
				$('#radio-degF').attr("checked", true).checkboxradio("refresh");
				convertDegCToF();
			}
			else{
				$('#radio-degC').attr("checked", true).checkboxradio("refresh");
			}
			$("#send_email_temp").attr("checked", msConfig.send_email).checkboxradio("refresh").trigger("change");
			$("#send_tweet_temp").attr("checked", msConfig.send_tweet).checkboxradio("refresh").trigger("change");
			$("#send_email_to_temp").val(msConfig.email || loginEmail);
			$("#beep_at_pc_temp").attr("checked", msConfig.beep_pc).checkboxradio("refresh").trigger("change");
			$("#beep_at_pc_tts_temp").attr("checked", msConfig.beep_pc_tts).checkboxradio("refresh").trigger("change");
			$("#beep_at_pc_vibrate_temp").attr("checked", msConfig.beep_pc_vibrate).checkboxradio("refresh");

			$('#slider_min').unbind("change");
			$('#slider_min').change(function() {
				var min = parseInt($(this).val());
				var max = parseInt($('#slider_max').val());
				if (min > max) {
					$(this).val(max).slider('refresh');
				}
			});
			$('#slider_max').unbind("change");
			$('#slider_max').change(function() {
				var min = parseInt($('#slider_min').val());
				var max = parseInt($(this).val());
				if (min > max) {
					$(this).val(min).slider('refresh');
				}
			});
			$("#btnTempCal").unbind("click");
			$("#btnTempCal").click(function(event){
				event.preventDefault();
				var tempCalDegC = degCmode ? $("#tempcal").val() : ($("#tempcal").val()-32)*5/9;
				tag.tempCalOffset = tempCalDegC - (tag.temperature - tag.tempCalOffset);
				tag.temperature = tempCalDegC;
				updateTag(tag);
				SaveTagInfo(tag, $("#btnTempCal"));
			});

			$("#tempOptionForm").unbind("submit");
			$("#tempOptionForm").submit(function (event) {
				event.preventDefault();
				$("#tempOptionForm input:visible").trigger('blur');
				//if ($("label.error").length == 0) {
				var btn1 = $("#btnOptionSubmit_temp");
				var oldhtml = show_finding(btn1, "Saving...");
				var applyAll = $("#applyAll_temp").is(":checked");
				
				var org_th_low=msConfig.th_low, org_th_high=msConfig.th_high;
				msConfig.th_low=degCmode ? $("#slider_min").val() : ($("#slider_min").val()-32)*5/9;
				msConfig.th_high = degCmode ? $("#slider_max").val() : ($("#slider_max").val()-32)*5/9;
								
				msConfig.send_email = $("#send_email_temp").is(":checked");
				msConfig.send_tweet = $("#send_tweet_temp").is(":checked");
				msConfig.email = $("#send_email_to_temp").val();
				msConfig.beep_pc = $("#beep_at_pc_temp").is(":checked");
				msConfig.beep_pc_tts = $("#beep_at_pc_tts_temp").is(":checked");
				msConfig.beep_pc_vibrate = $("#beep_at_pc_vibrate_temp").is(":checked");

				$.ajax({
					url: WSROOT + "ethClient.asmx/SaveTempSensorConfig",
					data: JSON.stringify({ "id": id, "config": msConfig, "applyAll": applyAll }),
					complete: function () { restore_finding(btn1, oldhtml); },
					success: function (retval, textStatus) {
						$.mobile.changePage("#indexPage", { transition: device_transition }, true);
						
						if(($("#enableTempEvent").is(":checked") && tag.tempEventState==0) ||org_th_high!=msConfig.th_high || org_th_low!=msConfig.th_low){
							var oldhtml = show_finding(btn, "Configuring...");
							$.ajax({
								url: WSROOT + "ethClient.asmx/ArmTempSensor",
								data: "{id: '" + id + "'}",
								success: function (retval, textStatus) {
									updateTag(retval.d);
								},
								complete: function () { restore_finding(btn, oldhtml); },
								error: function (xhr, textStatus, exception) {
									popup_error(xhr, null);
								}
							});
						}						
						else if(!$("#enableTempEvent").is(":checked") && tag.tempEventState!=0){
							var oldhtml = show_finding(btn, "Configuring...");
							$.ajax({
								url: WSROOT + "ethClient.asmx/DisarmTempSensor",
								data: "{id: '" + id + "'}",
								success: function (retval, textStatus) {
									updateTag(retval.d);
								},
								complete: function () { restore_finding(btn, oldhtml); },
								error: function (xhr, textStatus, exception) {
									popup_error(xhr, null);
								}
							});
						}
					},
					error: function (xhr, textStatus, exception) {
						popup_error(xhr, null);
					}
				});
			});
		},
		error: function (xhr, textStatus, exception) {
			popup_error(xhr, btn);
		}
	});
}
function oorOptions(btn, id) {
	$(".msg_template").unbind("click");
	$(".msg_template").click(function(event){
		event.preventDefault();
		messageOptions($(this), id);
	});

	var oldhtml = show_finding(btn, "Loading...");
	$.ajax({
		complete: function () { restore_finding(btn, oldhtml); },
		url: WSROOT + "ethClient.asmx/LoadOutOfRangeConfig",
		data: "{id: '" + id + "'}",
		success: function (retval, textStatus) {
			if (retval.d != null) msConfig = retval.d;

			$.mobile.changePage($("#oorOptionPage"), { transition: device_transition, role: "dialog" });
			$("#oorOptionTitle").text("Out of Range Notification Options for " + taglist_cache[id].name);

			$("#send_email_oor").attr("checked", msConfig.send_email_oor).checkboxradio("refresh").trigger("change");
			$("#send_tweet_oor").attr("checked", msConfig.send_tweet).checkboxradio("refresh").trigger("change");
			$("#send_email_to_oor").val(msConfig.email_oor || loginEmail);
			$("#beep_at_pc_oor").attr("checked", msConfig.beep_pc_oor).checkboxradio("refresh").trigger("change");
			$("#beep_at_pc_tts_oor").attr("checked", msConfig.beep_pc_tts_oor).checkboxradio("refresh").trigger("change");
			$("#beep_at_pc_vibrate_oor").attr("checked", msConfig.beep_pc_vibrate_oor).checkboxradio("refresh");

			$("#oorOptionForm").unbind("submit");
			$("#oorOptionForm").submit(function (event) {
				event.preventDefault();
				$("#oorOptionForm input:visible").trigger('blur');
				//if ($("label.error").length == 0) {
				var btn = $("#btnOptionSubmit_oor");
				var oldhtml = show_finding(btn, "Saving...");
				var applyAll = $("#applyAll_oor").is(":checked");
				
				msConfig.send_email_oor = $("#send_email_oor").is(":checked");
				msConfig.send_tweet = $("#send_tweet_oor").is(":checked");
				msConfig.email_oor = $("#send_email_to_oor").val();
				msConfig.beep_pc_oor = $("#beep_at_pc_oor").is(":checked");
				msConfig.beep_pc_tts_oor = $("#beep_at_pc_tts_oor").is(":checked");
				msConfig.beep_pc_vibrate_oor = $("#beep_at_pc_vibrate_oor").is(":checked");

				$.ajax({
					url: WSROOT + "ethClient.asmx/SaveOutOfRangeConfig",
					data: JSON.stringify({ "id": id, "config": msConfig, "applyAll": applyAll }),
					complete: function () { restore_finding(btn, oldhtml); },
					success: function (retval, textStatus) {
						$.mobile.changePage("#indexPage", { transition: device_transition }, true);
						//location.hash = "#indexPage";
					},
					error: function (xhr, textStatus, exception) {
						popup_error(xhr, null);
					}
				});
				//}
			});
		},
		error: function (xhr, textStatus, exception) {
			popup_error(xhr, btn);
		}
	});
}
function twitterLogin(btn){
	var oldhtml = show_finding(btn, "Redirecting...");
	$.ajax({
		complete: function () { restore_finding(btn, oldhtml); },
		url: WSROOT + "ethMobileNotifications.asmx/GetTwitterAuthorizeURL",
		data: "{}",
		success: function (retval, textStatus) {
			if (retval.d != null) window.location.replace(retval.d); //$.mobile.changePage(retval.d, { transition: device_transition, role: "dialog" });
		},
		error: function (xhr, textStatus, exception) {
			popup_error(xhr, btn);
		}
	});
}

var accountConfig = {loginEmail: null, loginPwd: null, twitterID: null, twitterPwd: null, allowMore: true};
function accountOptions(btn) {
	var oldhtml = show_finding(btn, "Loading...");
	$.ajax({
		complete: function () { restore_finding(btn, oldhtml); },
		url: WSROOT + "ethClient.asmx/LoadAccountConfig",
		data: "{}",
		success: function (retval, textStatus) {
			if (retval.d != null) accountConfig = retval.d;

			$.mobile.changePage($("#accountOptionPage"), { transition: device_transition, role: "dialog" });

			$("#allowmore").attr("checked", accountConfig.allowMore).checkboxradio("refresh");
			$("#loginEmail").val(accountConfig.loginEmail);
			$("#loginPwd").val(accountConfig.loginPwd);
			
			$("#accountOptionForm").unbind("submit");
			$("#accountOptionForm").submit(function (event) {
				event.preventDefault();
				$("#accountOptionForm input:visible").trigger('blur');
				if ($("label.error").length == 0) {
					var btn = $("#btnOptionSubmit_account");
					var oldhtml = show_finding(btn, "Saving...");
					
					accountConfig.allowMore = $("#allowmore").is(":checked");
					accountConfig.loginEmail = $("#loginEmail").val();
					accountConfig.loginPwd = $("#loginPwd").val();

					$.ajax({
						url: WSROOT + "ethClient.asmx/SaveAccountConfig",
						data: JSON.stringify({"config": accountConfig}),
						complete: function () { restore_finding(btn, oldhtml); },
						success: function (retval, textStatus) {
							history.back();
							//$.mobile.changePage("#indexPage", { transition: device_transition }, true);
							//location.hash = "#indexPage";
						},
						error: function (xhr, textStatus, exception) {
							popup_error(xhr, btn);
						}
					});
				}
			});
		},
		error: function (xhr, textStatus, exception) {
			popup_error(xhr, btn);
		}
	});
}

var eventURLConfig;
function eventURLOptions(btn, id) {
	var oldhtml = show_finding(btn, "Loading...");
	$.ajax({
		complete: function () { restore_finding(btn, oldhtml); },
		url: WSROOT + "ethClient.asmx/LoadEventURLConfig",
		data: "{id: '" + id + "'}",
		success: function (retval, textStatus) {
			if (retval.d != null) eventURLConfig = retval.d;
			
			$.mobile.changePage($("#eventURLOptionPage"), { transition: device_transition, role: "dialog" });
			$("#eventURLTitle").text("Custom URL Calling on Event for " + taglist_cache[id].name);

			for(var x in eventURLConfig){
				if(eventURLConfig[x]!=null){
					$('#eu_' + x + '_url').val(eventURLConfig[x].url);
					var enbtn = $('#eu_' + x + '_en');
					enbtn.change(function () {	if (this.checked) {	$(this).parent().next().show();	} else { $(this).parent().next().hide();  }});
					if(eventURLConfig[x].disabled){
						enbtn.attr('checked', false).checkboxradio("refresh"); 
						$('#eu_' + x + '_group').hide();
					}else{
						enbtn.attr('checked', true).checkboxradio("refresh"); 
						$('#eu_' + x + '_group').show();
					}
                    $("#eu_"+x+"_nat").attr('checked', eventURLConfig[x].nat);
				}
			}
			$("#eventURLOptionForm").unbind("submit");
			$("#eventURLOptionForm").submit(function (event) {
				event.preventDefault();
				var btn = $("#btnOptionSubmit_eu");
				var oldhtml = show_finding(btn, "Saving...");

				for(var x in eventURLConfig){
					if(eventURLConfig[x]!=null){
						eventURLConfig[x].url= $('#eu_' + x + '_url').val();
						eventURLConfig[x].disabled= ! ($('#eu_' + x + '_en').is(":checked"));
                        eventURLConfig[x].nat= $('#eu_' + x + '_nat').is(":checked");
					}
				}
				var applyAll = $("#applyAll_eu").is(":checked");
				
				$.ajax({
					url: WSROOT + "ethClient.asmx/SaveEventURLConfig",
					data: JSON.stringify({ "id": id, "config": eventURLConfig, "applyAll": applyAll }),
					complete: function () { restore_finding(btn, oldhtml); },
					success: function (retval, textStatus) {
						history.back();
						//$.mobile.changePage("#indexPage", { transition: device_transition }, true);
						//location.hash = "#indexPage";
					},
					error: function (xhr, textStatus, exception) {
						popup_error(xhr,null);
					}
				});
			});
		},
		error: function (xhr, textStatus, exception) {
			popup_error(xhr);
		}
	});
}
var messageConfig;
function messageOptions(btn, id) {
	var oldhtml = show_finding(btn, "Loading...");
	$.ajax({
		complete: function () { restore_finding(btn, oldhtml); },
		url: WSROOT + "ethClient.asmx/LoadMessageTemplateConfig",
		data: "{id: '" + id + "'}",
		success: function (retval, textStatus) {
			if (retval.d != null) messageConfig = retval.d;
			
			$.mobile.changePage($("#messageOptionPage"), { transition: device_transition, role: "dialog" });
			$("#msgTempTitle").text("Customize Notification Messages for " + taglist_cache[id].name);

			for(var x in messageConfig){
				if(messageConfig[x].title!=null){
					$('#msg_' + x + '_t').val(messageConfig[x].title);
					$('#msg_' + x + '_d').val(messageConfig[x].detail);
				}
			}
			$("#messageOptionForm").unbind("submit");
			$("#messageOptionForm").submit(function (event) {
				event.preventDefault();
				var btn = $("#btnOptionSubmit_msg");
				var oldhtml = show_finding(btn, "Saving...");

				for(var x in messageConfig){
					if(messageConfig[x].title!=null){
						messageConfig[x].title= $('#msg_' + x + '_t').val();
						messageConfig[x].detail= $('#msg_' + x + '_d').val();
					}
				}
				var applyAll = $("#applyAll_message").is(":checked");
				
				$.ajax({
					url: WSROOT + "ethClient.asmx/SaveMessageTemplateConfig",
					data: JSON.stringify({ "id": id, "config": messageConfig, "applyAll": applyAll }),
					complete: function () { restore_finding(btn, oldhtml); },
					success: function (retval, textStatus) {
						history.back();
						//$.mobile.changePage("#indexPage", { transition: device_transition }, true);
						//location.hash = "#indexPage";
					},
					error: function (xhr, textStatus, exception) {
						popup_error(xhr, btn);
					}
				});
			});
		},
		error: function (xhr, textStatus, exception) {
			popup_error(xhr, btn);
		}
	});
}
function undelete(btn){
	$.ajax({
		complete: function () { restore_finding(btn, oldhtml); },
		url: WSROOT + "ethClient.asmx/UndeleteTag",
		data: "{id: " + btn.val() + "}", 
		success: function (retval) {
			if(retval.d)
				updateTag(retval.d);
		}
	});
}

function globalSettings(btn){
	switch (btn.val()) {
		case "1":
			accountOptions(btn);
			break;
		case "2":
			migrateConfig(btn); break;
		case "3":
			undeleteChoice(btn); break;
	}
}
function recalc_wireless_perf(dr, resp, display){
	var drkbps=(10e3/29.0/((dr.val()&0x7F)+1.0)/(1.0+8.0*(dr.val()>>7) ));
	var rexp_dqd = Math.round(0x10 / drkbps* 20);
	if(rexp_dqd>128)rexp_dqd=128;
	if(rexp_dqd<10)rexp_dqd=10;

	display.html("Est. Range:  <b>{0}m</b><br>Est. Battery Life:  <b>{1} months</b>".format(
		Math.round(60*Math.pow(10.0, (-0.5*10.0*Math.log(drkbps/20.0)/Math.log(10)  )/20.0 )), 
		(20.0*resp.val()/0x60 * (0x10/rexp_dqd)).toFixed(1)  ));
}
$("#newdatarate").change(function(){recalc_wireless_perf($("#newdatarate"), $("#newresp"), $("#newperformance"));});
$("#newresp").change(function(){recalc_wireless_perf($("#newdatarate"), $("#newresp"), $("#newperformance"));});

var oldConfig, newConfig;
function migrateConfig(btn){
	var oldhtml = show_finding(btn, "Loading...");
	$.ajax({
		complete: function () { restore_finding(btn, oldhtml); },
		url: WSROOT + "ethClient.asmx/LoadWirelessConfigs",
		success: function (retval) {
			$.mobile.changePage($("#migratePage"), { transition: device_transition, role: "dialog" });
			oldConfig = retval.d[0];
			$("#oldfreq").val(oldConfig.Freq).selectmenu("refresh");
			$("#olddatarate").val(oldConfig.dataRate).selectmenu("refresh");
			$("#oldresp").val(oldConfig.activeInterval).selectmenu("refresh");	
			recalc_wireless_perf($("#olddatarate"), $("#oldresp"), $("#oldperformance"));
			newConfig= retval.d[1]; 
			$("#newfreq").val(newConfig.Freq).selectmenu("refresh");
			$("#newdatarate").val(newConfig.dataRate).selectmenu("refresh");
			$("#newresp").val(newConfig.activeInterval).selectmenu("refresh").trigger("change");
		}
	});
}
$("#migratePage").live("pagebeforecreate", function () {
	for(var i=0;i<105;i++){
		var freqv = (13+i)*32+1;
		$('<option/>').val(freqv).text(Math.round((430+0.0025*freqv)*100)/100+"MHz").appendTo('#oldfreq').clone().appendTo('#newfreq');
	}
});
$("#migrateform").submit(function (event) {
	event.preventDefault();

	var btn = $("#submitBtn");
	var oldhtml = show_finding(btn, "Migrating...");
	newConfig.Freq = $("#newfreq").val(); newConfig.dataRate = $("#newdatarate").val(); newConfig.activeInterval=$("#newresp").val();
	$.ajax({
		url: WSROOT + "ethClient.asmx/MigrateWirelessConfig",
		data: JSON.stringify({"newConfig": newConfig}),
		complete: function () { restore_finding(btn, oldhtml); },
		success: function (retval, textStatus) {
			$.mobile.changePage("#indexPage", { transition: device_transition }, true);
			for (var i = 0; i < retval.d.length; i++) {
				updateTag(retval.d[i]);
			}
			var ai = $("#updateInterval");
			if(ai.val()<2147483647)ai.trigger("change");
		},
		error: function (xhr, textStatus, exception) {
			popup_error(xhr, null);
		}
	});
});