// ADHS STEPS JS FUNCTIONS
// Written by Jamie Parker
// March 2007

var subState = 0;
var prevSub = 0;
var XMLHttpRequestObject = false;
var submitPop;

var prev_m_hilite = "";
var prev_w_hilite = "";

var browserName = navigator.appName;

if(window.XMLHttpRequest){
	XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject){
	XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHttp");
}

function sendXHR(query, type){
	if(XMLHttpRequestObject){
		
		XMLHttpRequestObject.open("GET", query);
		
		XMLHttpRequestObject.onreadystatechange = function(){
			if(XMLHttpRequestObject.readyState != 4){
				document.getElementById("form").style.display = "none";
				document.getElementById("pageCopy").innerHTML = "Submitting Form...";
			}
			if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200){
				var xhrResponse = XMLHttpRequestObject.responseText;
				
				if(type == 1){
					document.getElementById("form").style.display = "none";
					document.getElementById("pageTitle").innerHTML = "Thank You.";
					document.getElementById("pageCopy").innerHTML = "Need thank you copy here...";
				} else if(type == 2){
					document.getElementById("storyForm").style.display = "none";
					document.getElementById("storyCopy").innerHTML = "Your success story has been submitted! Thank you for sharing your story with others. Trying to lead a healthier lifestyle can be challenging, especially in the very beginning. Sharing how you overcame hurdles helps others do the same!<br/><br/><a href='javascript:window.close();'>Close This Window</a>";
					document.getElementById("storyHeader").innerHTML = "Thank You.";
				} else if(type == 3){
					document.getElementById("storyResults").innerHTML = xhrResponse;
				} else if(type == 4){
					//do nothing
				} else if(type == 5){
					document.getElementById("storiesCont").innerHTML = xhrResponse;
				} else if(type == 6){
					eval(xhrResponse);
				} else if(type == 7){
					document.getElementById("form").style.display = "none";
					document.getElementById("formInstructions").style.display = "none";
					document.getElementById("contactAddress").style.display = "none";
					document.getElementById("thanks").style.display = "block";
				} else if(type == 8){
					document.getElementById("clubResults").innerHTML = xhrResponse;
					document.getElementById("pageCopy").innerHTML = "";
				} else if(type == 9){
					document.getElementById("storyForm").style.display = "none";
					document.getElementById("storyCopy").innerHTML = "&iexcl;Su historia de &eacute;xito se ha enviado! Gracias por compartir su historia con los dem&aacute;s. Tratar de llevar una vida m&aacute;s saludable puede ser un reto, especialmente   al principio. Al compartir c&oacute;mo venci&oacute; los obst&aacute;culos ayuda a los dem&aacute;s a hacer lo mismo!<br/><br/><a href='javascript:window.close();'>Cierre esta ventana</a>";
					document.getElementById("storyHeader").innerHTML = "&iexcl;Muchas Gracias!";
				}
			}
		}
		XMLHttpRequestObject.send(query);
	} else {
		var xhrResponse = "XHR ERROR";
		return xhrResponse;
	}
}


function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function showSubNav(which){
	var target = document.getElementById("subNav");
	
	if(which == 1){
		target.innerHTML = "<a href=\"articles.html\">Articles</a> | <a href=\"tips.html\">Tips &amp; Tricks</a> | <a href=\"resources.html\">Resources</a> | <a href=\"faq.html\">FAQ</a>";
	} else if (which == 2){
		target.innerHTML = "<a href=\"calcs.html\">Calculators</a> | <a href=\"recc.html\">Recommendations</a> | <a href=\"charts.html\">Charts</a> | <a href=\"tracker.html\">Physical Activity Tracker</a>";
	} else if (which == 3) {
		target.innerHTML = "<a href=\"games_online.html\">Online</a> | <a href=\"games_offline.html\">Offline</a>";
	} else if (which == 4) {
		target.innerHTML = "<a href=\"stories_read.html\">Read Stories</a> | <a href=\"stories_submit.html\">Submit Your Own Story</a>";
	}
	
	if(subState == 0){
		target.style.display = "block";
		subState = 1;
	} else if(subState == 1){
		if(which == prevSub){
			target.style.display = "none";
			subState = 0;
		}
	}
	
	prevSub = which;
}

function getBMI(){
	var weight = document.getElementById("weight").value;
	var height = document.getElementById("height").value;
	
	var height_sq = height * height;
	
	var BMI_index = (weight / height_sq) * 703;
	
	var result = Math.round(BMI_index*10)/10;
	
	if((prev_m_hilite != "") && (prev_w_hilite != "")){
		document.getElementById(prev_m_hilite).style.backgroundColor = "white";
		document.getElementById(prev_w_hilite).style.backgroundColor = "white";
	}
	
	var m_hilite_str = "m_" + height;
	var w_hilite_str = "w_" + height;
	
	prev_m_hilite = m_hilite_str;
	prev_w_hilite = w_hilite_str;
	
	document.getElementById(m_hilite_str).style.backgroundColor = "#cce3eb";
	document.getElementById(w_hilite_str).style.backgroundColor = "#cce3eb";
	
	document.getElementById("BMI").innerHTML = result;
	document.getElementById("BMIResults").style.display = "block";
}

function calcCB(met, target){
	var lb = document.getElementById("cb_weight").value;
	var kg = lb / 2.2;
	var kg_round = Math.round(kg*10)/10;
	var cb = ((met * 3.5) * kg_round) / 200; //kcals burned per minute
	var cb_hh = Math.round(cb * 30); //kcals burned ber half hour of activity
	
	var rowTargStr = "met_" + target;
	var act = document.getElementById(rowTargStr).firstChild.innerHTML;
	
	document.getElementById("activity").innerHTML = act;
	document.getElementById("KCals_total").innerHTML = cb_hh + " calories per half hour";
	
	document.getElementById("METTable").style.display = "none";
	document.getElementById("CB_results").style.display = "block";
}

function resetCB(){
	document.getElementById("METTable").style.display = "block";
	document.getElementById("CB_results").style.display = "none";
}

function showNav(target){
	var targ = target + "DropDwn";
	
	if(document.getElementById(targ).style.display == "none"){
		document.getElementById(targ).style.display = "block";
	}
}

function submitClubForm(){
	var firstName = document.getElementById("firstName").value;
	var lastName = document.getElementById("lastName").value;
	var city = document.getElementById("city").value;
	var state = "AZ";
	var zip = document.getElementById("zip").value;
	var phone = document.getElementById("phone").value;
	var email = document.getElementById("email").value;
	var confEmail = document.getElementById("confirmEmail").value;
	var contactPref;
	
	for(var i=0; i < document.contactForm.contactPref.length; i++){
		if(document.contactForm.contactPref[i].checked){
			contactPref = document.contactForm.contactPref[i].value;
		}
	}
	
	if(firstName == ""){
		var firstNameError = true;
		var foundError = true;
	}
	if(lastName == ""){
		var lastNameError = true;
		var foundError = true;
	}
	if(city == ""){
		var cityError = true;
		var foundError = true;
	}
	
	if(zip == ""){
		var zipError = true;
		var foundError = true;
	}
	
	if(zip.length != 5){
		var zipLengthError = true;
		var foundError = true;
	}
	
	if(email == ""){
		var emailError = true;
		var foundError = true;
	}
	
	if(confEmail == ""){
		var confEmailError = true;
		var foundError = true;
	}
	if(email != confEmail){
		var emailConfirmError = true;
		var foundError = true;
	}
	
	var test1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)|(\s)/;
	var test2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
	if(!test1.test(email) && test2.test(email)){
		var emailValidError = false;
		var foundError = false;
	} else {
		var emailValidError = true;
		var foundError = true;
	}
	
	if(foundError == true){
		var message = "";
		
		if(firstNameError == true){
			message += "Please enter your first name.\n";
		}
		if(lastNameError == true){
			message += "Please enter your last name.\n";
		}
		if(cityError == true){
			message += "Please enter your city.\n";
		}
		if(stateError == true){
			message += "Please enter your state.\n";
		}
		if(zipError == true){
			message += "Please enter your state.\n";
		}
		if(zipLengthError == true){
			message += "Please make sure your zip code is 5 digits long.\n";
		}
		if(emailError == true){
			message += "Please enter your email address.\n";
		}
		if(confEmailError == true){
			message += "Please confirm your email address.\n";
		}
		if(emailConfirmError == true){
			message += "You email address did not match.\n";
		}
		if(emailValidError == true){
			message += "Please enter a valid email.\n";
		}
		
		alert(message);
	} else {
		//run php script
		var qString = "com/walkClub.php?fn=" + firstName + "&ln=" + lastName + "&city=" + city + "&state=" + state + "&zip=" + zip + "&email=" + email + "&phone=" + phone + "&contact=" + contactPref;
		
		sendXHR(qString, 1);
	}
}

function getClubs(){
	var whichCity = document.getElementById("cities").value;
	
	var qString = "com/getWalkClubs.php?city=" + whichCity;
	
	sendXHR(qString, 8);
}

function getClubsSP(){
	var whichCity = document.getElementById("cities").value;
	var qString = "../com/getWalkClubs.php?city=" + whichCity;
	sendXHR(qString, 8);
}

/* SUCCESS STORIES FUNCTIONS */

function checkLogin(){
	var qString = "com/loginCheck.php";
	sendXHR(qString, 6);
}

function badSession(error){
	//show login instructions
	document.getElementById("logInstColumn").style.display = "block";
	
	//show login console
	document.getElementById("loginConsole").style.display = "block";
	
	//hide manager instructions
	document.getElementById("instColumn").style.display = "none";
	
	//hide manager console
	document.getElementById("storyResults").style.display = "none";
	
	//hide logout button
	document.getElementById("logoutBtn").style.display = "none";
	
	//show error message if any
	document.getElementById("loginError").innerHTML = error;
	
}

function goodSession(){
	//hide login instructions
	document.getElementById("logInstColumn").style.display = "none";
	
	//hide login console
	document.getElementById("loginConsole").style.display = "none";
	
	//show manager instructions
	document.getElementById("instColumn").style.display = "block";
	
	//show manager console
	document.getElementById("storyResults").style.display = "block";
	
	//show logout button
	document.getElementById("logoutBtn").style.display = "block";
	
	//retrieve stories
	getStories();
}

function submitLogin(){
	var username = document.getElementById("username").value;
	var pass = document.getElementById("password").value;
	
	if (username == ""){
		var usernameError = true;
		var foundError = true;
	}
	
	if(pass == ""){
		var passError = true;
		var foundError = true;
	}
	
	if(foundError == true){
		
		var message = "";
		
		if(usernameError == true){
			message += "Please enter your username.\n";
		}
		
		if(passError == true){
			message += "Please enter your password.\n";
		}
		
		alert(message);
		
	} else {
		
		var qString = "com/loginUser.php?username=" + username + "&pass=" + pass;
		
		sendXHR(qString, 6);
		
	}
}

function logout(){
	var qString = "com/logoutUser.php";
	sendXHR(qString, 6);
}

function openStoryForm(){
	submitPop = window.open("story_pop.html", "submit", "width=600, height=635, directories=no, menubar=no, resizable=no, scrollbars=no, status=no, titlebar=no, toolbar=no");
}

function openStoryFormSP(){
	submitPop = window.open("story_pop_sp.html", "submit", "width=600, height=635, directories=no, menubar=no, resizable=no, scrollbars=no, status=no, titlebar=no, toolbar=no");
}

function getStories(){
	if(document.getElementById("lang").value == 1){
		var qString = "com/getStories.php";
	} else if(document.getElementById("lang").value == 2){
		var qString = "com/getStoriesSP.php";
	}
	sendXHR(qString, 3);
}

function submitStory(){
	if(document.getElementById("story").value == ""){
		alert("Please type your story in the text box.");
	} else {
		var sStory = escape(document.getElementById("story").value);
		
		//alert(sStory);
		
		var qString = "com/submitStory.php?story=" + sStory;
		
		sendXHR(qString, 2);
	}
}

function submitStorySP(){
	if(document.getElementById("story").value == ""){
		alert("Por favor escriba su historia en el casillero para texto.");
	} else {
		var sStory = escape(document.getElementById("story").value);
		
		//alert(sStory);
		
		var qString = "../com/submitStorySP.php?story=" + sStory;
		
		sendXHR(qString, 9);
	}
}



function showStory(which, pubState){
	var targDiv = "story_" + which
	var targ = document.getElementById(targDiv);
	
	targ.style.display = "block";
	
	var headTarg = "title_" + which;
	
	if(pubState == 0){
		document.getElementById(headTarg).innerHTML = "<a href=\"javascript:hideStory('" + which + "','0')\">Story " + which + "</a>";
	} else {
		document.getElementById(headTarg).innerHTML = "<a href=\"javascript:hideStory('" + which + "','1')\">Story " + which + "</a> <span style='color:red; font-size:10px'><strong>(Published)</strong></span>";
	}
}

function hideStory(which, pubState){
	var targDiv = "story_" + which
	var targ = document.getElementById(targDiv);
	
	targ.style.display = "none";
	
	var headTarg = "title_" + which;
	
	if(pubState == 0){
		document.getElementById(headTarg).innerHTML = "<a href=\"javascript:showStory('" + which + "','0')\">Story " + which + "</a>";
	} else {
		document.getElementById(headTarg).innerHTML = "<a href=\"javascript:showStory('" + which + "','1')\">Story " + which + "</a> <span style='color:red; font-size:10px'><strong>(Published)</strong></span>";
	}
}

function storyPubChange(target){
	
	var targName = "select_" + target;
	var targ = document.getElementById(targName).value;
	
	//alert(targ);
	
	var headTarg = "title_" + target;
	
	if(targ == 1){
		document.getElementById(headTarg).innerHTML = "<a href=\"javascript:showStory('" + target + "')\">Story " + target + "</a> <span style='color:red; font-size:10px'><strong>(Published)</strong></span>";
	} else {
		document.getElementById(headTarg).innerHTML = "<a href=\"javascript:showStory('" + target + "')\">Story " + target + "</a>";
	}
	
	if(document.getElementById("lang").value == 1){
		qString = "com/pubChange.php?id=" + target + "&pub=" + targ;
	} else if(document.getElementById("lang").value == 2){
		qString = "com/pubChangeSP.php?id=" + target + "&pub=" + targ;
	}
	sendXHR(qString, 4);
}

function removeStory(id){
	var answer = confirm("Are you sure you want to remove this story from the database?");
	
	if(answer){
		if(document.getElementById("lang").value == 1){
			var qString = "com/removeStory.php?id=" + id;
		} else if(document.getElementById("lang").value == 2){
			var qString = "com/removeStorySP.php?id=" + id;
		}
		sendXHR(qString, 6);
	}	
}

function editStory(id){
	var elem = "story_" + id;
	
	var targDiv = document.getElementById(elem);
	var targText = targDiv.innerHTML;
	
	//if(browserName =="Microsoft Internet Explorer"){
		//var newStr = targText.replace(/<BR>/g, "\n");
	//} else {
		var newStr = targText.replace(/<br>/g, "\n");
	//}
	
	if(targDiv.style.display == "none"){
		targDiv.style.display = "block";
	}
	
	targDiv.innerHTML = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"5\"><tr><td><textarea name=\"storyEdit_" + id + "\" cols=\"60\" rows=\"15\" id=\"storyEdit_" + id + "\">" + targText + "</textarea></td></tr><tr><td style=\"padding-left:0\"><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"3\"><tr><td style=\"width:30px\"><input type=\"submit\" name=\"Submit\" value=\"Update\" onclick=\"updateStory(" + id + ")\" /></td><td width=\"82%\"><input type=\"reset\" name=\"Reset\" value=\"Cancel\" onclick=\"cancelEdit(" + id + ")\" /></td></tr></table></td></tr></table>";
	
}

function updateStory(id){
	
	var targ = document.getElementById("storyEdit_" + id).value;
	
	var answer = confirm("Are you sure you want to commit these changes to the database?");
	
	if(answer){
	
		if(targ == ""){
			alert("Story input box cannot be left blank.");
		} else {
			var sStory = escape(targ);
		
			if(document.getElementById("lang").value == 1){
				var qString = "com/updateStory.php?story=" + sStory + "&id=" + id;
			} else if(document.getElementById("lang").value == 2){
				var qString = "com/updateStorySP.php?story=" + sStory + "&id=" + id;
				//window.location = "com/updateStorySP.php?story=" + sStory + "&id=" + id;
			}
		
			sendXHR(qString, 3);
			
		}
	}
	
}

function cancelEdit(id){
	var elemInput = "storyEdit_" + id;
	var elem = "story_" + id;
	var targDiv = document.getElementById(elem);
	var targText = document.getElementById(elemInput).value;
	
	var newStr = targText.replace(/\n/g, "<br>");
	
	document.getElementById(elem).innerHTML = newStr;
}

function printStories(){
	var qString = "com/printStories.php";
	
	sendXHR(qString, 5);
}

function printStoriesSP(){
	var qString = "../com/printStoriesSP.php";
	
	sendXHR(qString, 5);
}

function popGames(){
	
	var mine = window.open('','','width=1,height=1,left=0,top=0,scrollbars=no');
	
	if(mine){
		var popUpsBlocked = false;
		window.open("http://stepitupaz.com/fitnessware.html","StepItUpAZ","menubar=0,resizable=0,width=650,height=500");
	} else {
		var popUpsBlocked = true;
		alert('You appear to be using a pop-up blocker.  In order to play our online games, you will need to disable your pop-up blocker and re-click this link.');
	}
	
	mine.close();
	
	
}

function popMuscle(){
	var mine = window.open('','','width=1,height=1,left=0,top=0,scrollbars=no');
	
	if(mine){
		var popUpsBlocked = false;
		window.open("http://stepitupaz.com/muscleDiagram.html","StepItUpAZ","menubar=0,resizable=0,width=800,height=600");
	} else {
		var popUpsBlocked = true;
		alert('You appear to be using a pop-up blocker.  In order to play our online games, you will need to disable your pop-up blocker and re-click this link.');
	}
	
	mine.close();	
}

function popMuscleSP(){
	var mine = window.open('','','width=1,height=1,left=0,top=0,scrollbars=no');
	
	if(mine){
		var popUpsBlocked = false;
		window.open("muscleDiagram_sp.html","StepItUpAZ","menubar=0,resizable=0,width=800,height=600");
	} else {
		var popUpsBlocked = true;
		alert('Por favor desactive los bloqueadores de &quot;pop-ups&quot;.');
	}
	
	mine.close();	
}


function doWipe(elem){
	Spry.Effect.AppearFade(elem,{duration:1000,from:0, to:100,toggle:true});
	Spry.Effect.Blind(elem,{duration:1000,from:'0%',to:'100%',toggle:true});
}

function submitContact(){
	if(document.getElementById("name").value == ""){
		var nameError = true;
		var foundError = true;
	}
	if(document.getElementById("comments").value == ""){
		var commentError = true;
		var foundError = true;
	}
	if(document.getElementById("email").value != ""){
		var email = document.getElementById("email").value;
		var test1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)|(\s)/;
		var test2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
		if(!test1.test(email) && test2.test(email)){
			var emailValidError = false;
			var foundError = false;
		} else {
			var emailValidError = true;
			var foundError = true;
		}
	}
	
	if(foundError == true){
		var msg = "";
		if(nameError == true){
			msg += "Please enter your name.\n";
		}
		if(commentError == true){
			msg += "Please enter your question and/or comment.\n";
		}
		if(emailValidError == true){
			msg += "Please enter a valid email address.\n";
		}
		if(msg != ""){
			alert(msg);
		}
	} else {
		var qString = "com/sendContact.php";
		qString += "?name=" + document.getElementById("name").value;
		if(document.getElementById("email").value != ""){
			qString += "&email=" + document.getElementById("email").value;
		}
		if(document.getElementById("phone").value != ""){
			qString += "&phone=" + document.getElementById("phone").value;
		}
		qString += "&comment=" + document.getElementById("comments").value;
		
		sendXHR(qString, 7);
	}
}

function submitContactSP(){
		if(document.getElementById("name").value == ""){
		var nameError = true;
		var foundError = true;
	}
	if(document.getElementById("comments").value == ""){
		var commentError = true;
		var foundError = true;
	}
	if(document.getElementById("email").value != ""){
		var email = document.getElementById("email").value;
		var test1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)|(\s)/;
		var test2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
		if(!test1.test(email) && test2.test(email)){
			var emailValidError = false;
			var foundError = false;
		} else {
			var emailValidError = true;
			var foundError = true;
		}
	}
	
	if(foundError == true){
		var msg = "";
		if(nameError == true){
			msg += "Por favor escriba su nombre.\n";
		}
		if(commentError == true){
			msg += "Por favor escriba su pregunta o comentario.\n";
		}
		if(emailValidError == true){
			msg += "Por favor escriba su e-mail válido.\n";
		}
		if(msg != ""){
			alert(msg);
		}
	} else {
		var qString = "../com/sendContact.php";
		qString += "?name=" + document.getElementById("name").value;
		if(document.getElementById("email").value != ""){
			qString += "&email=" + document.getElementById("email").value;
		}
		if(document.getElementById("phone").value != ""){
			qString += "&phone=" + document.getElementById("phone").value;
		}
		qString += "&comment=" + document.getElementById("comments").value;
		
		sendXHR(qString, 7);
	}
}
