
function Anthem_AddEvent(obj, evType, fn, useCapture) {
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent) {
		var r = obj.attachEvent("on" + evType, fn);
		return r;
	} else {
		alert("Anthem_AddEvent could not add event!");
	}
}

function Anthem_GetXMLHttpRequest() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else {
		if (window.Anthem_XMLHttpRequestProgID) {
			return new ActiveXObject(window.Anthem_XMLHttpRequestProgID);
		} else {
			var progIDs = ["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
			for (var i = 0; i < progIDs.length; ++i) {
				var progID = progIDs[i];
				try {
					var x = new ActiveXObject(progID);
					window.Anthem_XMLHttpRequestProgID = progID;
					return x;
				} catch (e) {
				}
			}
		}
	}
	return null;
}

function Anthem_CallBack(url, target, id, method, args, clientCallBack, clientCallBackArg, includeControlValuesWithCallBack, updatePageAfterCallBack) {
	if (window.Anthem_PreCallBack) {
		var preCallBackResult = Anthem_PreCallBack();
		if (!(typeof preCallBackResult == "undefined" || preCallBackResult)) {
			if (window.Anthem_CallBackCancelled) {
				Anthem_CallBackCancelled();
			}
			return null;
		}
	}
	var x = Anthem_GetXMLHttpRequest();
	var result = null;
	if (!x) {
		result = { "value": null, "error": "NOXMLHTTP" };
		Anthem_DebugError(result.error);
		if (window.Anthem_Error) {
			Anthem_Error(result);
		}
		if (clientCallBack) {
			clientCallBack(result, clientCallBackArg);
		}
		return result;
	}
	x.open("POST", url ? url : Anthem_DefaultURL, clientCallBack ? true : false);
	x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
	x.setRequestHeader("Accept-Encoding", "gzip, deflate");
	if (clientCallBack) {
		x.onreadystatechange = function() {
			if (x.readyState != 4) {
				return;
			}
			Anthem_DebugResponseText(x.responseText);
			result = Anthem_GetResult(x);

			if (result.error) {
				Anthem_DebugError(result.error);
				if (window.Anthem_Error) {
					Anthem_Error(result);
				}
			}
			if (updatePageAfterCallBack) {
				Anthem_UpdatePage(result);
			}
			Anthem_EvalClientSideScript(result);
			clientCallBack(result, clientCallBackArg);
			x = null;
			if (window.Anthem_PostCallBack) {
				Anthem_PostCallBack();
			}
		}
	}
    var encodedData = "";
    if (target == "Page") {
        encodedData += "&Anthem_PageMethod=" + method;
    } else if (target == "MasterPage") {
        encodedData += "&Anthem_MasterPageMethod=" + method;
    } else if (target == "Control") {
        encodedData += "&Anthem_ControlID=" + id.split(":").join("_");
        encodedData += "&Anthem_ControlMethod=" + method;
    }
	if (args) {
		for (var argsIndex = 0; argsIndex < args.length; ++argsIndex) {
			if (args[argsIndex] instanceof Array) {
				for (var i = 0; i < args[argsIndex].length; ++i) {
					encodedData += "&Anthem_CallBackArgument" + argsIndex + "=" + encodeURIComponent(args[argsIndex][i]);
				}
			} else {
				encodedData += "&Anthem_CallBackArgument" + argsIndex + "=" + encodeURIComponent(args[argsIndex]);
			}
		}
	}
	if (updatePageAfterCallBack) {
		encodedData += "&Anthem_UpdatePage=true";
	}
	if (includeControlValuesWithCallBack) {
		var form = document.getElementById(Anthem_FormID);
		if (form != null) {
			for (var elementIndex = 0; elementIndex < form.length; ++elementIndex) {
				var element = form.elements[elementIndex];
				if (element.name) {
					var elementValue = null;
					if (element.nodeName == "INPUT") {
						var inputType = element.getAttribute("TYPE").toUpperCase();
						if (inputType == "TEXT" || inputType == "PASSWORD" || inputType == "HIDDEN") {
							elementValue = element.value;
						} else if (inputType == "CHECKBOX" || inputType == "RADIO") {
							if (element.checked) {
								elementValue = element.value;
							}
						}
					} else if (element.nodeName == "SELECT") {
						if (element.multiple) {
							elementValue = [];
							for (var i = 0; i < element.length; ++i) {
								if (element.options[i].selected) {
									elementValue.push(element.options[i].value);
								}
							}
						} else {
							elementValue = element.value;
						}
					} else if (element.nodeName == "TEXTAREA") {
						elementValue = element.value;
					}
					if (elementValue instanceof Array) {
						for (var i = 0; i < elementValue.length; ++i) {
							encodedData += "&" + element.name + "=" + encodeURIComponent(elementValue[i]);
						}
					} else if (elementValue != null) {
						encodedData += "&" + element.name + "=" + encodeURIComponent(elementValue);
					}
				}
			}
			// ASP.NET 1.1 won't fire any events if neither of the following
			// two parameters are not in the request so make sure they're
			// always in the request.
			if (typeof form.__VIEWSTATE == "undefined") {
				encodedData += "&__VIEWSTATE=";
			}
			if (typeof form.__EVENTTARGET == "undefined") {
				encodedData += "&__EVENTTARGET=";
			}
		}
	}
	Anthem_DebugRequestText(encodedData.split("&").join("\n&"));
	x.send(encodedData);
	
	if (!clientCallBack) {
		Anthem_DebugResponseText(x.responseText);
		result = Anthem_GetResult(x);
		if (result.error) {
			Anthem_DebugError(result.error);
			if (window.Anthem_Error) {
				Anthem_Error(result);
			}
		}
		if (updatePageAfterCallBack) {
			Anthem_UpdatePage(result);
		}
		Anthem_EvalClientSideScript(result);
	}

	// jcm for some reason login errors sometimes look like this 
	//if (result != null && ((result.error == "BADRESPONSE" && result.responseText.indexOf("Password") > 0) || result.error == "LOGIN"))
	//{
	//debugger;
	    // reload will force the login redirect to happen
	  //  window.location.reload( true );
	//}
	return result;
}

function Anthem_GetResult(x) {
	var result = { "value": null, "error": null };
	var responseText = x.responseText;
	try {
		result = eval("(" + responseText + ")");
	} catch (e) {
		if (responseText.length == 0) {
			result.error = "NORESPONSE";
		} else {
			result.error = "BADRESPONSE";
			result.responseText = responseText;
		}
	}
	return result;
}

function Anthem_SetHiddenInputValue(form, name, value) {
    var input = null;
    if (form[name]) {
        input = form[name];
    } else {
        input = document.createElement("input");
        input.setAttribute("name", name);
        input.setAttribute("type", "hidden");
    }
    input.setAttribute("value", value);
    var parentElement = input.parentElement ? input.parentElement : input.parentNode;
    if (parentElement == null) {
        form.appendChild(input);
        form[name] = input;
    }
}

function Anthem_RemoveHiddenInput(form, name) {
    var input = form[name];
    var parentElement = input.parentElement ? input.parentElement : input.parentNode;
    if (input && parentElement == form) {
        form[name] = null;
        form.removeChild(input);
    }
}

function Anthem_FireEvent(eventTarget, eventArgument, clientCallBack, clientCallBackArg, includeControlValuesWithCallBack, updatePageAfterCallBack) {
	
	var form = document.getElementById(Anthem_FormID);
	Anthem_SetHiddenInputValue(form, "__EVENTTARGET", eventTarget);
	Anthem_SetHiddenInputValue(form, "__EVENTARGUMENT", eventArgument);
	Anthem_CallBack(null, null, null, null, null, clientCallBack, clientCallBackArg, includeControlValuesWithCallBack, updatePageAfterCallBack);
	form.__EVENTTARGET.value = "";
	form.__EVENTARGUMENT.value = "";
}

function Anthem_UpdatePage(result) {
	var form = document.getElementById(Anthem_FormID);
	if (result.viewState) {
		Anthem_SetHiddenInputValue(form, "__VIEWSTATE", result.viewState);
	}
	if (result.viewStateEncrypted) {
		Anthem_SetHiddenInputValue(form, "__VIEWSTATEENCRYPTED", result.viewStateEncrypted);
	}
	if (result.eventValidation) {
		Anthem_SetHiddenInputValue(form, "__EVENTVALIDATION", result.eventValidation);
	}
	if (result.controls) {
		for (var controlID in result.controls) {
			var containerID = "Anthem_" + controlID.split("$").join("_") + "__";
			var control = document.getElementById(containerID);
			if (control) {
				control.innerHTML = result.controls[controlID];
				if (result.controls[controlID] == "") {
					control.style.display = "none";
				} else {
					control.style.display = "";
				}
			}
		}
	}
	if (result.pagescript) {
		for (var i = 0; i < result.pagescript.length; ++i) {
			try {
			    var script = document.createElement('script');
			    script.type = 'text/javascript';
			    if (script.canHaveChildren ) {
			        script.appendChild(document.createTextNode(result.pagescript[i]));
			    } else {
			        script.text = result.pagescript[i];
			    }
				document.getElementsByTagName("head")[0].appendChild(script);
			} catch (e) {
			    Anthem_DebugError("Error adding page script to head. " + e.name + ": " + e.message);
			}
		}
	}
}

function Anthem_EvalClientSideScript(result) {
	if (result.script) {
		for (var i = 0; i < result.script.length; ++i) {
			try {
				eval(result.script[i]);
			} catch (e) {
				alert("Error evaluating client-side script!\n\nScript: " + result.script[i] + "\n\nException: " + e);
			}
		}
	}
}

function Anthem_DebugRequestText(text) {
}

function Anthem_DebugResponseText(text) {
}

function Anthem_DebugError(text) {
}

//Fix for bug #1429412, "Reponse callback returns previous response after file push".
//see http://sourceforge.net/tracker/index.php?func=detail&aid=1429412&group_id=151897&atid=782464
function Anthem_Clear__EVENTTARGET()
{
	var form = document.getElementById(Anthem_FormID);
	Anthem_SetHiddenInputValue(form, "__EVENTTARGET", "");
}

function Anthem_InvokePageMethod(methodName, args, callBack, context) {
	Anthem_Clear__EVENTTARGET(); // fix for bug #1429412
    return Anthem_CallBack(null, "Page", null, methodName, args, callBack, context, true, true);
}

function Anthem_InvokeMasterPageMethod(methodName, args, callBack, context) {
	Anthem_Clear__EVENTTARGET(); // fix for bug #1429412
    return Anthem_CallBack(null, "MasterPage", null, methodName, args, callBack, context, true, true);
}

function Anthem_InvokeControlMethod(id, methodName, args, callBack, context) {
	Anthem_Clear__EVENTTARGET(); // fix for bug #1429412
    return Anthem_CallBack(null, "Control", id, methodName, args, callBack, context, true, true);
}

function GetLabelText(id) {
    var labels = document.getElementsByTagName('label');
    for (var i = 0; i < labels.length; i++) {
        if (labels[i].htmlFor == id) {
            return labels[i].innerHTML;
        }
    }
    return null;
}

function SetLabelText(id, text) {
    var labels = document.getElementsByTagName('label');
    for (var i = 0; i < labels.length; i++) {
        if (labels[i].htmlFor == id) {
            labels[i].innerHTML = text;
            return;
        }
    }
}

// jcm added preCallBackFunction and postCallBackFunction to allow gridview to using "searching" label during paging/sorting
function Anthem_FireEvent(eventTarget, eventArgument, clientCallBack, clientCallBackArg, includeControlValuesWithCallBack, updatePageAfterCallBack,	preCallBackFunction,postCallBackFunction) {
	var preCallBackResult = true;
	if (preCallBackFunction) {
		preCallBackResult = preCallBackFunction();
	}
	var form = document.getElementById(Anthem_FormID);
	Anthem_SetHiddenInputValue(form, "__EVENTTARGET", eventTarget);
	Anthem_SetHiddenInputValue(form, "__EVENTARGUMENT", eventArgument);

	//Anthem_CallBack(null, null, null, null, null, clientCallBack, clientCallBackArg, includeControlValuesWithCallBack, updatePageAfterCallBack);
	var postCallBackResult = true;
	if (postCallBackFunction) {
		Anthem_CallBack(null, null, null, null, null, postCallBackFunction, clientCallBackArg, includeControlValuesWithCallBack, updatePageAfterCallBack);
	}
	else {
	    Anthem_CallBack(null, null, null, null, null, clientCallBack, clientCallBackArg, includeControlValuesWithCallBack, updatePageAfterCallBack);
	}
	
	form.__EVENTTARGET.value = "";
	form.__EVENTARGUMENT.value = "";
}

function Anthem_FireCallBackEvent(
	control,
	e,
	eventTarget,
	eventArgument,
	causesValidation,
	validationGroup,
	imageUrlDuringCallBack,
	textDuringCallBack,
	enabledDuringCallBack,
	preCallBackFunction,
	postCallBackFunction,
	callBackCancelledFunction,
	includeControlValuesWithCallBack,
	updatePageAfterCallBack
) {
	var preCallBackResult = true;
	if (preCallBackFunction) {
		preCallBackResult = preCallBackFunction(control);
	}
	if (typeof preCallBackResult == "undefined" || preCallBackResult) {
		var valid = true;
		if (causesValidation && typeof Page_ClientValidate == "function") {
			valid = Page_ClientValidate(validationGroup);
		}
		if (valid) {
			var inputType = control.getAttribute("TYPE");
			inputType = (inputType == null) ? '' : inputType.toUpperCase();
			var parentElement = null;
			var text = '';
			if (imageUrlDuringCallBack || textDuringCallBack) {
			    if (control.nodeName == "INPUT") {
			        if (inputType == "CHECKBOX" || inputType == "RADIO" || inputType == "TEXT") {
			            text = GetLabelText(control.id);
			            SetLabelText(control.id, textDuringCallBack);
			        }
			        else if (inputType == "IMAGE") {
	                    var form = document.getElementById(Anthem_FormID);
	                    if (e.offsetX)
	                    {
	                        Anthem_SetHiddenInputValue(form, eventTarget + ".x", e.offsetX);
	                        Anthem_SetHiddenInputValue(form, eventTarget + ".y", e.offsetY);
	                    }
	                    else
	                    {
	                        Anthem_SetHiddenInputValue(form, eventTarget + ".x", e.clientX - control.offsetLeft + 1);
	                        Anthem_SetHiddenInputValue(form, eventTarget + ".y", e.clientY - control.offsetTop + 1);
	                    }
			            if (imageUrlDuringCallBack) {
			                text = control.src;
			                control.src = imageUrlDuringCallBack;
			            }
			            else {
			                parentElement = control.parentElement ? control.parentElement : control.parentNode;
			                if (parentElement) {
			                    text = parentElement.innerHTML;
			                    parentElement.innerHTML = textDuringCallBack;
			                }
			            }
			        }
			        else if (inputType == "SUBMIT") {
			            text = control.value;
			            control.value = textDuringCallBack;
			        }
			    }
			    else if (control.nodeName == "SELECT") {
			        text = GetLabelText(control.id);
			        SetLabelText(control.id, textDuringCallBack);
			    }
			    else {
			        text = control.innerHTML;
				    control.innerHTML = textDuringCallBack;
				}
			}
			var enabled = !control.disabled;
			control.disabled = !enabledDuringCallBack;
			Anthem_FireEvent(
				eventTarget,
				eventArgument,
				function(result) {
					if (postCallBackFunction) {
						postCallBackFunction(control);
					}
					control.disabled = !enabled;
					if (imageUrlDuringCallBack || textDuringCallBack) {
					    if (control.nodeName == "INPUT") {
					        if (inputType == "CHECKBOX" || inputType == "RADIO" || inputType == "TEXT")
					            SetLabelText(control.id, text);
					        else if (inputType == "IMAGE") {
	                            Anthem_RemoveHiddenInput(form, eventTarget + ".x");
	                            Anthem_RemoveHiddenInput(form, eventTarget + ".y");
					            if (imageUrlDuringCallBack)
					                control.src = text;
					            else
					                parentElement.innerHTML = text;
					        }
					        else if (inputType == "SUBMIT")
					            control.value = text;
					    }
					    else if (control.nodeName == "SELECT") {
					        SetLabelText(control.id, text);
					    }
					    else {
					        control.innerHTML = text;
					    }
					}
				},
				null,
				includeControlValuesWithCallBack,
				updatePageAfterCallBack
			);
		}
	} else if (callBackCancelledFunction) {
		callBackCancelledFunction(control);
	}
}

function AnthemLinkButton_Click(button, id, textDuringCallBack, enabledDuringCallBack, preCallBackFunction, postCallBackFunction, callBackCancelledFunction, includeControlValuesWithCallBack, updatePageAfterCallBack) {
	var preCallBackResult = true;
	if (preCallBackFunction) {
		preCallBackResult = preCallBackFunction(button);
	}
	if (typeof preCallBackResult == "undefined" || preCallBackResult) {
		var text = button.innerHTML;
		if (textDuringCallBack) {
			button.innerHTML = textDuringCallBack;
		}
		var enabled = !button.disabled;
		button.disabled = !enabledDuringCallBack;
		Anthem_FireEvent(
			id,
			null,
			function(result) {
				if (postCallBackFunction) {
					postCallBackFunction(button);
				}
				button.disabled = !enabled;
				button.innerHTML = text;
			},
			null,
			includeControlValuesWithCallBack,
			updatePageAfterCallBack,
			preCallBackFunction,
			postCallBackFunction	
		);
	} else if (callBackCancelledFunction) {
		callBackCancelledFunction(button);
	}
}

function Anthem_Error(result)
{
    if (result != null && ((result.error == "BADRESPONSE" && result.responseText.indexOf("Password") > 0) || result.error == "LOGIN"))
	{
	//debugger;
	    // reload will force the login redirect to happen
	    window.location.reload( true );
	}
}
function AnthemListControl_OnClick(
    e,
	causesValidation,
	validationGroup,
	textDuringCallBack,
	enabledDuringCallBack,
	preCallBackFunction,
	postCallBackFunction,
	callBackCancelledFunction,
	includeControlValuesWithCallBack,
	updatePageAfterCallBack
) {
	var target = e.target || e.srcElement;
	if (target.nodeName == "LABEL" && target.htmlFor != '')
	    return;
	var eventTarget = target.id.split("_").join("$");
	Anthem_FireCallBackEvent(
	    target, 
	    e,
	    eventTarget, 
	    '', 
	    causesValidation, 
	    validationGroup, 
	    '',
	    textDuringCallBack, 
	    enabledDuringCallBack, 
	    preCallBackFunction, 
	    postCallBackFunction, 
	    callBackCancelledFunction, 
	    true, 
	    true
	);
}
