/**
 * A common m2l library file for runtime, which all the runtime
 * files should include
 */

/**
 * List of all the js files merged
 * 1.  drp_lib.js
 * 2.  UtilityFunctions.js
 * 3.  ofr-runtime-lib.js
 */

/**
 * ----------------------------------------------------------------------------------------------------
 * included from drp_lib.js
 * ----------------------------------------------------------------------------------------------------
 */
if (!String.prototype.startsWith) {
	String.prototype.startsWith = function(prefix) {
		// return (this.substr(0, prefix.length) == prefix);
		return (this.indexOf(prefix) === 0);
	};
}

if (!String.prototype.endsWith) {
	String.prototype.endsWith = function(suffix) {
		var startPos = this.length - suffix.length;
		if (startPos < 0) {
			return false;
		}
		return (this.lastIndexOf(suffix, startPos) == startPos);
	};
}

function captureEvent() {
	var args = captureEvent.arguments;
	var len = args.length;
	var component = getElement(args[0]);

	if (component) {
		if (component.type == "text" || component.type == "textarea") {
			m2l_addEventListener(component, 'change', eval(args[1]));
			m2l_addEventListener(component, 'keyup', eval(args[1]));
		} else if (component.type == "checkbox" || component.type == "radio") {
			var components = document.getElementsByName(args[0]);

			if (components.length >= 1) {
				for ( var u = 0; u < components.length; u++) {
					m2l_addEventListener(components[u], 'click', eval(args[1]));
				}
			}
		} else if (component.type == "select-multiple") {
			// m2l_addEventListener(component, 'click', eval(args[1]));
			m2l_addEventListener(component, 'change', eval(args[1]));
		} else {
			m2l_addEventListener(component, 'change', eval(args[1]));
		}
	}
}

function getElement(element_id) {
	var element = null;

	if (document.getElementById && document.getElementById(element_id)) {
		element = document.getElementById(element_id);
	} else {
		var elements = document.getElementsByName(element_id);
		if (elements != null && elements.length > 0) {
			element = elements[0];
		}
	}
	return element;
}

function getValue(qasetId) {

	var element_id = 'q' + qasetId;
	var qsid = getElement(element_id);

	if (qsid != null) {
		var scqaid = qsid.value;

		var answer = getElement(scqaid);

		if (answer) {
			if (answer.type == "checkbox") {
				var an = document.getElementsByName(scqaid);

				if (an.length >= 1) {
					var names = new Array();
					var j = 0;
					for ( var i = 0; i < an.length; i++) {
						if (an[i].checked) {
							names[j] = an[i].value;
							j++;
						}
					}
					return names;
				}
				return 'null';
			} else if (answer.type == "radio") {
				var an = document.getElementsByName(scqaid);
				if (an.length >= 1) {
					for ( var i = 0; i < an.length; i++) {
						if (an[i].checked) {
							return an[i].value;

						}
					}
				}
				return 'null'
			} else if (answer.type == "select-multiple") {

				if (answer.selectedIndex != -1) {
					var names = new Array();
					var j = 0;
					for ( var i = 0; i < answer.options.length; i++) {
						if (answer.options[i].selected) {
							names[j] = answer.options[i].value;
							j++;
						}
					}
					return names;
				}
				return 'null';
			} else if (answer.type == "select-one") {
				return getAnswer(answer.value, '_NA');
			} else {
				return getAnswer(answer.value, '');
			}
		}
	}
}

function getAnswer(answer, regExp) {
	var ans = trim(answer);
	if (ans == regExp)
		return 'null';
	else
		return ans;
}

function m2l_show() {
	var args = m2l_show.arguments;
	var len = args.length;

	for ( var i = 0; i < len; i++) {
		var component = document.getElementsByName(args[i]);
		if (component != null) {
			if (component.length >= 1) {
				for ( var u = 0; u < component.length; u++) {
					component[u].style.display = document
							.getElementById('buttonRow').style.display;
					enable(args[i]);
				}
			}
		}
	}
}

function m2l_hideNdisable() {
	var args = m2l_hideNdisable.arguments;
	var len = args.length;

	for ( var i = 0; i < len; i++) {
		var component = document.getElementsByName(args[i]);
		if (component != null) {
			if (component.length >= 1) {
				for ( var u = 0; u < component.length; u++) {
					component[u].style.display = 'none';
					disable(args[i]);
				}
			}
		}
	}
}

function m2l_disable() {
	var args = m2l_disable.arguments;
	var len = args.length;
	for ( var i = 0; i < len; i++) {
		var component = document.getElementsByName(args[i]);
		if (component != null) {
			if (component.length >= 1) {
				for ( var u = 0; u < component.length; u++) {
					disable(args[i]);
				}
			}
		}
	}

}

function m2l_hide() {
	var args = m2l_hide.arguments;
	var len = args.length;

	for ( var i = 0; i < len; i++) {
		var component = document.getElementsByName(args[i]);
		if (component != null) {
			if (component.length >= 1) {
				for ( var u = 0; u < component.length; u++) {
					component[u].style.display = 'none';
				}
			}
		}
	}
}

function updateNode(node, flag) {
	var thisChild = node.firstChild;

	while (thisChild != null) {
		if (thisChild.nodeType == 1 && thisChild.type != null) {
			thisChild.disabled = flag;
		}
		updateNode(thisChild, flag);
		thisChild = thisChild.nextSibling;
	}
}

function disable(qasetId) {
	var parents = document.getElementsByName(qasetId);
	if (parents != null) {
		for ( var u = 0; u < parents.length; u++) {
			updateNode(parents[u], true);
		}
	}
}

function enable(qasetId) {
	var parents = document.getElementsByName(qasetId);
	if (parents != null) {
		for ( var u = 0; u < parents.length; u++) {
			updateNode(parents[u], false);
		}
	}
}

// Logging related Function

// broswer, os, version detecting code
var detect = navigator.userAgent.toLowerCase();
var OS, browser, version, total, thestring;

if (checkIt('konqueror')) {
	browser = "Konqueror";
	OS = "Linux";
} else if (checkIt('safari'))
	browser = "Safari"
else if (checkIt('omniweb'))
	browser = "OmniWeb"
else if (checkIt('opera'))
	browser = "Opera"
else if (checkIt('webtv'))
	browser = "WebTV";
else if (checkIt('icab'))
	browser = "iCab"
else if (checkIt('msie'))
	browser = "Internet Explorer"
else if (!checkIt('compatible')) {
	browser = "Netscape Navigator"
	version = detect.charAt(8);
} else
	browser = "An unknown browser";

if (!version)
	version = detect.charAt(place + thestring.length);

if (!OS) {
	if (checkIt('linux'))
		OS = "Linux";
	else if (checkIt('x11'))
		OS = "Unix";
	else if (checkIt('mac'))
		OS = "Mac"
	else if (checkIt('win'))
		OS = "Windows"
	else
		OS = "an unknown operating system";
}

function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

var isIE = (browser == "Internet Explorer");

/**
 * given an elementName, this function registers the events on the element.
 * Events are decided based on the element type
 */
function registerLogEvents(elementName) {
	var args = registerLogEvents.arguments;
	var len = args.length;
	var component = getElement(elementName);

	if (component) {
		if (component.type == "text" || component.type == "textarea") {
			addLogEventListner(component, 'blur');
		} else if (component.type == "checkbox" || component.type == "radio") {
			var components = document.getElementsByName(args[0]);
			if (components.length >= 1) {
				for ( var u = 0; u < components.length; u++) {
					addLogEventListner(component, 'click');
				}
			}
		} else if (component.type == "select-multiple") {
			// addLogEventListner(component, 'click');
			addLogEventListner(component, 'change');
		} else if (component.type == 'select-one') {
			addLogEventListner(component, 'change');
		}
	}
}

/**
 * Adds a logging event for the given element
 */
function addLogEventListner(element, eventType) {
	m2l_addEventListener(element, eventType, logEvents);
}

/**
 * Adds an event listner
 */
function m2l_addEventListener(element, eventType, listner) {
	if (isIE) {
		element.attachEvent('on' + eventType, listner);
	} else {
		element.addEventListener(eventType, listner, false);
	}
}

/**
 * Returns true if the given question is answered
 */
function isResponded(element) {
	if (element.type == "text" || element.type == "textarea") {
		return (element.value.length > 0);
	} else if (element.type == "checkbox" || element.type == "radio") {
		return element.checked;
	} else if (element.type == "select-multiple"
			|| element.type == 'select-one') {
		var selIndex = element.selectedIndex;
		if (selIndex != -1) {
			var value = element.options[selIndex].value;
			return (value.length > 0 && value != '_NA');
		}
		return false;
	}
}

function iE(lhs, rhs) {
	// for checkboxes,list it is arrya,for others it is string
	if (lhs instanceof Array) {
		if (lhs.length > 0) {
			for ( var i = 0; i < lhs.length; i++) {
				if (lhs[i].toUpperCase() == rhs.toUpperCase())
					return true;
			}
		}
		return false;
	}
	return (lhs.toUpperCase() == rhs.toUpperCase());
}
function iNE(lhs, rhs) {
	return (!iE(lhs, rhs));
	/*
	 * if(lhs instanceof Array) { if(lhs && lhs.length) { var flag = false;
	 * for(var i =0; i < lhs.length; i ++) { if(lhs[i].toUpperCase() !=
	 * rhs.toUpperCase()) { flag = true; } } return flag; } else return false; }
	 * return (lhs.toUpperCase() != rhs.toUpperCase());
	 */
}

function iGT(lhs, rhs) {
	return (parseInt(lhs) > parseInt(rhs));

}
function iGTE(lhs, rhs) {
	return (parseInt(lhs) >= parseInt(rhs));
}

function iLT(lhs, rhs) {
	return (parseInt(lhs) < parseInt(rhs));
}
function iLTE(lhs, rhs) {
	return (parseInt(lhs) <= parseInt(rhs));
}
function iN(lhs, rhs) {
	// if we entered value and deleted it is null,so added this check
	if (lhs != null && lhs.length > 0 && (lhs != 'null'))
		return false;
	else
		return true;
}

function iNN(lhs, rhs) {

	if (lhs != null && lhs.length > 0 && (lhs != 'null'))
		return true;
	else
		return false;
}
function isIn(lhs, rhs) {
	var rnames = new Array();
	var lnames = new Array();
	if (rhs.length > 0) {
		rnames = rhs.split(",");
	}
	// checking getValue() returning string or Array
	if (!(lhs instanceof Array)) {
		if (lhs) {
			lnames = lhs.split(",");
		}
	} else
		lnames = lhs;

	if (rnames.length > 0 && lnames.length > 0) {
		for ( var i = 0; i < rnames.length; i++) {
			for ( var j = 0; j < lnames.length; j++) {
				if (rnames[i].toUpperCase() == lnames[j].toUpperCase()) {
					return true;
				}
			}
		}
		return false;
	}
	return (lhs == rhs);

}

function startsWith(lhs, rhs) {
	if (lhs instanceof Array) {
		if (lhs.length > 0) {
			for ( var i = 0; i < lhs.length; i++) {

				if (lhs[i].toUpperCase().startsWith(rhs.toUpperCase()))
					return true;
			}
		}
		return false;
	}
	return (lhs.toUpperCase().startsWith(rhs.toUpperCase()));
}

function endsWith(lhs, rhs) {
	if (lhs instanceof Array) {
		if (lhs.length > 0) {
			for ( var i = 0; i < lhs.length; i++) {

				if (lhs[i].toUpperCase().endsWith(rhs.toUpperCase()))
					return true;
			}
		}
		return false;
	}
	return (lhs.toUpperCase().endsWith(rhs.toUpperCase()));
}
function limitText(limitField, limitCount) {
	if (limitField.value.length > limitCount) {
		limitField.value = limitField.value.substring(0, limitCount);
		return false;
	}

}

/**
 * ----------------------------------------------------------------------------------------------------
 * included from UtilityFunctions.js
 * ----------------------------------------------------------------------------------------------------
 */

ie = document.all ? 1 : 0
ns4 = document.layers ? 1 : 0

function setSubmitAction(formname, actionStr) {
	var form = eval("document." + formname);

	form.subAction.value = actionStr;

	form.submit();
}

function setSubmitActionError(formname) {
	var form = eval("document." + formname);

	form.submit();
}

function ltrim(s) {
	if (s != null && s.length > 0)
		return s.replace(/^\s*/, "")
	else
		return "";
}

function rtrim(s) {
	if (s != null && s.length > 0)
		return s.replace(/\s*$/, "");
	else
		return "";
}

function trim(s) {
	return rtrim(ltrim(s));
}

function setSubmitAct(formname, actionStr, browserBackButton) {
	var form = eval("document." + formname);
	var bValue = form[browserBackButton];
	bValue.value = true;

	form.subAction.value = actionStr;
	form.submit();
}

function disableBackButton() {
	var hField = document["GSDeployBean"]["browserBack"];
	var bValue = hField.value;
	if (eval(bValue) == eval("true"))
		history.forward(1);
}

function performClientValidation(formName, mandatoryQuestionFieldName,
		serverSideValidationFlag) {
	var returnValue = true;
	if (eval(serverSideValidationFlag) == false) {
		returnValue = validateAnswers(formName, mandatoryQuestionFieldName,
				'<%=request.getContextPath()%>');
	}
	return returnValue;
}

/**
 * ----------------------------------------------------------------------------------------------------
 * included from ofr-runtime-lib.js
 * ----------------------------------------------------------------------------------------------------
 */

// browser identification
var _browser = navigator.appName;
var _netscape = "Netscape";
var _ie = "Microsoft Internet Explorer";

/**
 * function which creates the main table adjusting the width accordingly to span
 * the complete browser
 */
function writeMainTable() {
	var screen_width = 770;
	var table_stmt = "<TABLE BORDER=\"0\" CELLPADDING=\"0\" CELLSPACING=\"0\" WIDTH=\""
			+ screen_width + "\" ALIGN=\"left\" CLASS=\"table-bg-white\" >";
	document.write(table_stmt);
}

/**
 * a common submit function
 */
function submitForm(formName, actionFieldName, actionValue) {
	var form = document[formName];

	form[actionFieldName].value = actionValue;
	form.submit();
}

/**
 * sets the configuration fields present in form1 to form2
 */
function setConfigFields(fromFormName, toFormName) {
	var fromForm = document[fromFormName];
	var toForm = document[toFormName];

	if (typeof (fromForm) != "undefined" && typeof (toForm) != "undefined") {
		setField("contactId", fromForm, toForm);
		setField("tenantId", fromForm, toForm);
		setField("languageId", fromForm, toForm);
		setField("overrideSiteLanguageId", fromForm, toForm);
		setField("locale", fromForm, toForm);

	}
}

/**
 * sets the given field's value present in form1 to form2
 */
function setField(fieldName, fromForm, toForm) {
	var fromField = fromForm[fieldName];
	var toField = toForm[fieldName];
	if (typeof (fromField) != "undefined" && typeof (toField) != "undefined") {
		toField.value = fromField.value;
	}
}

// email challenge functions

function submitEmailChanllengeForm() {
	var nullField = getNullField("emailChallengeBean", new Array(
			"challengeEmail"));
	if (nullField != null) {
		showDiv("emailChallengeNullDiv", true);
		showDiv("emailChallengeInvalidEmailDiv", false);
		sendFocus("emailChallengeBean", "challengeEmail")
	} else {
		showDiv("emailChallengeNullDiv", false);
		var form = document["emailChallengeBean"];
		var email = trim(form["challengeEmail"].value);
		form["subAction"].value = "submit";
		form.submit();
		return true;
	}
	return false;
}

function showDiv(divName, showFlag) {
	var obj = document.getElementById(divName);
	if (showFlag) {
		obj.style.display = "block";
	} else {
		obj.style.display = "none";
	}
}

function sendFocus(formName, fieldName) {
	document[formName][fieldName].focus();
}

function isValidEmail(email) {
	// var re = new RegExp();

	// reg expression for email format
	// re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

	var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

	if (!filter.test(email)) {
		return false;
	} else {
		return true;
	}
}

function getNullField(formName, fields) {
	var form = document[formName];
	var nullField = null;
	for ( var i = 0; i < fields.length; i++) {
		var fieldName = fields[i];
		var field = form[fieldName];
		if (typeof (field) != "undefined") {
			var value = trim(field.value);
			if (value.length == 0) {
				nullField = field;
				break;
			}
		}
	}
	return nullField;
}

var _browser = navigator.appName;
var _netscape = "Netscape";
var _ie = "Microsoft Internet Explorer";
/**
 * this method stops the submit func.. when the enter key is pressed
 */
function checkEnter(event) {
	var code = 0;

	if (_browser == _netscape)
		code = event.which;
	else
		code = event.keyCode;

	// if key code is enter key.. discard it
	if (code == 13) {
		return submitEmailChanllengeForm();
	}
}

/**
 * Logs the events
 */
function logEvents(e) {

	var element;
	if (isIE) {
		element = window.event.srcElement;
	} else {
		element = this;
	}

	if (isResponded(element)) {
		var qId = element.name.substring(1);
		var img = document.getElementById('i' + qId);

		if (img) {
			if (!img.responded) {
				img.src = img.src + "&r=y";
				img.responded = true;
			}
		}
	}
}

/**
 * Intialization method to register the log events for all the answer elements
 */
function m2lInit() {
	var form = document.GSDeployBean;
	var emailChallengeForm = document["emailChallengeBean"];
	if (typeof (emailChallengeForm) != "undefined")
		form.showEmailChallenge.value = true;
}

var M2L = {
		emptyFunction : function() {
		},

		Browser : {
			IE :!!(window.attachEvent && navigator.userAgent.indexOf('Opera') === -1),
			Opera :navigator.userAgent.indexOf('Opera') > -1,
			WebKit :navigator.userAgent.indexOf('AppleWebKit/') > -1,
			Gecko :navigator.userAgent.indexOf('Gecko') > -1
					&& navigator.userAgent.indexOf('KHTML') === -1,
			MobileSafari :!!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
		}
	}

M2L.Utils = {
	interpret : function(value) {
		return value == null ? '' : String(value);
	},
	isUndefined : function(object) {
		return typeof object == "undefined";
	}
}

M2L.Ajax = {
	getTransport : function() {
		var request = null;
		try {
			request = new XMLHttpRequest();
		} catch (trymicrosoft) {
			try {
				request = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (othermicrosoft) {
				try {
					request = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (failed) {
					request = false;
				}
			}
		}
		return request;
	}
}

M2L.Ajax.Request = function(url, options) {
	this.initialize(url, options);
}

M2L.Ajax.Request.prototype = {

	initialize : function(url, options) {
		if (options == null)
			options = {};
		if (options.method == null)
			options.method = 'post';
		if (options.asynchronous == null)
			options.asynchronous = true;

		var params = options.parameters;

		this.options = options;
		this.url = url;
		this.transport = M2L.Ajax.getTransport();
		this.method = this.options.method;
		this.parameters = params;
		
		if (this.method == 'get' && params) {
    	    this.url += ((this.url.indexOf('?') > -1) ? '&' : '?') + params;
		}

		// open connection
		this.transport.open(this.method.toUpperCase(), this.url,
				this.options.asynchronous);

		var myInstance = this;
		this.transport.onreadystatechange = function() {
			myInstance.onStateChange.apply(myInstance);
		};
		this.body = this.method == 'post' ? (this.options.postBody || params)
				: null;
		this.transport.send(this.body);
	},

	success : function() {
		var status = this.getStatus();
		return !status || (status >= 200 && status < 300);
	},

	getStatus : function() {
		try {
			return this.transport.status || 0;
		} catch (e) {
			return 0
		}
	},

	onStateChange : function() {
		var readyState = this.transport.readyState;
		if (readyState > 1 && !((readyState == 4) && this._complete))
			this.respondToReadyState(this.transport.readyState);
	},

	dispatchException : function(exception) {
		(this.options.onException || M2L.emptyFunction)(this, exception);
	},

	respondToReadyState : function(readyState) {
		var state = M2L.Ajax.Request.Events[readyState], response = new M2L.Ajax.Response(
				this);

		if (state == 'Complete') {
			try {
				this._complete = true;
				(this.options['on' + response.status]
						|| this.options['on' + (this.success() ? 'Success'
								: 'Failure')] || M2L.emptyFunction)(response,
						response.headerJSON);
			} catch (e) {
				this.dispatchException(e);
			}
		}

		try {
			(this.options['on' + state] || M2L.emptyFunction)(response,
					response.headerJSON);
		} catch (e) {
			this.dispatchException(e);
		}

		if (state == 'Complete') {
			// avoid memory leak in MSIE: clean up
			this.transport.onreadystatechange = M2L.emptyFunction;
		}
	}
}

M2L.Ajax.Request.Events = [ 'Uninitialized', 'Loading', 'Loaded',
		'Interactive', 'Complete' ]

M2L.Ajax.Response = function(request) {
	this.initialize(request);
}

M2L.Ajax.Response.prototype = {
	initialize : function(request) {
		this.request = request;
		var transport = this.transport = request.transport, readyState = this.readyState = transport.readyState;

		if ((readyState > 2 && !M2L.Browser.IE) || readyState == 4) {
			this.status = this.getStatus();
			this.statusText = this.getStatusText();
			this.responseText = M2L.Utils.interpret(transport.responseText);
		}

		if (readyState == 4) {
			var xml = transport.responseXML;
			this.responseXML = M2L.Utils.isUndefined(xml) ? null : xml;
		}
	},

	status :0,
	statusText :'',

	getStatus :M2L.Ajax.Request.prototype.getStatus,

	getStatusText : function() {
		try {
			return this.transport.statusText || '';
		} catch (e) {
			return ''
		}
	}
}

M2L.PeriodicalExecuter = function(callback, frequency) {
	this.initialize(callback, frequency);
}

M2L.PeriodicalExecuter.prototype = {
	initialize : function(callback, frequency) {
		this.callback = callback;
		this.frequency = frequency;
		this.currentlyExecuting = false;

		this.registerCallback();
	},

	registerCallback : function() {
		var myInstance = this;
		this.timer = setInterval( function() {
			myInstance.onTimerEvent.apply(myInstance);
		}, this.frequency * 1000);
	},

	execute : function() {
		this.callback(this);
	},

	stop : function() {
		if (!this.timer)
			return;
		clearInterval(this.timer);
		this.timer = null;
	},

	onTimerEvent : function() {
		if (!this.currentlyExecuting) {
			try {
				this.currentlyExecuting = true;
				this.execute();
			} finally {
				this.currentlyExecuting = false;
			}
		}
	}
}

M2L.SessionKeeper = {
	Config : {
		DELAY :4*60,
		MAX_REQUESTS : 12
	},

	_count :0,
	_thread :null,

	start : function() {
		var requestor = function() {
			var config = M2L.SessionKeeper.Config;
			if (M2L.SessionKeeper._count < config.MAX_REQUESTS) {
				var ajaxRequest = new M2L.Ajax.Request("/go/keepAlive.do", {
					method: 'get',
					parameters:'ctr='+ M2L.SessionKeeper._count,
					onSuccess : function(response) {
						M2L.SessionKeeper._count++;
					}
				});
			} else {
				M2L.SessionKeeper._thread.stop();
			}
		}
		M2L.SessionKeeper._thread = new M2L.PeriodicalExecuter(requestor,
				M2L.SessionKeeper.Config.DELAY);
	}
}

M2L.WebForm = {
	init: function() {
		m2l_addEventListener(window, 'load', M2L.SessionKeeper.start);
	}
}