function getEnterStepsPopup(userID, url) {

	//Do an ajax call to get the content of our popup.
	url = SETTINGS.webRoot + "home.php?mode=getEnterStepsPopupXML&userID="+userID+"&url="+url;
	Boxy.load(url, {title: 'Enter Steps' ,modal: true});
}

function changeStepsLabel(selectBox){
	var selectedValue = $(selectBox).attr('value');
	var newLabel = "";
	switch (selectedValue){
		case "miles":
			newLabel = "Miles Walked";
			break;
			
		case "minutes":
			newLabel = "Minutes Walked";
			break;
			
		case "steps":
			newLabel = "Number of Steps";
			break;
	
	}
	$(selectBox).parents('div.field').next('div.field').children('label').html(newLabel);
}

function removeElement(obj) {
	
	var parent = obj.parentNode;
	if (parent != null) {
		parent.removeChild(obj);
	}	
}

function getURLPath() {
	var urlPath = window.location.href;
	var stringLength = urlPath.lastIndexOf("/");
	urlPath = urlPath.substr(0, stringLength);
	return urlPath;
}

function setShippingInformation() {
	var checkboxStatus = document.getElementById('sameasabove');
	if (checkboxStatus.checked == true) {
		document.getElementById('sName').value = document.getElementById('bName').value;
		document.getElementById('saddress').value = document.getElementById('baddress').value;
		document.getElementById('sAddress2').value = document.getElementById('bAddress2').value;
		document.getElementById('scity').value = document.getElementById('bcity').value;
		var billStateIndex = document.getElementById('billingstate').selectedIndex;
		document.getElementById('shippingstate').selectedIndex = billStateIndex;
		document.getElementById('szip').value = document.getElementById('bzip').value;
	} else {
		document.getElementById('sName').value = "";
		document.getElementById('saddress').value = "";
		document.getElementById('sAddress2').value = "";
		document.getElementById('scity').value = "";
		document.getElementById('shippingstate').selectedIndex = 0;
		document.getElementById('szip').value = "";
	}
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function createBookmarkLink(title, url) {
	
	if (window.sidebar) { // firefox
		window.sidebar.addPanel(title, url, "");
		
	} else if (window.opera && window.print) { // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
		
	} else if (document.all) { // ie
		window.external.AddFavorite(url, title);
	}
}

function toggleContent(span) {

	var spanClassName = document.getElementById(span).className;
	position = spanClassName.search("hidden");

	//The classname contains 'hidden'. Remove it.
	if (position != -1) {
		document.getElementById(span).className = str_replace(spanClassName, "hidden", "");
	
	//The classname does not contain 'hidden'. Add it.
	} else {
		document.getElementById(span).className += " hidden";
	}
}

function showContent(span) {

	var spanClassName = document.getElementById(span).className;
	position = spanClassName.search("hidden");
	if (position != -1) {
		document.getElementById(span).className = str_replace(spanClassName, "hidden", "");
	}
}

function hideContent(span) {

	var spanClassName = document.getElementById(span).className;
	position = spanClassName.search("hidden");
	if (position == -1) {
		document.getElementById(span).className += " hidden";
	}
}

//string, search, replace
function str_replace(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function

function logVote(){
	var pollID = jQuery('#pollID').attr("value");
	var answerID = jQuery('input[name=answerID]:checked').val();
	if (!answerID){
		alert("Please select a choice.");
		return false;
	} else {
		if(jQuery('#pollQuestion').length){
			savePollAnswer(pollID, answerID);
			displayPollResults(pollID);			
		}
		return false;
	}
}

function displayPollResults(pollID) {
	var url = SETTINGS.webRoot + "intranet/pollControl.php?mode=displayPublicResults&pollID=" + pollID;
	jQuery.ajax({
		url:url,
		type:"GET",
		success:function(html){
			jQuery('#pollQuestion').empty();
			jQuery('#pollQuestion').append(html);				
		}
	});		
}

function savePollAnswer(pollID, answerID) {
	var url = SETTINGS.webRoot + "intranet/pollControl.php?mode=logVote&pollID=" + pollID+"&answerID="+answerID;
	jQuery.ajax({
		url:url,
		type:"GET",
		success:function(html){
			return true;
		}
	});		
}


function calculateDistanceTravelled(obj) {
	var walkpace = document.getElementById('walkpace').value;
	var stridelength = document.getElementById('stridelength').value;
	

	
	if(obj.attr('value')){
		var numSteps = 0;
		jQuery(".numSteps").each( function () {
			if (parseFloat(jQuery(this).attr("value")) > 0) {
				var selectValue = jQuery(this).parents('div.field').prev('div.field').children('div').children('select').attr('value');
				var temp = parseFloat(jQuery(this).attr("value"));
					
				if(selectValue == "miles"){
					numSteps += (temp * 5280) / stridelength;
				}else if(selectValue == "minutes"){
					numSteps += (((temp/60)*walkpace) * 5280) / stridelength;
				}else if(selectValue == "steps"){
					numSteps += temp;
				}
			}
		});
		
		var milesWalked = Math.round(((numSteps * stridelength) / 5280)*100)/100;
		
		var boxyobj = Boxy.get(obj);
		boxyobj.setTitle('Total Distance Traveled: '+milesWalked+' miles');
		jQuery(".title-bar h2").css('font-weight','bold').css('color','#DDD000');
	}
}

function removeStepField(obj) {	
	
	//Get the number of enter steps fields in this form.
	formObj = obj.parent().parent().parent().parent().parent().parent().parent();
	numStepFields = jQuery("input.numSteps", formObj).length;

	if (numStepFields > 1) {
		obj.parent().parent().parent().parent().parent().remove();	
		calculateDistanceTravelled(obj);
	}
	return;
}

function addStepLog(obj) {
	
	//Get the last fieldset.
	formObj = obj.parent().parent().parent();
	fieldset = jQuery("div.fieldset:last", formObj);
	
	//How many fieldsets do we have?
	var numStepFields = jQuery("input.numSteps", formObj).length;
	var lastFieldID = numStepFields - 1;
	
	//Create a new fieldset and make sure it has the default values.
	newFieldset = jQuery("<div class='fieldset'>"+fieldset.html()+"</div>");
	jQuery("input:first", newFieldset).attr("value", "");
	jQuery("input:first", newFieldset).attr("id", jQuery("input:first", newFieldset).attr("id").replace("-0", "-"+numStepFields));
	jQuery("a:first", newFieldset).attr("onclick", "createCalendarPopup('stepDate-"+numStepFields+"',this);");
	jQuery("#stepDate-"+lastFieldID+"Month", newFieldset).attr("id", "stepDate-"+numStepFields+"Month").attr("name", "stepDate-"+numStepFields+"Month");
	jQuery("#stepDate-"+lastFieldID+"Day", newFieldset).attr("id", "stepDate-"+numStepFields+"Day").attr("name", "stepDate-"+numStepFields+"Day");
	jQuery("#stepDate-"+lastFieldID+"Year", newFieldset).attr("id", "stepDate-"+numStepFields+"Year").attr("name", "stepDate-"+numStepFields+"Year");
	jQuery("#stepDate-"+lastFieldID+"Hour", newFieldset).attr("id", "stepDate-"+numStepFields+"Hour").attr("name", "stepDate-"+numStepFields+"Hour");
	jQuery("#stepDate-"+lastFieldID+"Minute", newFieldset).attr("id", "stepDate-"+numStepFields+"Minute").attr("name", "stepDate-"+numStepFields+"Minute");
	jQuery("#stepDate-"+lastFieldID+"Ampm", newFieldset).attr("id", "stepDate-"+numStepFields+"Ampm").attr("name", "stepDate-"+numStepFields+"Ampm");
	jQuery("#stepDate-"+lastFieldID+"Calendar", newFieldset).attr("id", "stepDate-"+numStepFields+"Calendar").attr("name", "stepDate-"+numStepFields+"Calendar");
	
	//Append the required div so we can validate this form.
	jQuery("#required").attr("value", jQuery("#required").attr("value") + ", numSteps-" + numStepFields);
	
	//Add our new fieldset.
	(jQuery("#boxyControls")).before(newFieldset);
	changeStepsLabel($(newFieldset.contents().find('select[rel="logTypeSelector"]')));
	fixPopupHeight(Boxy.get(obj));
}


function toggleParticipateInNow(checkbox){
	var checked = checkbox.checked;
	if(checked){
		// reset "required" var for validation (add memberid from required)
		// display member id
		document.getElementById('required').value = 'name,address,city,state,zip,county,phone,email,comments,memberid';
		document.getElementById('memberiddiv').style.display = 'block';
	}
	else{
		// reset "required" var for validation (remove memberid from required)
		// hide member id
		document.getElementById('required').value = 'name,address,city,state,zip,county,phone,email,comments';
		document.getElementById('memberiddiv').style.display = 'none';
	}
}	

function fixPopupHeight(popup)
{
	size = popup.getSize();
	if(size[1] > 500)
	{
		popup.resize(587,400);
	}
	popup.center();
}