﻿/// <reference path="jquery-vsdoc.js" />

var Cpo = {

	init: function () {
		if (!window.console) {
			window.console = function () { };
			window.console.log = function () { };
		}
		this.AddHandler(window, "load", this.CreateDelegate(this, this.mainOnLoad));
	},

	// -------------
	// Public
	// -------------

	$: function (id) {
		//var obj = document.getElementById(id + "_VCpO");
		//if (!obj)
		obj = document.getElementById(id);
		return obj;
	},

	CreateDelegate: function (instance, method) {
		return function () {
			return method.apply(instance, arguments);
		}
	},

	AddHandler: function (element, eventName, handler) {
		var browserHandler = handler;
		if (element.addEventListener)
			element.addEventListener(eventName, browserHandler, false);
		else if (element.attachEvent)
			element.attachEvent('on' + eventName, browserHandler);
	},

	RemoveHandler: function (element, eventName, handler) {
		var browserHandler = handler;
		if (element.removeEventListener)
			element.removeEventListener(eventName, browserHandler, false);
		else if (element.detachEvent)
			element.detachEvent('on' + eventName, browserHandler);
	},

	StopPropagation: function (ev) {
		ev.stopPropagation ? ev.stopPropagation() : ev.cancelBubble = true;
	},

	PreventDefault: function (ev) {
		ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
		return false;
	},

	AddOnAjaxLoaded: function (handler) {
		if (!this.ajaxHandlers)
			this.ajaxHandlers = [];
		if (!window.pageLoad)
			window.pageLoad = this.CreateDelegate(this, this._onAjaxLoaded);
		this.ajaxHandlers[this.ajaxHandlers.length] = handler;
	},

	_onAjaxLoaded: function (sender, args) {
		//for (var i = 0; i < this.ajaxHandlers.length; i++)
		//	this.ajaxHandlers[i]();
		//this.ajaxHandlers = [];
		while (this.ajaxHandlers.length > 0) {
			this.ajaxHandlers[0]();
			this.ajaxHandlers.shift();
		}
	},

	IsPageValid: function () {
		if (typeof (ValidatorOnLoad) == "function")
			return Page_IsValid;
		return true;
	},

	// DISMISS
	/*
	RegisterEvent: function(name, call, obj) {
	if (!obj)
	obj = window;
	if (obj.addEventListener)
	obj.addEventListener(name, call, false);
	else
	obj.attachEvent("on" + name, call);
	},

	// DISMISS
	UnRegisterEvent: function(name, call, obj) {
	if (!obj)
	obj = window;
	if (obj.removeEventListener)
	obj.removeEventListener(name, call, false);
	else
	obj.detachEvent("on" + name, call);
	},
	*/

	ScrollTo: function (elm) {
		if (!elm) elm = this;
		if (typeof (jQuery) !== "function") {
			if (elm.scrollIntoView)
				elm.scrollIntoView(true);
			return;
		}
		elm = $(elm);
		if (!elm.is(":visible"))
			return;
		var pos = elm.position();
		if (pos.top < $(window).scrollTop()) {
			$("html,body").animate({ scrollTop: pos.top });
		}
		else if (pos.top + elm.outerHeight() > $(window).scrollTop() + $(window).height()) {
			var top = pos.top + elm.outerHeight() - $(window).height() + 10;
			$("html,body").animate({ scrollTop: top });
		}
	},

	UrlAddParam: function (key, value, url) {
		// SAFE-DUPE: DDK34KSD34
		var useDoc = url == null;
		if (useDoc)
			searchPart = document.location.search;
		else {
			if (url.length == 0)
				url = "?";
			else if (url.indexOf('?') < 0)
				url += "?";
			var segments = url.split('?');
			url = segments[0];
			searchPart = "?" + segments[1];
		}
		key = escape(key);
		value = escape(value);
		var kvp = searchPart.substr(1).split('&');
		var i = kvp.length; var x; while (i--) {
			x = kvp[i].split('=');
			if (x[0] == key) {
				if (!value)
					kvp[i] = null;
				else {
					x[1] = value;
					kvp[i] = x.join('=');
				}
				break;
			}
		}
		if (i < 0)
			kvp[kvp.length] = [key, value].join('=');
		if (useDoc)
			document.location.search = kvp.join('&');
		else
			return url + "?" + kvp.join('&');
	},

	RadWinGet: function () {
		if (window.radWindow)
			return window.radWindow;
		else if (window.frameElement.radWindow)
			return window.frameElement.radWindow;
		return null;
	},

	RadWinClose: function (arg) {
		var win = this.RadWinGet();
		if (win) {
			win.Close(arg);
			return true;
		}
		return false;
	},

	RadWinOpen: function (name, url) {
		if (!window.radopen) {
			alert("No valid window object found");
			return;
		}
		window.radopen(url, name);
	},

	/*
	RegisterOnClick: function(iobj, call) {
	var obj;
	if (typeof (iobj) == "string")
	obj = document.getElementById(iobj);
	else
	obj = iobj;
	if (!obj) {
	alert("Could not find control " + iobj);
	return false;
	}
	this.RegisterEvent("mousedown", call);
	},
	*/

	Search: function (el) {
		// DISMISS
		if (window.RegExp && window.encodeURIComponent) {
			var ue = el.href;
			var qe = encodeURIComponent(document.f.q.value);
			if (ue.indexOf("q=") != -1) {
				el.href = ue.replace(new RegExp("q=[^&$]*"), "q=" + qe);
			}
			else {
				el.href = ue + "&q=" + qe;
			}
		}
		return 1;
	},

	SearchInputKey: function (ev, execId) {
		// DISMISS
		if (ev.keyCode == 13) {
			var execObj = document.getElementById(execId);
			if (execObj == null) {
				alert("Invalid search setup");
				return true;
			}
			execObj.click();
		}
		return true;
	},

	SearchClick: function (inputId, url, ev) {
		var inputObj = document.getElementById(inputId);
		if (inputObj == null) {
			alert("Invalid search setup");
			return true;
		}
		if (inputObj.value.length == 0)
			return true;
		if (window.encodeURIComponent) {
			if (ev) {
				this.StopPropagation(ev);
				this.PreventDefault(ev);
			}
			document.location.href = url + "?q=" + encodeURIComponent(inputObj.value);
			//theForm.method = "GET";
			//theForm.action = url + "?q=" + encodeURIComponent(inputObj.value);
			//theForm.submit();
			return false;
		}
		return true;
	},

	AlternateForm: function (method, url, validation, validationGroup) {
		if (method || url) {
			if (validation) {
				if (typeof (Page_ClientValidate) == 'function') {
					if (!Page_ClientValidate(validationGroup))
						return false;
				}
			}
		}
		else
			return true;
		if (method)
			theForm.method = method;
		if (url)
			theForm.action = url;
		this.RemoveAspxFields();
		return true;
	},

	Reload: function () {
		document.location = document.location;
	},


	FormSubmit: function (ev) {
		// likeness from WebForm.js
		var lastFocus = theForm.elements["__LASTFOCUS"];
		if ((typeof (lastFocus) != "undefined") && (lastFocus != null)) {
			if (lastFocus.value != null && lastFocus.value.length > 0)
				return true;
			if (typeof (document.activeElement) != "undefined") {
				var active = document.activeElement;
				if ((typeof (active.id) != "undefined") && (active.id != null) && (active.id.length > 0))
					lastFocus.value = active.id;
				else if (typeof (active.name) != "undefined")
					lastFocus.value = active.name;
			}
		}
		return true;
	},

	OnEnterTab: function (ev) {
		if (event.keyCode != 13)
			return;
		event.keyCode = 9; // Only works in IE
		return true;
	},

	OnEnterClick: function (ev, obj) {
		this.OnKeyClick(ev, obj, 13);
	},

	OnKeyClick: function (ev, obj, keyCode) {
		if (typeof (obj) == "string")
			obj = document.getElementById(obj);
		if (!obj)
			return;
		var key = ev.which != undefined ? ev.which : ev.keyCode;
		if (key != keyCode)
			return;
		ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
		ev.stopPropagation ? ev.stopPropagation() : ev.cancelBubble = true;
		//this.FireEvent(obj, "click");
		obj.click();
	},

	FireEvent: function (obj, name) {
		if (typeof (obj) == "string")
			obj = document.getElementById(obj);
		if (!obj)
			return;
		if (obj.tagName == "A") {
			if (obj.href.substring(0, 11) == "javascript:") {
				var code = unescape(obj.href.substring(11));
				window.setTimeout(code, 0);
				return true;
			}
		}
		if (!document.createEvent)
			return obj.fireEvent("on" + name);
		else {
			// IE9 and others
			var evt = document.createEvent("MouseEvents");
			evt.initMouseEvent(name, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
			return !obj.dispatchEvent(evt);
		}
	},

	ClearItems: function (id) {
		// Only supports RadComboBox for now
		var elm = $find(id);
		elm.clearItems();
		elm.didLoad = false;
		//var items = elm.get_items();
		//elm.clear();
	},

	CollectFormItems: function (parentId, skipUnderscores) {
		if (!window.jQuery)
			alert("Missing jQuery");
		var q;
		if (parentId && parentId.length > 0)
			q = "#" + parentId + " *";
		var elements = $(q || "form").map(function () {
			return this.elements ? jQuery.makeArray(this.elements) : this;
		}).filter(function () {
			return this.name && !this.disabled &&
					(this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password|search/i.test(this.type));
		}).get();
		var formValues = [];
		//var s = "", s2 = "";
		for (var fi = 0; fi < elements.length; fi++) {
			var name = elements[fi].name;
			//s += name + "\r\n";
			if (!name || (skipUnderscores && name.indexOf("_") > -1))
				continue;
			/*
			switch (name) {
			case "__VIEWSTATE":
			case "__EVENTTARGET":
			case "__EVENTARGUMENT":
			case "__SCROLLPOSITIONX":
			case "__SCROLLPOSITIONY":
			case "__PREVIOUSPAGE":
			case "__EVENTVALIDATION":
			continue;
			}*/
			var value = elements[fi].value;
			//if (!value)
			//	continue;
			var type = elements[fi].type;
			switch (type) {
				case "submit":
					continue;
				case "checkbox":
					if (!elements[fi].checked)
						continue;
					else
						value = "true";
					break;
			}
			//s2 += name + "(" + type + "): " + value + "\r\n";
			formValues.push({ Key: name, Value: value });
		}
		//alert(s); alert(s2);
		return formValues;
	},

	RemoveSystemFields: function () {
		//try {
		var fields = [];
		for (var i = theForm.elements.length - 1; i >= 0; i--) {
			var field = theForm.elements[i];
			/*if (!field.value || field.value.lenth == 0)
			fields.push(field.name);
			else*/
			if (field.name.substring(0, 2) == "__")
				fields.push(field.name);
			else if (field.name.indexOf("_ClientState") > -1 || field.name.indexOf("_CpoS") > -1 /*|| field.name.indexOf("_CpoS") > -1*/)
				fields.push(field.name);
		}
		for (var i = 0; i < fields.length; i++)
			this.RemoveField(fields[i]);
		this.RemoveField("ScriptManager_HiddenField");
		//} catch (ex) {
		//}
	},

	RemoveField: function (name, setTo) {
		var obj = theForm.elements[name];
		if (!obj)
			return;
		var parent = obj.parentNode;
		parent.removeChild(obj);
		theForm.elements[name] = "";
	},

	NumericInput: function (ev, groupAcsii, decAcsii) {
		if (!groupAcsii) groupAcsii == 44;
		if (!decAcsii) decAcsii == 46;
		var key = ev.which != undefined ? ev.which : ev.keyCode;
		//alert(ev.which + "," + ev.keyCode);
		if (key == groupAcsii) {
			if (ev.target && ev.target.value != undefined && ev.target.value.length == 0)
				return this.PreventDefault(ev);
			return true;
		}
		if ((key >= 48 && key <= 57) || key == decAcsii || key == 8 || key == 9 || key == 13 || key == 0)
			return true;
		return this.PreventDefault(ev);
	},
	/*
	StretchElement: function(obj) {
	if (typeof (obj) == "string")
	obj = document.getElementById(obj);
	if (!obj)
	return;
	if (!obj.orgHeight)
	obj.orgHeight = obj.offsetHeight;
	//if (this.IE6)
	//	obj.style.height = "30px";
	var h = 0;
	var child;
	var length = obj.parentNode.childNodes.length;
	for (var i = 0; i < length; i++) {
	child = obj.parentNode.childNodes[i];
	if (child != obj && child.nodeName.toLowerCase() != "script")
	if (child.offsetHeight)
	h += child.offsetHeight;
	}
	h = obj.parentNode.offsetHeight - h;
	if (h < 0 || h < obj.orgHeight)
	return;

	// e.g. tabstrips
	obj.style.height = h + "px";
	},
	
	MainOnWindowResize: function() {
	if (this.mainStretchId)
	this.StretchElement(this.mainStretchId);

	if (this.strechObj && (this.stretchBottomObj || this.stretchTopObj)) {
	var height = parseInt(document.body.clientHeight - (this.stretchBottomObj ? this.stretchBottomObj.offsetHeight : 0) -
	(this.stretchTopObj ? this.stretchTopObj.offsetHeight : 0));
	if (height > 0)
	this.strechObj.style.height = height + "px";
	}
	},

	SetStretchBottom: function(strechId, stretchBottomId, stretchTopId) {
	this.strechObj = document.getElementById(strechId);
	this.stretchBottomObj = document.getElementById(stretchBottomId);
	this.stretchTopObj = document.getElementById(stretchTopId);
	var instance = this;
	this.RegisterEvent("resize", function() { instance.MainOnWindowResize() });
	this.MainOnWindowResize();
	},
	*/
	ScrollbarSize: function () {
		var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;" /></div>');
		$(document.body).append(div);
		var w1 = $('div', div).innerWidth();
		div.css('overflow-y', 'auto');
		var w2 = $('div', div).innerWidth();
		$(div).remove();
		return (w1 - w2);
	},

	Alert: function () {
		// HACK: Should cast server error..
		alert("CPO ERROR: To use this function - add a window to the page.");
	},
	Prompt: function () {
		this.Alert();
	},
	Confirm: function () {
		this.Alert();
	},

	RangeValidatorEvaluateIsValid: function (val) {
		//alert("A: " + val.groupchar);
		var value = ValidatorGetValue(val.controltovalidate);
		if (ValidatorTrim(value).length == 0)
			return false;
		value = value.replace(new RegExp("\\" + val.groupchar, "g"), "");
		return (ValidatorCompare(value, val.minimumvalue, "GreaterThanEqual", val) &&
						ValidatorCompare(value, val.maximumvalue, "LessThanEqual", val));
	},

	CallSys: function (callId, arg, noAjax, targetId) {
		if (arg) {
			objArg = document.getElementById('__CPOARG');
			if (!objArg) {
				alert("No actions registered");
				return;
			}
			objArg.value = arg;
		}
		if (!noAjax) {
			var ajaxManager = $find("CpoAjaxManager");
			if (ajaxManager) {
				if (targetId)
					ajaxManager.ajaxRequestWithTarget(targetId, callId);
				else
					ajaxManager.ajaxRequest(callId);
				return;
			}
		}
		__doPostBack("cpoSysEvent", callId);
	},

	StopKeepAlive: function (interval, callback) {
		if (this.keepAliveThread)
			window.clearInterval(this.keepAliveThread);
		this.keepAliveThread = null;
	},

	// Cpo.StartKeepAlive(5, function(httpReq) { alert("Server status "+ httpReq.status +" said: "+ httpReq.responseText); });
	StartKeepAlive: function (interval, callback) {
		if (this.keepAliveThread)
			return;
		if (!interval)
			interval = 60 * 5;
		this.keepAliveThread = window.setInterval(this.CreateDelegate(this, function () {
			this.ServerTalk("ping", callback);
		}), interval * 1000);
	},

	ServerTalk: function (cmd, callback) {
		if (!this.reqCounter)
			this.reqCounter = 1;
		else
			this.reqCounter++;
		if (window.XMLHttpRequest)
			this.httpReq = new XMLHttpRequest();
		else if (window.ActiveXObject)
			this.httpReq = new ActiveXObject("Microsoft.XMLHTTP");
		this.httpReq.open("GET", "/cposervices/rest.svc/talk?rc=" + this.reqCounter + "&cmd=" + cmd, true);
		this.httpReq.onreadystatechange = this.CreateDelegate(this, function () {
			if (this.httpReq.readyState == 4) {
				if (callback) {
					var retVal = callback(this.httpReq);
					if (retVal != undefined && !retVal)
						window.clearInterval(this.keepAliveThread);
				}
			}
		});
		this.httpReq.send(null);
	},

	Serialize: function (obj) {
		// TODO: test for native: window.JSON
		// TODO: Check for ajax avail and if obj is HTML (jquery = .serialize()).
		return Sys.Serialization.JavaScriptSerializer.serialize(obj);
	},

	DeSerialize: function (stringVal) {
		// TODO: test for native: window.JSON
		return Sys.Serialization.JavaScriptSerializer.deserialize(stringVal);
	},

	InsertAtCursor: function (elm, value) {
		if (document.selection) {
			elm.focus();
			sel = document.selection.createRange();
			sel.text = value;
		}
		else if (elm.selectionStart || elm.selectionStart == '0') {
			var startPos = elm.selectionStart;
			var endPos = elm.selectionEnd;
			restoreTop = elm.scrollTop;

			elm.value = elm.value.substring(0, startPos) + value + elm.value.substring(endPos, elm.value.length);

			elm.selectionStart = startPos + value.length;
			elm.selectionEnd = startPos + value.length;

			if (restoreTop > 0)
				elm.scrollTop = restoreTop;
		}
	},


	// -------------
	// System
	// -------------

	setField: function (name, value) {
		var obj = document.getElementById(name);
		if (!obj)
			return;
		obj.value = value;
	},

	navPage: function (group, relative, index, sort) {
		this.navSetDidNav(group);
		var obj = document.getElementById("index" + group);
		if (!obj)
			return;
		if (relative) {
			var pageNumber = parseInt("0" + obj.value, 10);
			if (pageNumber == 0)
				pageNumber = 1;
			if (pageNumber < 0)
				return;
			obj.value = pageNumber + index;
		}
		else
			obj.value = index;
		if (sort)
			this.setField("sort" + group, sort);
		//__doPostBack(null, null);
	},

	navSetDidNav: function (group) {
		var obj = document.getElementById(group + "_NDN");
		if (obj)
			obj.value = "1";
	},



	/*
	crudMode: function(id, mode) {
	if (mode != "save") {
	if (!navSetDidNav(id))
	return false;
	}
	var obj = document.getElementById(id + "_CRUDM");
	if (obj == null)
	return;
	obj.value = mode;
	__doPostBack(null, null);
	},
	*/
	// internal

	mainOnLoad: function () {
		/*if (window.WebForm_FireDefaultButton) {
		var org = window.WebForm_FireDefaultButton;
		window.WebForm_FireDefaultButton = function (event, target) {
		return org(event, target);
		}
		}*/

		if (window.radalert) {
			this.Alert = window.radalert;
			this.Prompt = window.radprompt;
			this.Confirm = window.radconfirm;
		}

		if (typeof (Sys) == "object" && Sys.WebForms)
			Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.onEndRequest);

		this.sysOverrideRad();
		/*
		this.mainStretchId = document.body.getAttribute("stretch");
		if (this.mainStretchId) {
		this.mainStretchId = document.getElementById(this.mainStretchId);
		if (this.mainStretchId) {
		this.MainOnWindowResize();
		var instance = this;
		this.RegisterEvent("resize", function() { instance.MainOnWindowResize() });
		}
		}
		*/
	},

	sysOverrideRad: function () {
		if (typeof (Telerik) != 'undefined') {
			if (Telerik.Web.UI.WebServiceLoader) {
				Telerik.Web.UI.WebServiceLoader.prototype._serializeDictionaryAsKeyValuePairs = function (dictionary) {
					return dictionary;
				}
			}

			if (Telerik.Web.UI.WebServiceLoader) {
				Telerik.Web.UI.WebServiceLoader.prototype._serializeDictionaryAsKeyValuePairs = function (dictionary) {
					return dictionary;
				}
			}

			/*if (Telerik.Web.UI.RadAjaxControl) {
			Telerik.Web.UI.RadAjaxControl.prototype._old_RestorePostData = Telerik.Web.UI.RadAjaxControl.prototype.RestorePostData;
			Telerik.Web.UI.RadAjaxControl.prototype.RestorePostData = function (element, value) {
			alert(element.type);
			if (element.tagName.toLowerCase() == "input" && (element.type.toLowerCase() == "number"))
			element.value = value;
			return this._old_RestorePostData(eventName, value);
			}
			}*/
		}

		// Override WebForm_InitCallback to enable other input types HTML5-override
		/*if (window.WebForm_InitCallback)
		window.WebForm_InitCallback = function WebForm_InitCallback() {
		var count = theForm.elements.length;
		var element;
		for (var i = 0; i < count; i++) {
		element = theForm.elements[i];
		var tagName = element.tagName.toLowerCase();
		if (tagName == "input") {
		var type = element.type;
		if (type == "number") {
		alert(element.value);
		}
		if ((type == "text" || type == "hidden" || type == "password" ||
		type == "number" ||
		((type == "checkbox" || type == "radio") && element.checked)) &&
		(element.id != "__EVENTVALIDATION")) {
		WebForm_InitCallbackAddField(element.name, element.value);
		}
		}
		else if (tagName == "select") {
		var selectCount = element.options.length;
		for (var j = 0; j < selectCount; j++) {
		var selectChild = element.options[j];
		if (selectChild.selected == true) {
		WebForm_InitCallbackAddField(element.name, element.value);
		}
		}
		}
		else if (tagName == "textarea") {
		WebForm_InitCallbackAddField(element.name, element.value);
		}
		}
		};*/

		//Sys.Application.add_init(function () { alert(window.Sys$WebForms$PageRequestManager$_onFormSubmit); });

		// HACK: SSK34343 - only needed by Android now?
		//Sys.WebForms.PageRequestManager.prototype._onFormSubmit = this.__onFormSubmit;

	},


	// HACK: SSK34343
	/*
	__onFormSubmit: function (evt) {
	var i, l, continueSubmit = true,
	isCrossPost = this._isCrossPost;
	this._isCrossPost = false;
	if (this._onsubmit) {
	continueSubmit = this._onsubmit();
	}
	if (continueSubmit) {
	for (i = 0, l = this._onSubmitStatements.length; i < l; i++) {
	if (!this._onSubmitStatements[i]()) {
	continueSubmit = false;
	break;
	}
	}
	}
	if (!continueSubmit) {
	if (evt) {
	evt.preventDefault();
	}
	return;
	}
	var form = this._form;
	if (isCrossPost) {
	return;
	}
	if (this._activeDefaultButton && !this._activeDefaultButtonClicked) {
	this._onFormElementActive(this._activeDefaultButton, 0, 0);
	}
	if (!this._postBackSettings || !this._postBackSettings.async) {
	return;
	}
	var formBody = new Sys.StringBuilder(),
	count = form.elements.length,
	panelID = this._createPanelID(null, this._postBackSettings);
	formBody.append(panelID);

	for (i = 0; i < count; i++) {
	var element = form.elements[i];
	var name = element.name;
	if (typeof (name) === "undefined" || (name === null) || (name.length === 0) || (name === this._scriptManagerID)) {
	continue;
	}
	var tagName = element.tagName.toUpperCase();
	if (tagName === 'INPUT') {
	var type = element.type;
	if ((type === 'text') ||
	(type === 'password') ||
	(type === 'number' || type === 'url' || type === 'email') || // AMA OVERRIDE
	(type === 'hidden') ||
	(((type === 'checkbox') || (type === 'radio')) && element.checked)) {
	formBody.append(encodeURIComponent(name));
	formBody.append('=');
	formBody.append(encodeURIComponent(element.value));
	formBody.append('&');
	}
	}
	else if (tagName === 'SELECT') {
	var optionCount = element.options.length;
	for (var j = 0; j < optionCount; j++) {
	var option = element.options[j];
	if (option.selected) {
	formBody.append(encodeURIComponent(name));
	formBody.append('=');
	formBody.append(encodeURIComponent(option.value));
	formBody.append('&');
	}
	}
	}
	else if (tagName === 'TEXTAREA') {
	formBody.append(encodeURIComponent(name));
	formBody.append('=');
	formBody.append(encodeURIComponent(element.value));
	formBody.append('&');
	}
	}
	formBody.append("__ASYNCPOST=true&");
	if (this._additionalInput) {
	formBody.append(this._additionalInput);
	this._additionalInput = null;
	}

	var request = new Sys.Net.WebRequest();
	var action = form.action;
	if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
	var fragmentIndex = action.indexOf('#');
	if (fragmentIndex !== -1) {
	action = action.substr(0, fragmentIndex);
	}
	var queryIndex = action.indexOf('?');
	if (queryIndex !== -1) {
	var path = action.substr(0, queryIndex);
	if (path.indexOf("%") === -1) {
	action = encodeURI(path) + action.substr(queryIndex);
	}
	}
	else if (action.indexOf("%") === -1) {
	action = encodeURI(action);
	}
	}
	request.set_url(action);
	request.get_headers()['X-MicrosoftAjax'] = 'Delta=true';
	request.get_headers()['Cache-Control'] = 'no-cache';
	request.set_timeout(this._asyncPostBackTimeout);
	request.add_completed(Function.createDelegate(this, this._onFormSubmitCompleted));
	request.set_body(formBody.toString());
	var panelsToUpdate, eventArgs, handler = this._get_eventHandlerList().getHandler("initializeRequest");
	if (handler) {
	panelsToUpdate = this._postBackSettings.panelsToUpdate;
	eventArgs = new Sys.WebForms.InitializeRequestEventArgs(request, this._postBackSettings.sourceElement, panelsToUpdate);
	handler(this, eventArgs);
	continueSubmit = !eventArgs.get_cancel();
	}
	if (!continueSubmit) {
	if (evt) {
	evt.preventDefault();
	}
	return;
	}

	if (eventArgs && eventArgs._updated) {
	panelsToUpdate = eventArgs.get_updatePanelsToUpdate();
	request.set_body(request.get_body().replace(panelID, this._createPanelID(panelsToUpdate, this._postBackSettings)));
	}
	this._scrollPosition = this._getScrollPosition();
	this.abortPostBack();
	handler = this._get_eventHandlerList().getHandler("beginRequest");
	if (handler) {
	eventArgs = new Sys.WebForms.BeginRequestEventArgs(request, this._postBackSettings.sourceElement,
	panelsToUpdate || this._postBackSettings.panelsToUpdate);
	handler(this, eventArgs);
	}

	if (this._originalDoCallback) {
	this._cancelPendingCallbacks();
	}
	this._request = request;
	this._processingRequest = false;
	request.invoke();
	if (evt) {
	evt.preventDefault();
	}
	},
	*/

	/*onAjaxRequestStart: function (sender, args) {
	},

	onAjaxResponseEnd: function (sender, args) {
	},*/

	onEndRequest: function (sender, args) {
		// DEVNOTE: KKEPA663R
		var error = args.get_error();
		if (error != null) {
			args.set_errorHandled(true);
			var msg = error.message.replace("Sys.WebForms.PageRequestManagerServerErrorException: ", "");
			if (typeof (CpoAjaxError) == "function")
				CpoAjaxError(msg, sender, args);
			else
				alert(msg);
		}
	},

	debug: function (obj, newWindow) {
		var result;
		for (var name in obj) {
			try {
				result = (result ? result + "\r" : "") + name + ":" + (name.length > 15 ? "\t" : (name.length > 7 ? "\t\t" : "\t\t\t")) + obj[name];
			} catch (e) {
				result = (result ? result + "\r" : "") + name + ": ERROR: " + e.message;
			}
		}
		if (newWindow)
			this.text(result);
		else
			alert(result);
		return obj;
	},

	startZoomListener: function () {
		if (this.threadZoomListener)
			return;
		this.threadZoomListener = setInterval(this.execZoomListener, 2000);
	},

	execZoomListener: function () {
		var width = $(window).width();
		if (!this.lastZoomWidth) {
			this.lastZoomWidth = width;
			return;
		}
		if (this.lastZoomWidth == width)
			return;
		this.lastZoomWidth = width;
		$(".zoomListener").trigger("cpoEventZoom");
	}

};

Cpo.init();

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
