﻿(function() {
	if ($.browser.msie && $.browser.version < 7) {
		var objs = document.getElementsByTagName("INPUT");
		for (var i = 0, l = objs.length; i < l; i++) {
			var input = objs[i];
			if (input.type == "text" || input.type == "password")
				input.className = (input.className ? input.className + " " : "") + "textual";
		}
	}
	var objs = document.getElementsByTagName("A");
	for (var i = 0, l = objs.length; i < l; i++) {
		var rel = objs[i].getAttribute("rel");
		if (rel && rel.indexOf("external") != -1)
			objs[i].setAttribute("target", "_blank");
	}
})();
$("a[href=\"#\"]").live("click", function(event) {
	event.preventDefault();
}).live("keypress", function(event) {
	var keyCode = event.keyCode;
	if (keyCode != 9)
		event.preventDefault();
	if (keyCode == 13)
		this.click();
});
$(function() {
	if ($.browser.msie && $.browser.version < 7) {
		var objs = document.getElementsByTagName("IMG");
		var isPng = /\.png$/i;
		for (var i = 0, l = objs.length; i < l; i++) {
			var img = objs[i];
			if (!isPng.test(img.src))
				continue;
			img.style.width = img.offsetWidth + "px";
			img.style.height = img.offsetHeight + "px";
			img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + img.src + "',sizingMethod='scale')";
			img.src = "img/t.gif";
		}
	}
	$.extend($.modal.defaults, { close: false, persist: true, opacity: 75, minWidth: null, minHeight: null });
	$("a[href=\"#print\"]").click(function(event) {
		event.preventDefault();
		window.open(document.getElementsByTagName("BASE")[0].href + "print", null, "top=0,left=0,height=600,width=800,resize=no,scrollbars=auto,toolbar=no,location=no,menubar=no,status=no");
	});
});

String.prototype.padLeft = function(l, c) {
	if (!c) c = "0";
	return (l + 1 - this.length > 0 ? Array(l + 1 - this.length).join(c) : "") + this;
}
String.prototype.htmlAttributeEncode = function() {
	return this.replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
String.prototype.splitToInt = function(d) {
	var a = this.split(d);
	for (var i = 0, l = a.length; i < l; i++)
		a[i] = parseInt(a[i]);
	return a;
}
Date.prototype.toTimeString = function() {
	return this.getHours().toString().padLeft(2) + ":" + this.getMinutes().toString().padLeft(2);
}
Date.prototype.toShortDateTimeString = function() {
	return this.getDate().toString().padLeft(2) + "/" + (this.getMonth() + 1).toString().padLeft(2) + " " + this.toTimeString();
}

$.isNull = function(o, a) {
	if (o == null)
		return a;
	return o;
};
$.binarySearch = function(o, v) {
    var h = o.length - 1, l = 0, m;
    while (l <= h)
		if (o[m = h + l >> 1] > v)
			h = m - 1;
		else if (o[m] < v)
			l = m + 1;
		else
			return m;
	return -1;
};
$.fn.replace = function() {
	var stack = [];
	return this.domManip(arguments, true, function(a) {
		this.parentNode.replaceChild(a, this);
		stack.push(a);
	}).pushStack(stack);
};
$.ajaxSetup({
	global: false,
	async: true,
	contentType: "application/json; charset=utf-8",
	dataType: "json",
	type: "POST",
	data: "{}",
	dataFilter: function(data, type) {
		//return data.replace(/"\\\/(Date\([0-9-]+\))\\\/"/gi, "new $1");
		return data.replace(/"\\\/Date\(([0-9-]+)\)\\\/"/gi, "$1");
	},
	error: function(xhr, msg) {
		var response = JSON.parse(xhr.responseText);
		var message;
		if (response && (message = response.Message)) {
			if (!Login.visible) {
				if (message == "Unauthorized") {
					if (Login.identified) {
						if (this.authCallbackElement)
							Login.authCallbackElement = this.authCallbackElement;
						setTimeout("Login.show(true);", 250);
					}
					else
						window.location.href = $("base").attr("href") + "login?url=" + escape(window.location.href);
				}
				else
					alert(response.Message);
			}
		}
		else
			alert(msg);
	}
});
$.addFavorite = function(url, title) {
    if (window.sidebar)
        window.sidebar.addPanel(title, url, "");
    else
        window.external.AddFavorite(url, title);
};
$("a[class=protected]").bind("mouseover focus", function () {
	var a = $(this);
	a.unbind().click(function(event) {
		a.removeAttr("title");
		var d = a.attr("href");
		d = d.substring(d.indexOf("?") + 1);
		try {
			$.ajax({
				async: false,
				url: "services/security.asmx/Reveal",
				data: JSON.stringify({d: d}),
				success: function(msg) {
					var e;
					if (e = msg.d) {
						e = a.text().replace("...", e);
						a.attr("href", "mailto:" + e).text(e);
					}
				}
			});
		}
		catch(e) {
			event.preventDefault();
		}
	});
});

$.fn.menu = function() {
	var _current = null;
	var _focused = null;
	var _toHide = null;
	var _toHideTimerID = null;
	var _toHideTimeout = $.browser.msie && $.browser.version < 7 ? 1000 : 500;
	var _timerID = null;

	return this.each(function() {
		$("> li", this).hover(function() {
			if (_toHideTimerID) {
				clearTimeout(_toHideTimerID);
				_toHideTimerID = null;
			}
			showSub(this);
		},
		function() {
			_toHide = $(this);
			_toHideTimerID = setTimeout(beforeHide, _toHideTimeout);
		});
		$("> li > a", this).bind("focus", function() {
			showSub($(this).parent());
		}).bind("blur", function() {
			_timerID = setTimeout(afterBlur, 50);
		});
		$("> li > ul > li > a", this).bind("focus", function() {
			_focused = $(this).parent();
		}).bind("blur", function() {
			_focused = null;
			setTimeout(afterBlur, 50);
		});
	});

	function beforeHide() {
		_toHideTimerID = null;
		hideSub(_toHide);
	}
	function showSub(li) {
		if (li != _current) {
			clearTimeout(_timerID);
			hideSub(_current);
		}
		$("ul:first", li).css({
			top: $(li).position().top + $(li).height(),
			left: $(li).position().left - $("ul:first", li).width() + $(li).attr("offsetWidth")
		}).show();
		_current = li;
	}
	function hideSub(li) {
		if (!li)
			return;
		$("ul:first", li).hide();
		_current = null;
	}
	function afterBlur() {
		if (_focused == null) {
			hideSub(_current);
			return;
		}
	}
};
$("#header > ul").menu();

$.extend($.fn.disableTextSelect = function(enable) {
	return this.each(function() {
		if ($.browser.mozilla)
			$(this).css("MozUserSelect", enable ? "" : "none");
		else if ($.browser.msie) {
			if (enable)
				$(this).unbind("selectstart");
			else
				$(this).bind("selectstart", function(){ return false; });
		}
		else {
			if (enable)
				$(this).unbind("mousedown");
			else
				$(this).mousedown(function(){ return false; });
		}
	});
});

var Login = new function() {
	var _self = this;
	var reload = true;
	this.identified = false;
	this.authenticated = false;
	this.visible = false;
	this.setup = function() {
		$("#login_modal").bind("submit", function(event) {
			event.preventDefault();
			var username = $("#login_username");
			if (!username.val()) {
				username.focus();
				return;
			}
			var password = $("#login_password");
			if (!password.val()) {
				password.focus();
				return;
			}
			var form = $(this);
			$("button", form).attr("disabled", "disabled");
			$.ajax({
				url: "services/security.asmx/Login",
				data: JSON.stringify({u: username.val(), p: password.val()}),
				success: function(msg) {
					var ret = msg.d;
					this.identified = this.authenticated = true;
					if (reload)
						window.location.reload(false);
					else
						$.modal.close();
					_self.hide();
				},
				error: function(xhr, msg) {
					var response = JSON.parse(xhr.responseText);
					if (response.Message)
						$("#login_modal .error").html(response.Message).show();
				},
				complete: function() {
					$("button", form).removeAttr("disabled");
					if (_self.authCallbackElement) {
						_self.authCallbackElement.click();
						_self.authCallbackElement = null;
					}
				}
			});
		}).find("button[type=button]").click(function() {
			_self.hide();
		});
	};
	this.show = function(noReload) {
		_self.visible = true;
		reload = !noReload;
		$("#login_modal button").attr("disabled", "");
		$("#login_modal .error").html("").hide();
		$.modal($("#login_modal"));
		var username = $("#login_username");
		if (username.val())
			$("#login_password").focus();
		else
			username.focus();
	};
	this.hide = function() {
		$("#login_password").val("");
		$.modal.close();
		_self.visible = false;
	};
	this.out = function() {
		$.ajax({
			url: "services/security.asmx/Logout",
			data: "{}",
			success: function(msg) {
				location.href = $("base").attr("href");
			}
		});
	};
};
Login.setup();

var IFrameForm = {
	_form: null,
	frame: function(c) {
		var n = "f" + Math.floor(Math.random() * 99999);
		var d = document.createElement("DIV");
		d.innerHTML = "<iframe style=\"display: none;\" src=\"about:blank\" id=\"" + n + "\" name=\"" + n + "\" onload=\"IFrameForm.loaded('" + n + "');\"></iframe>";
		document.body.appendChild(d);
		var i = document.getElementById(n);
		if (c) {
			if (typeof(c.onSuccess) == "function")
				i.onSuccess = c.onSuccess;
			if (typeof(c.onComplete) == "function")
				i.onComplete = c.onComplete;
		}
		return n;
	},
	form: function(f, name) {
		f.setAttribute("target", name);
	},
	submit: function(f, c) {
		this._form = f;
		IFrameForm.form(f, IFrameForm.frame(c));
		if (!c.onStart || (typeof(c.onStart) == "function" && c.onStart()))
			f.submit();
	},
	loaded: function(id) {
		var i = document.getElementById(id);
		var d;
		if (i.contentDocument)
			d = i.contentDocument;
		else if (i.contentWindow)
			d = i.contentWindow.document;
		else
			d = window.frames[id].document;
		if (d.location.href == "about:blank")
			return;
		if (typeof(i.onSuccess) == "function") {
			var t = d.getElementById("text");
			if (t)
				i.onSuccess(t.value, this._form);
		}
		if (typeof(i.onComplete) == "function")
			i.onComplete();
		setTimeout("IFrameForm.dispose(\"" + id + "\");", 0);
	},
	dispose: function(id) {
		var i = document.getElementById(id);
		i.parentNode.removeChild(i);
	}
}

var History = new function() {
	var base = "include/history.htm";
	var list = [];
	var navigating = false;
	var historyLength = window.history.length;
	var historyDisabled = false;
	var iframe = null;
	this.navigate = function(callback, state) {
		if (!iframe) {
			iframe = $("<iframe />").attr("src", base).hide().appendTo(document.body).bind("load", function() {
				if (navigating) {
					navigating = false;
					if (historyLength == window.history.length)
						historyDisabled = true;
					return;
				}
				back();
			});
		}
		var item = { id: Math.random(), callback: callback, state: state };
		list.push(item);
		navigating = true;
		iframe.attr("src", base + "?" + item.id);
	};
	this.unavigate = function() {
		if (!historyDisabled) {
			window.history.go(-1);
			return;
		}
		back();
	};

	function back() {
		var count = list.length;
		if (count > 0) {
			var item = list.pop();
			item.callback(item.state);
		}
	}
};

