

//wFORMS.helpers.addEvent(window,'load',powerUpPage);
wFORMS.functionName_formValidation = "doPostBack";
powerUpPage();

function powerUpPage() { 	
	// HOMEPAGE
	if(document.getElementById('wf_TFA20Login')) {
		document.getElementById('wf_TFA20Login').style.display='block';
		document.getElementById('wf_TFA20Registration').style.display='none';	
		document.getElementById('registrationLink').onclick = showRegistration;
		document.getElementById('loginLink').onclick = showLogin;	
	}
	// SIGN UP PAGE
	if(document.getElementById('SignUp')) {
		document.getElementById('wf_TFA20Login').style.display='none';
		document.getElementById('wf_TFA20Registration').style.display='block';	
		document.getElementById('registrationLink').onclick = showRegistration;
		document.getElementById('loginLink').onclick = showLogin;	
	}	
	// LANDING PAGES
	if(document.getElementById('wf_TFA20Landing')) {
		document.getElementById('wf_TFA20Login').style.display='none';
		document.getElementById('wf_TFA20Registration').style.display='block';	
		document.getElementById('registrationLink').onclick = showRegistration;
		document.getElementById('loginLink').onclick = showLogin;	
	}
	// FORM-PROPERTIES.PHP 
	var SSLCheckbox = document.getElementById('secureFormCheckbox');
	if(SSLCheckbox) {
		SSLCheckbox.onclick = function() {
			var formLink = document.getElementById('formLink'); 
			var formXHTML = document.getElementById('formXHTMLCode');
			if(SSLCheckbox.checked) {
				formLink.href      = formLink.href.replace('http://www.','https://secure.');
				formLink.innerHTML = formLink.innerHTML.replace('http://www.','https://secure.');
				if(formXHTML)
					formXHTML.value = formXHTML.value.replace('http://www.formassembly','https://secure.formassembly');
			} else {
				formLink.href      = formLink.href.replace('https://secure.', 'http://www.');
				formLink.innerHTML = formLink.innerHTML.replace('https://secure.', 'http://www.');
				if(formXHTML)
					formXHTML.value = formXHTML.value.replace('https://secure.formassembly','http://www.formassembly');				
			} 
		}
	}
	// REPORT.PHP 
	var responseBrowser = document.getElementById('responseBrowser');
	if(responseBrowser) {
		var allLinks = responseBrowser.getElementsByTagName('a');
		
		for (var i=0; i<allLinks.length; i++) {
			switch(allLinks[i].className) {
				case 'responseLink':
					if(window.XMLHttpRequest) {
						allLinks[i].onclick = function(e) {
							// load content
							var responseId = this.href.substr(this.href.indexOf('responseId='));
							loadContent('/srvc-response-store.php?'+responseId, 'RightColumn');
							
							// move placeholder if necessary to avoid scrolling up.
							var scrollTop = (document.body.scrollTop || document.documentElement.scrollTop); 
							var placeholder = document.getElementById('RightColumn');
							if(scrollTop > 50) {								
								placeholder.style.marginTop = (scrollTop - 30) + "px";
							} else {
								placeholder.style.marginTop = "0px";
							}
							
							
							// deal with 'selected' class on TRs
							var responseBrowser = document.getElementById('responseBrowser');
							var allTRs = responseBrowser.getElementsByTagName('tr');
							for (var i=0; i<allTRs.length; i++) {
								if(allTRs[i].className=='selected') allTRs[i].className = '';
							}
							this.parentNode.parentNode.className = 'selected';
							// prevents click to go through.
							return wFORMS.helpers.XBrowserPreventEventDefault(e);
						}
					}
					break;
				case 'selectAllResponsesLink': 
					allLinks[i].onclick = function() {
						var allCbs = this.parentNode.parentNode.parentNode.getElementsByTagName('input');
						for (var j=0; j<allCbs.length; j++) { 
							if(allCbs[j].type=='checkbox') {
								allCbs[j].checked=!allCbs[j].checked;
							}
						}
						return false;
					}
					break;
				case 'flagLink':
					if(window.XMLHttpRequest) {
						allLinks[i].onclick = function() {
							var responseId = this.id.substr(5);
							postContent('/srvc-response-store.php','responseId='+responseId+'&flag=2');
							this.innerHTML = "<img src='/images/v2/tfa_flag.gif' alt='flag'/>";
							this.className = "unflagLink";
							powerUpPage();
							return false;
						}
					}
					break;
				case 'unflagLink':
					if(window.XMLHttpRequest) {
						allLinks[i].onclick = function() {
							var responseId = this.id.substr(5);
							postContent('/srvc-response-store.php','responseId='+responseId+'&flag=0');
							this.innerHTML = ".";
							this.className = "flagLink";
							powerUpPage();
							return false;
						}
					}
					break;
				case 'showAggregateLink':
					if(window.XMLHttpRequest) {
						allLinks[i].onclick = function() { 
							var href = this.getAttribute('href');
							var formId = (href.split('formId='))[1].split('&')[0];
							// unicode font support (do not set to one unless output looks garbled)
							var u = href.split('&u=')[1].split('&')[0];							
							loadContent('/srvc-response-store.php?format=aggregate&formId='+formId+'&u='+u, "RightColumn");
							// move placeholder if necessary to avoid scrolling up.
							var placeholder = document.getElementById('RightColumn');
							/*
							var scrollTop = (document.body.scrollTop || document.documentElement.scrollTop); 						
							
							if(scrollTop > 50) {								
								placeholder.style.marginTop = (scrollTop - 30) + "px";
							} else {
								placeholder.style.marginTop = "0px";
							}
							*/
							placeholder.style.marginTop = "0px";
							window.scroll(0,0);
							return false; 
						};							

						
					}
					break;
			}
		}
	}
}
function showRegistration() {
	document.getElementById('wf_TFA20Login').style.display='none';
	document.getElementById('wf_TFA20Registration').style.display='block';	
}
function showLogin() {
	document.getElementById('wf_TFA20Login').style.display='block';
	document.getElementById('wf_TFA20Registration').style.display='none';	
}

function doPostBack(e) {
	if(!e) e = window.event;	
	if(wFORMS.behaviors['validation'].run(e)) {
		var f = wf.utilities.getSrcElement(e);
		switch(f.id) {
			case 'wf_TFA20Registration': 										 // TFA2.0 Registration Form
				if(f['tfa_reg_Password'].value != "" && f['tfa_reg_Password'].value != f['tfa_reg_ConfirmPassword'].value) {
					wFORMS.behaviors['validation'].showError(f['tfa_reg_ConfirmPassword'],"The passwords don't match");
					return wFORMS.helpers.preventEvent(e);
				} 
				if(window.XMLHttpRequest) 
					ajaxRegistration(e);
				break;
			case 'wf_TFA20Login':
				if(window.XMLHttpRequest) 
					ajaxLogin(e);
				break;
			case 'AccountInformation':
				if(f['tfa_changePassword'].checked && f['tfa_Password'].value != f['tfa_Password2'].value) {
					wFORMS.behaviors['validation'].showError(f['tfa_Password2'],"The passwords don't match");
					return wFORMS.helpers.preventEvent(e);
				} 
				document.getElementById('submitAccountInformation').value=" Wait...";  
				break;
		}
	} 	
}
function ajaxRegistration(e) {
	// do not let it happen twice
	var b = document.getElementById('submitRegistration');
	if(b.value!=' Wait...') b.value=' Wait...';
	else return wFORMS.helpers.preventEvent(e);
	
	// ok, proceed
	document.getElementById('message2PlaceHolder').innerHTML = "";
	var urlRegistrar = "http://" + window.location.host + "/srvc-registrar.php"
	var xmlhttp      = new XMLHttpRequest();
	xmlhttp.open("POST", urlRegistrar, true);
	xmlhttp.onreadystatechange= function() {
		if (xmlhttp.readyState==4) {
			if(xmlhttp.status==201 || xmlhttp.status==undefined /* safari bug */) {
				document.location =  "http://" + window.location.host + "/upgrade-plan.php?new=1";
			//	loadContent('/includes/tmpl_overview.php', 'wf_TFA20Registration');
			//	setTimeout("loadContent('/includes/tmpl_nav_bar.php', 'NavBarPlaceHolder')", 500); // timer for Opera.
			}
			else {
				b.value="  Sign Up";
				document.getElementById('tfa_reg_Username').focus();
				document.getElementById('message2PlaceHolder').innerHTML = "<p class='errMsg'>"+xmlhttp.responseText + "</p>";
			}
		}
	}
	xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	var data = "msgformat=html&tfa_reg_Username="+encodeURIComponent(document.getElementById('tfa_reg_Username').value)+"&tfa_reg_Password="+encodeURIComponent(document.getElementById('tfa_reg_Password').value)+"&tfa_reg_ConfirmPassword="+encodeURIComponent(document.getElementById('tfa_reg_ConfirmPassword').value)+"&tfa_reg_Email="+encodeURIComponent(document.getElementById('tfa_reg_Email').value);
	xmlhttp.send(data);
	return wf.utilities.XBrowserPreventEventDefault(e);
}

function ajaxLogin(e) {
	// do not let it happen twice
	var b = document.getElementById('submitLogin');
	if(b.value!=' Wait...') b.value=' Wait...';
	else return wFORMS.helpers.preventEvent(e);
	
	document.getElementById('messagePlaceHolder').innerHTML = "";
	var urlRegistrar = "http://" + window.location.host + "/srvc-registrar.php"
	var xmlhttp      = new XMLHttpRequest();
	xmlhttp.open("POST", urlRegistrar, true);
	xmlhttp.onreadystatechange= function() {
		if (xmlhttp.readyState==4) {
			if(xmlhttp.status==300 || xmlhttp.status==200 || xmlhttp.status==undefined /* safari bug */) {

				var redirectUrl = xmlhttp.getResponseHeader("location");
				
				if (redirectUrl)
					document.location = redirectUrl;
				else
					document.getElementById('messagePlaceHolder').innerHTML = "<p class='errMsg'>"+xmlhttp.responseText + "</p>";
				
				//document.location = "forms.php";
				
				//loadContent('/includes/tmpl_overview.php', 'wf_TFA20Login');
				//setTimeout("loadContent('/includes/tmpl_nav_bar.php', 'NavBarPlaceHolder')", 500); // timer for Opera.
			}
			else  {
				b.value='Login';
				document.getElementById('messagePlaceHolder').innerHTML = "<p class='errMsg'>"+xmlhttp.responseText + "</p>";
			}
		}
	}
	xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	var data = "msgformat=html&tfa_Username="+encodeURIComponent(document.getElementById('tfa_Username').value)+"&tfa_Password="+encodeURIComponent(document.getElementById('tfa_Password').value);
	if(document.getElementById('tfa_AutoLogin').checked)
		data += "&tfa_AutoLogin="+encodeURIComponent(document.getElementById('tfa_AutoLogin').value);
	if(document.getElementById('redirectUrl'))
		data += "&redirect="+encodeURIComponent(document.getElementById('redirectUrl').value);
	xmlhttp.send(data);
	return wFORMS.helpers.preventEvent(e);
}

function loadContent(url, placeHolder) {
	url 		= "http://" + window.location.host + url;
	placeHolder = document.getElementById(placeHolder);
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open("GET", url, true);
	xmlhttp.onreadystatechange= function() {
		
		if (xmlhttp.readyState==4) {
			if(xmlhttp.status==200 || xmlhttp.status==201) {
				if(placeHolder)
					placeHolder.innerHTML = xmlhttp.responseText;					
			}
			else {
				if(placeHolder)
					placeHolder.innerHTML = "<p class='errorMsg'>"+xmlhttp.responseText+"</p>";
			}
		}
	}
	xmlhttp.send(null);
	if(placeHolder) {
		var height    = placeHolder.offsetHeight;
		var topmargin = (height - 50)/2;
		if(topmargin > 300) 
			topmargin = 300;
		height 		  = height - topmargin;
		var width     = placeHolder.offsetWidth;
		placeHolder.innerHTML = "<div style=\"text-align:center; margin-top: "+topmargin+"px; height: "+height+"px; width="+width+"px;\">Loading...<br/><img src=\"/images/v2/loading-throbber.gif\" alt=\"Loading...\" /></div>";
	}
}

function postContent(url, data) {
	var resultPlaceHolder = arguments[2] || "";
	var xmlhttp      = new XMLHttpRequest();
	xmlhttp.open("POST", url, true);
	xmlhttp.onreadystatechange= function() {
		if (xmlhttp.readyState==4) {
			if(xmlhttp.status==200 || xmlhttp.status==201 || xmlhttp.status==undefined /* safari bug */) {
				if(resultPlaceHolder)
					document.getElementById(resultPlaceHolder).innerHTML = xmlhttp.responseText;
			}
			else  {
				if(resultPlaceHolder)
					document.getElementById(resultPlaceHolder).innerHTML = "<p class='errMsg'>"+xmlhttp.responseText + "</p>";
			}
		}
	}
	xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlhttp.send(data);
}
/**
 * Sarissa is an ECMAScript library acting as a cross-browser wrapper for native XML APIs.
 * The library supports Gecko based browsers like Mozilla and Firefox,
 * Internet Explorer (5.5+ with MSXML3.0+), Konqueror, Safari and a little of Opera
 * @version 0.9.6.1
 * @author: Manos Batsis, mailto: mbatsis at users full stop sourceforge full stop net
 */
pickRecentProgID = function (idList, enabledList){
	// found progID flag
	var bFound = false;
	for(var i=0; i < idList.length && !bFound; i++){
		try{
			var oDoc = new ActiveXObject(idList[i]);
			o2Store = idList[i];
			bFound = true;
			for(var j=0;j<enabledList.length;j++)
				if(i <= enabledList[j][1])
					Sarissa["IS_ENABLED_"+enabledList[j][0]] = true;
		}catch (objException){
			// trap; try next progID
		};
	};
	if (!bFound)
		throw "Could not retreive a valid progID of Class: " + idList[idList.length-1]+". (original exception: "+e+")";
	idList = null;
	return o2Store;
};
var _SARISSA_IS_IE = document.all && window.ActiveXObject && navigator.userAgent.toLowerCase().indexOf("msie") > -1  && navigator.userAgent.toLowerCase().indexOf("opera") == -1;
if(_SARISSA_IS_IE) {
	_SARISSA_XMLHTTP_PROGID = pickRecentProgID(["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"], [["XMLHTTP", 4]]);
	if(!window.XMLHttpRequest){
	    XMLHttpRequest = function() {
	        return new ActiveXObject(_SARISSA_XMLHTTP_PROGID);
	    };
	}
}