// JavaScript Document

function navSwitch(dir) {
		
	if (dir=='open') {
					
		$("#rb_toggle").hide();
		$("#rb_menu").show();
		 
		
		$("#headLeft #menu2").animate({ 
			width: "700px"			
		  }, 500, "swing" );
		
				
	}
	else {
			
		$("#headLeft #menu2").animate({ 
			width: "330px"			
		  }, 500, "swing", function() {
			$("#rb_toggle").css("display", "block");
		 $("#rb_menu").css("display", "none");	
		  });
		  				
	}
}

function changeSiteNavLabel(page) {
	src = "images/nav/" + page + ".png";
	document.getElementById("mainMenuLabel").src = src;
	sitenavLink = "sitenav_"+page;
	//alert(sitenavLink);
	document.getElementById(sitenavLink).style.color="#fff";
}

 
function isPluckLoggedIn() {
	return currentProfileID;
}

//this function is called from UserInfo.ascx
function submitUserRequest() {    
    
    if (currentProfileID == "-1") {
        document.getElementById("sitenav_myruncentre").href = "PleaseRegister.aspx";	
		return null;
	}
    
	var requestBatch = new RequestBatch();  
	// add the userKey to the request
	//It's not always the current user whose info we want.
	//If there's a paramter in the querystring pointing to a user's id, use that instead

	var otherUser = gSiteLife.GetParameter('userid');
	//alert(otherUser);
	if (otherUser != currentProfileID && otherUser != null) {
	    var userKey = new UserKey(otherUser);
	}
	else {
	    var userKey = new UserKey(currentProfileID);
	}
		
	requestBatch.AddToRequest(userKey);   
		 
	var groupPage = new CommunityGroupMembershipPage(userKey, 10, 1	);
	groupPage.Key = userKey;
	
	requestBatch.AddToRequest(groupPage);
		
	// initiate the request.  The response will be passed to the renderUserData() method.  
	
	requestBatch.BeginRequest(serverUrl, renderUserData);   
}    

// writes the user data into a <div> tag on the page    
function renderUserData(responseBatch) {    
    //console.dir(responseBatch);
    checkPluckResponseMessages(responseBatch);
    
	if (responseBatch.Responses.length == 0) {  
		 $("#pluckUser").html('User not found');  
	}    

	// get the user object out of the response  
	var user = responseBatch.Responses[0].User;
	var LastUpdated = user.LastUpdated.split(" ");
	$("#sectionHead #icon").css("display", "block");
	$("#UserAvatar").attr("src", user.AvatarPhotoUrl);
	$("#pluckUser").html(user.DisplayName);
	$("#pluckLastUpdated").html(LastUpdated[0]);

	var aboutMe = '';
	var tooLong = 210 - 3; //two lines of text
	
	if (user.AboutMe.length > tooLong) {
	    aboutMe = user.AboutMe.substring(0, tooLong) + '...'; 
	} else {
	    aboutMe = user.AboutMe;
	}
	
	if (user.ExtendedProfile.status != undefined && user.ExtendedProfile.status != "")
	{
		$("#pluckStatus").html(user.ExtendedProfile.status);
	} else {
		if (currentProfileID == user.UserKey.Key) {
		    $("#PluckStatusInput").css("display", "block");
		    $("#pluckStatus").css("display", "none");
		    $("#status").val("How do you feel about RUNNING today?");
		}
		else {
		   $("#pluckStatus").html("<br>"); 
		}
	}
	
	if (document.getElementById("pluckStatus") != null && document.getElementById("pluckStatus").innerHTML != "" ) {
		if (user.ExtendedProfile.Mood == "hate") {
			document.getElementById("sectionHead").style.backgroundImage = "url(/images/headers/hate-bg.png)";
			document.getElementById("hate").style.backgroundImage = "url(/images/Buttons/hate-black.gif)";
			document.getElementById("love").style.backgroundImage = "url(/images/Buttons/love-black.gif)";
		}
		else {
			document.getElementById("sectionHead").style.backgroundImage = "url(/images/headers/love-bg.png)";
			document.getElementById("hate").style.backgroundImage = "url(/images/Buttons/hate-red.gif)";
			document.getElementById("love").style.backgroundImage = "url(/images/Buttons/love-red.gif)";
		}
	}
	
	var location = "";
	var userLocation ="(Unknown Location)";
	
	if (user.ExtendedProfile.neighbourhood != undefined && user.ExtendedProfile.neighbourhood != "") {
		if (user.Location != undefined && user.Location != "") {
			userLocation ="(" + user.ExtendedProfile.neighbourhood + ", " + user.Location + ")";
		}
	}
	else {
		if (user.Location != undefined && user.Location != "") {
			userLocation ="(" + user.Location + ")";
		}
	}
	    
    $("#Location").html(userLocation);
    
	
    //get the user's groups out of the response
    if (responseBatch.Responses.length > 0) {
		groupIDs = new Array();
		groupAdminIDs = new Array();
		addUsersGroupIDsToCookie(responseBatch.Responses[1])
    }

    if (window.exRenderUserData != null) {        
        window.exRenderUserData(responseBatch);
    }
}  

//this function is called from RouteSelection.ascx
function submitRouteCreatorUserRequest(profileID) {

    if (profileID < 0) {
        return null;
    }
		
	var requestBatch = new RequestBatch();  
	// add the userKey to the request

	var userKey = new UserKey(profileID);
	requestBatch.AddToRequest(userKey);

	// initiate the request.  The response will be passed to the renderRouteCreatorUserData() method.
	requestBatch.BeginRequest(serverUrl, renderRouteCreatorUserData);   
}    

// writes the user data into a <div> tag on the page
function renderRouteCreatorUserData(responseBatch) {   
    if (responseBatch.Responses.length == 0) {
        $("#RouteCreator2").hide();
    }
    
    // get the user object out of the response  
    var user = responseBatch.Responses[0].User;
    
    $("#RouteCreator2UserAvatar").attr("src", user.AvatarPhotoUrl);
    $("#RouteCreator2PluckUser").html(user.DisplayName);
}


var groupIDs = new Array();
var groupAdminIDs = new Array();

function addUsersGroupIDsToCookie(groups) {
///adds the user's group ids (and the admin group ids) to a cookie, which is them processed on the server side for permissions

	
    var numGroupsTotal = 0;
    var currentGroupPage = 1;
    				
	if (groups != null) {



	    var numGroupsThisResponse = groups.CommunityGroupMembershipPage.CommunityGroupMemberships.length;
	    var numGroupsTotal = groups.CommunityGroupMembershipPage.NumberOfCommunityGroupMemberships;
		
		currentGroupPage = groups.CommunityGroupMembershipPage.OnPage;
		
		for (var j = 0; j < numGroupsThisResponse; j++) { //>
			var member = groups.CommunityGroupMembershipPage.CommunityGroupMemberships[j];
			
			var groupID = member.CommunityGroup.CommunityGroupKey.Key;
			groupIDs.push(groupID);	
			if (member.MembershipTier == "GroupAdmin") {
				groupAdminIDs.push(groupID);
			}			
		}
	}
	
	
	if (groupIDs.length >= numGroupsTotal)
	{	
		$.cookie('lrm_groups', groupIDs.join(";"));
		$.cookie('lrm_admingroups', groupAdminIDs.join(";"));
	} else  {
		
		currentGroupPage++;
		
		//get the next page of groups
		var requestBatch = new RequestBatch();  
		
		var userKey = new UserKey(currentProfileID); 
					 
		var groupPage = new CommunityGroupMembershipPage(userKey, 10,  currentGroupPage);
		groupPage.Key = userKey;
	
		requestBatch.AddToRequest(groupPage);
		requestBatch.BeginRequest(serverUrl, getPagedGroupsResponse);   
		
	}
}

//get the paged result of the user's groups
function getPagedGroupsResponse(responseBatch) {
    //console.dir(responseBatch);
	 if (responseBatch.Responses.length > 0) {
		addUsersGroupIDsToCookie(responseBatch.Responses[0])
    }
}


function checkPluckResponseMessages(responseBatch) 
{
	var msg = new Array();
    for (var i=0; i<responseBatch.Messages.length;i++) {
		msg.push(responseBatch.Messages[i].Message);
    }
       
	if (msg.length == 1 && msg[0].toLowerCase() == "ok") {
		return true;
	} else {
		throw new Error("An error occurred when accessing sitelife data.\n" + msg.join("\n"));		
	}
	
}

 
                
//    google.setOnLoadCallback(initializeUserLocation);
//    google.load("maps", "2");    
//    var userGeocoder;
//    function initializeUserLocation() {
//        getUserCityLatLng(currentPostalCode);
//    }

//    function getUserCityLatLng(postalcode) {
//		
//        userGeocoder = new GClientGeocoder();
//        userGeocoder.getLatLng(postalcode, GetLatLng);

//    }

//    function GetLatLng(point) {

//        if (!point) {

//        }
//        else {
//            userGeocoder.getLocations(point, GetCityAndProvince);
//        }
//    }

//    function GetCityAndProvince(response) {


//        var place = response.Placemark[0];
//        for (var i = 0; i < response.Placemark.length; i++) {
//            if (response.Placemark[i].AddressDetails.Accuracy > place.AddressDetails.Accuracy) {
//                place = response.Placemark[i];
//            }
//        }

//        var spanCity = document.getElementById("pluckCity");
//        var spanProvince = document.getElementById("pluckProvince");


//        var city = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
//        var province = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;


//        spanCity.innerHTML = city;
//        spanProvince.innerHTML = province;
//        $(".location").fadeIn();
//    }   


function InsertCustomGroupData(id) {
	$('#divStatus').html('Loading, please wait...');
	
	//alert($('#frmMain').serialize());

	$.post('/CustomGroup.aspx?m=1', $('#group').serialize(), function(a_objResponse){
		$('#divStatus').html('');
		
		if (a_objResponse.status) {
            pageTracker._trackPageview("/PluckEvent/CreatedGroup/");
            newURL = 'GroupProfile.aspx?slGroupKey=' + id;
            window.location = newURL;
		}
		
		else {
			alert("There was an error in creating your clinic.  Please try again.")
		}
		
		//$('#divAjaxResponseArticles').html(a_objResponse);
	}, 'json');
}

function UpdateCustomGroupData(id) {
	$('#divStatus').html('Loading, please wait...');
	
	//alert($('#frmMain').serialize());

	$.post('/CustomGroup.aspx?m=3&i='+id, $('#group').serialize(), function(a_objResponse){
		$('#divStatus').html('');
		
		if (a_objResponse.status) {
            newURL = 'GroupProfile.aspx?slGroupKey=' + id;
            window.location = newURL;
		}
		
		else {
			alert("There was an error in creating your clinic.  Please try again.")
		}
		
		//$('#divAjaxResponseArticles').html(a_objResponse);
	}, 'json');
}

function ReadCustomGroupData(id) {
	//$('#divStatus').html('Loading, please wait...');
	
	//alert($('#frmMain').serialize());

    $.post('/CustomGroup.aspx?m=2&i=' + id, $('#group').serialize(), function(a_objResponse) {
        $('#divStatus').html('');

        if (a_objResponse.status) {

            if (a_objResponse.customGroup != "false") {
                //alert(a_objResponse.customGroup.neighbourhood+ ", "+a_objResponse.customGroup.location);
                if (a_objResponse.customGroup.daysIRun != null && a_objResponse.customGroup.daysIRun) {
                    if (document.getElementById("groupRunsOn") != null) {
                        document.getElementById("groupRunsOn").innerHTML = a_objResponse.customGroup.daysIRun;
                    }
                }
                if (a_objResponse.customGroup.timeOfRunWeekdays != "-1") {
                    if (document.getElementById("grouptimeOfRunWeekdays") != null) {
                        document.getElementById("grouptimeOfRunWeekdays").innerHTML = a_objResponse.customGroup.timeOfRunWeekdays + " on weekdays";
                    }
                }
                if (a_objResponse.customGroup.timeOfRunWeekends != "-1") {
                    if (document.getElementById("grouptimeOfRunWeekends") != null) {
                        document.getElementById("grouptimeOfRunWeekends").innerHTML = a_objResponse.customGroup.timeOfRunWeekends + " on weekends";
                    }
                }
                if (a_objResponse.customGroup.goalDistance == "1") {
                    goalDistance = "5";
                }
                else if (a_objResponse.customGroup.goalDistance == "2") {
                    goalDistance = "10";
                }
                else if (a_objResponse.customGroup.goalDistance == "3") {
                    goalDistance = "15";
                }
                else if (a_objResponse.customGroup.goalDistance == "4") {
                    goalDistance = "25";
                }
                else {
                    goalDistance = a_objResponse.customGroup.goalDistance;
                }

                if (goalDistance != "-1") {
                    if (document.getElementById("groupGoalDistance") != null) {
                        document.getElementById("groupGoalDistance").innerHTML = goalDistance + " in ";
                    }

                    if (document.getElementById("groupGoalTime") != null) {
                        if (document.getElementById("groupGoalTime") != "") {
                            document.getElementById("groupGoalTime").innerHTML = a_objResponse.customGroup.goalTime;
                        }
                    }
                }
                //alert(a_objResponse.customGroup.headline);
                if (a_objResponse.customGroup.headline != undefined) {
                    document.getElementById("groupStatus").innerHTML = a_objResponse.customGroup.headline;
                }

                //alert(a_objResponse.customGroup.neighbourhood);
                if (a_objResponse.customGroup.neighbourhood != undefined) {
                    neighbourhood = a_objResponse.customGroup.neighbourhood;
                    if (neighbourhood.length > 30) {
                        neighbourhood = neighbourhood.substr(0, 30) + "...";
                    }
                    document.getElementById("groupNeighbourhood").innerHTML = neighbourhood + ", ";
                }
                if (a_objResponse.customGroup.location != "") {
                    document.getElementById("groupCityProvince").innerHTML = a_objResponse.customGroup.location;
                }
            }
        }

        else {
            //alert('faliure!');
        }

        //$('#divAjaxResponseArticles').html(a_objResponse);
    }, 'json');
}

function ReadCustomGroupDataForEdit(id) {
	//$('#divStatus').html('Loading, please wait...');
	
	//alert($('#frmMain').serialize());

	$.post('/CustomGroup.aspx?m=2&i='+id, $('#group').serialize(), function(a_objResponse){
		$('#divStatus').html('');
		
		if (a_objResponse.status) {
			
			//alert("daysIRun="+a_objResponse.customGroup.daysIRun);
			//alert("runDistance="+a_objResponse.customGroup.runDistance);
			var daysIRun = a_objResponse.customGroup.daysIRun.split(", ");
			for (z = 0; z < daysIRun.length; z++) {
				for (i = 0; i < document.forms['group'].elements.length; i++) {
					el = document.forms['group'].elements[i];
					if (el.type == "checkbox" && el.name.indexOf("daysIRun") != -1) {
						if (el.value == daysIRun[z]) {
							el.checked = true;
						}
					}
				}
			}
			
			var runDistance = a_objResponse.customGroup.runDistance.split(",");
			for (z = 0; z < runDistance.length; z++) {
				for (i = 0; i < document.forms['group'].elements.length; i++) {
					el = document.forms['group'].elements[i];
					if (el.type == "checkbox" && el.name.indexOf("runDistance") != -1) {
						//id="runDistance"+runDistance[z];
						//alert("el.name="+el.name+" || runDistance[z]="+runDistance[z]+" || id="+id+" || el.value="+el.value);
						if (el.value == runDistance[z]) {
							el.checked = true;
						}
					}
				}
			}
			
			weekend = "we_" + a_objResponse.customGroup.timeOfRunWeekends;
			weekday = "wd_" + a_objResponse.customGroup.timeOfRunWeekdays;
			
			//alert(weekend+ " | "+weekday);
			
			document.getElementById(weekend).selected = true;
			document.getElementById(weekday).selected = true;
			
			//document.getElementById("goalDistance").value = a_objResponse.customGroup.goalDistance;
			goalDistance = a_objResponse.customGroup.goalDistance;
				//alert(a_objResponse.customGroup.goalDistance);
				if (goalDistance == "5k" || goalDistance == "10k" || goalDistance == "15k" || goalDistance == "HalfMarathon" || goalDistance == "Marathon") {
					document.getElementById(goalDistance).selected = true;
				}
                    else if (goalDistance == "5") {
                        document.getElementById("5k").selected = true;
                    }
                    else if (goalDistance == "10") {
                        document.getElementById("10k").selected = true;
                    }
                    else if (goalDistance == "15") {
                        document.getElementById("15k").selected = true;
                    }
                    else if (goalDistance == "25") {
                        document.getElementById("goalDistanceOther").style.display = "inline";
                        document.getElementById("goalDistanceOther").value = "25";
                    }
				else {
					document.getElementById("goalDistanceOther").style.display = "inline";
					document.getElementById("goalDistanceOther").value = goalDistance;
				}
			goalSplit = a_objResponse.customGroup.goalTime.split(":");
			document.getElementById("goalTime1").value = goalSplit[0];
			document.getElementById("goalTime2").value = goalSplit[1];
			document.getElementById("goalTime3").value = goalSplit[2];
			
			document.getElementById("headline").value = a_objResponse.customGroup.headline;
			document.getElementById("neighbourhood").value = a_objResponse.customGroup.neighbourhood;
			
			var postalInsert1 = a_objResponse.customGroup.postal.substr(0, 3);
            var postalInsert2 = a_objResponse.customGroup.postal.substr(4, 6);
            document.getElementById("postal1").value = postalInsert1;
            document.getElementById("postal2").value = postalInsert2;
			//document.getElementById("postal").value = a_objResponse.customGroup.postal;
			
			
			locationValues = a_objResponse.customGroup.location.split(", ");
			//alert(locationValues[0]+ " | "+locationValues[1]);
			document.getElementById("city").value = locationValues[0];
			document.getElementById(locationValues[1]).selected = true;
			
		}
		
		else {
			//alert('faliure!');
		}
		
		//$('#divAjaxResponseArticles').html(a_objResponse);
	}, 'json');
}

function InsertCustomClinicData(clinicId) {
	//$('#divStatus').html('Loading, please wait...');
	
	//alert($('#frmMain').serialize());

	$.post('/CustomClinic.aspx?m=1', $('#group').serialize(), function(a_objResponse){
		$('#divStatus').html('');
		
		if (a_objResponse.status == "true") {
            pageTracker._trackPageview("/PluckEvent/CreatedClinic/");
			newURL = 'ClinicProfile.aspx?groupId='+clinicId;
			window.location = newURL;
		}
		
		else {
			alert("There was an error in creating your clinic.  Please try again.")
		}
		
		//$('#divAjaxResponseArticles').html(a_objResponse);
	}, 'json');
}

function ReadCustomClinicData(id) {
	//$('#divStatus').html('Loading, please wait...');
	
	//alert($('#frmMain').serialize());

    $.post('/CustomClinic.aspx?m=2&i=' + id, $('#group').serialize(), function(a_objResponse) {
        $('#divStatus').html('');

        if (a_objResponse.status) {
            //alert(a_objResponse.customGroup.neighbourhood+ ", "+a_objResponse.customGroup.location);
            
            if (a_objResponse.customGroup.feeAmount != null) {
                if (a_objResponse.customGroup.feeAmount.indexOf("$") > 0) {
                    clinicCostValue = a_objResponse.customGroup.feeAmount;
                }
                else {
                    clinicCostValue = "$" + a_objResponse.customGroup.feeAmount;
                }
                document.getElementById("clinicCost").innerHTML = clinicCostValue;
            }
            if (a_objResponse.customGroup.deadline != null) {
                document.getElementById("deadline").innerHTML = a_objResponse.customGroup.deadline;
            }
            if (a_objResponse.customGroup.howToRegister != null) {
                document.getElementById("howToRegister").innerHTML = a_objResponse.customGroup.howToRegister;
            }
            if (a_objResponse.customGroup.headline != null) {
                document.getElementById("clinicGoal").innerHTML = a_objResponse.customGroup.headline;
            }
            if (a_objResponse.customGroup.duration != null) {
                document.getElementById("duration").innerHTML = a_objResponse.customGroup.duration + ' weeks';
            }
            if (a_objResponse.customGroup.neighbourhood != "") {
                neighbourhood = a_objResponse.customGroup.neighbourhood;
                if (neighbourhood.length > 30) {
                    neighbourhood = neighbourhood.substr(0, 30) + "...";
                }
                document.getElementById("groupNeighbourhood").innerHTML = neighbourhood + ", ";
            }
            if (a_objResponse.customGroup.startdate != null) {
                document.getElementById("starting").innerHTML = a_objResponse.customGroup.startdate;
            }
            
            document.getElementById("groupCityProvince").innerHTML = a_objResponse.customGroup.location;
            document.getElementById("groupStatus").innerHTML = a_objResponse.customGroup.headline;
            
            if (a_objResponse.customGroup.r_name != "") {
                document.getElementById("organizedByHeader").style.display = "block";
                document.getElementById("organizedByTable").style.display = "block";
                document.getElementById("r_name").innerHTML = a_objResponse.customGroup.r_name;
                document.getElementById("r_phone").innerHTML = a_objResponse.customGroup.r_phone;
                document.getElementById("r_websiteLink").innerHTML = a_objResponse.customGroup.r_website;
                if (a_objResponse.customGroup.r_website.indexOf("http") > 0) {
                    document.getElementById("r_websiteLink").href = a_objResponse.customGroup.r_website;
                }
                else {
                    document.getElementById("r_websiteLink").href = "http://" + a_objResponse.customGroup.r_website;
                }
                var storeAddress = a_objResponse.customGroup.r_address + "<br>" + a_objResponse.customGroup.r_city + ", " + a_objResponse.customGroup.r_province + "<br>" + a_objResponse.customGroup.r_postal;
                document.getElementById("r_address").innerHTML = storeAddress;
            }
        }

        else {
            //alert('faliure!');
        }

        //$('#divAjaxResponseArticles').html(a_objResponse);
    }, 'json');
}

function ReadCustomClinicDataForEdit(id) {
	//$('#divStatus').html('Loading, please wait...');
	
	//alert($('#frmMain').serialize());

	$.post('/CustomClinic.aspx?m=2&i='+id, $('#group').serialize(), function(a_objResponse){
		$('#divStatus').html('');
		
		if (a_objResponse.status) {
			//alert(a_objResponse.customGroup.neighbourhood+ ", "+a_objResponse.customGroup.location);
			document.getElementById("startdate").value = a_objResponse.customGroup.startdate;
			document.getElementById("enddate").value = a_objResponse.customGroup.enddate;
			document.getElementById("headline").value = a_objResponse.customGroup.headline;
			
			runDistance = a_objResponse.customGroup.runDistance;
				//alert(a_objResponse.customGroup.runDistance);
				if (runDistance == "5k" || runDistance == "10k" || runDistance == "15k" || runDistance == "HalfMarathon" || runDistance == "Marathon") {
					document.getElementById(runDistance).selected = true;
				}
                    else if (runDistance == "5") {
                        document.getElementById("5k").selected = true;
                    }
                    else if (runDistance == "10") {
                        document.getElementById("10k").selected = true;
                    }
                    else if (runDistance == "15") {
                        document.getElementById("15k").selected = true;
                    }
                    else if (runDistance == "25") {
                        document.getElementById("runDistanceOther").style.display = "inline";
                        document.getElementById("runDistanceOther").value = "25";
                    }
				else {
					document.getElementById("runDistanceOther").style.display = "inline";
					document.getElementById("runDistanceOther").value = runDistance;
				}
			
			//document.getElementById(a_objResponse.customGroup.runDistance).selected = true;
			locationValues = a_objResponse.customGroup.location.split(" ");
			document.getElementById("city").value = locationValues[0];
			document.getElementById(locationValues[1]).selected = true;
			document.getElementById("neighbourhood").value = a_objResponse.customGroup.neighbourhood;
			document.getElementById("postal").value = a_objResponse.customGroup.postal;
			document.getElementById("r_name").value = a_objResponse.customGroup.r_name;
			document.getElementById("r_phone").value = a_objResponse.customGroup.r_phone;
			document.getElementById("r_address").value = a_objResponse.customGroup.r_address;
			document.getElementById("r_city").value = a_objResponse.customGroup.r_city;
			retailerProvinceID="r_"+a_objResponse.customGroup.r_province;
			//alert(retailerProvinceID);
			document.getElementById(retailerProvinceID).selected = true;
			document.getElementById("r_postal").value = a_objResponse.customGroup.r_postal;
			document.getElementById("r_website").value = a_objResponse.customGroup.r_website;
			if (a_objResponse.customGroup.r_postal == "yes") {
				document.getElementById("fee").checked = "true";
			}
			document.getElementById("feeAmount").value = a_objResponse.customGroup.feeAmount;
			document.getElementById("deadline").value = a_objResponse.customGroup.deadline;
			document.getElementById("howToRegister").value = a_objResponse.customGroup.howToRegister;
		}
		
		else {
			//alert('faliure!');
		}
		
		//$('#divAjaxResponseArticles').html(a_objResponse);
	}, 'json');
}

function InsertCustomEventData(clinicId) {
	//$('#divStatus').html('Loading, please wait...');
	
	//alert($('#frmMain').serialize());

	$.post('/CustomEvent.aspx?m=1', $('#event').serialize(), function(a_objResponse){
		$('#divStatus').html('');
		
		if (a_objResponse.status) {
			//alert(clinicId+" - "+raceLength);
            pageTracker._trackPageview("/PluckEvent/CreatedRace/");
			newURL = 'CreateRace.aspx?groupId=' + clinicId;
			window.location = newURL;
		}
		
		else {
			alert("There was an error in creating your event.  Please try again.")
		}
		
		//$('#divAjaxResponseArticles').html(a_objResponse);
	}, 'json');
}

function FinalizeCustomEventData(clinicId) {
	//$('#divStatus').html('Loading, please wait...');
	
	//alert($('#frmMain').serialize());

	$.post('/CustomEvent.aspx?m=1', $('#event').serialize(), function(a_objResponse){
		$('#divStatus').html('');
		
		if (a_objResponse.status == "true") {
			newURL = 'EventProfile.aspx?groupId=' + clinicId;
			window.location = newURL;
		}
		
		else {
			alert("There was an error in creating your event.  Please try again.")
		}
		
		//$('#divAjaxResponseArticles').html(a_objResponse);
	}, 'json');
}

function ReadCustomEventData(id,view) {
	//$('#divStatus').html('Loading, please wait...');
	
	//alert($('#frmMain').serialize());

	$.post('/CustomEvent.aspx?m=2&i='+id, $('#event').serialize(), function(a_objResponse){
		$('#divStatus').html('');
		
		//alert(view);
		
		if (a_objResponse.status) {
			
			if (view == "CreateEventPreview") {
				document.getElementById("headline").value = a_objResponse.customGroup.headline;
				document.getElementById("website").value = a_objResponse.customGroup.website;
				//document.getElementById("raceLinks").innerHTML = a_objResponse.customGroup.subRaces;
				document.getElementById("neighbourhood").value = a_objResponse.customGroup.neighbourhood;
				var locationValues = a_objResponse.customGroup.location.split(" ");
				document.getElementById("city").value = locationValues[0];
				document.getElementById(locationValues[1]).selected = true;
				document.getElementById("startdate").value = a_objResponse.customGroup.startDate;
				document.getElementById("enddate").value = a_objResponse.customGroup.endDate;
				
				document.getElementById("currentRacesStash").innerHTML = a_objResponse.customGroup.subRaces;
			} else {
				document.getElementById("groupStatus").innerHTML = a_objResponse.customGroup.headline;
				document.getElementById("website").innerHTML = a_objResponse.customGroup.website;
				document.getElementById("websiteHref").href = a_objResponse.customGroup.website;
				document.getElementById("raceLinks").innerHTML = a_objResponse.customGroup.subRaces;
				document.getElementById("groupNeighbourhood").innerHTML = a_objResponse.customGroup.neighbourhood;
				document.getElementById("groupCityProvince").innerHTML = a_objResponse.customGroup.location;
				document.getElementById("groupLastUpdated").innerHTML = a_objResponse.customGroup.startDate;
			}
		}
		
		else {
			//alert('faliure!');
		}
		
		//$('#divAjaxResponseArticles').html(a_objResponse);
	}, 'json');
}


function readCustomEventDataForRaceIndex(id){
    var ret;
    var qString = "/CustomEvent.aspx?m=2&i=" + id;
     /*$.ajax({
        async: false,
        type: "POST",
        url: qString,
        data: {a_objResponse},
        dataType: "json",
        success: function(data){
           ret = a_objResponse.customGroup.startDate;
        }}
     });
     return ret;
  }*/

    $.ajax({
       async: false,
       type: "POST",
       url: qString,
       data: {},
       dataType: "json",
       success: function(a_objResponse){
         if (a_objResponse.customGroup) {
            SplitDate = a_objResponse.customGroup.startDate.split("/");
            PrintMonth = SplitDate[0];
            PrintDay = SplitDate[1];
            PrintYear = SplitDate[2];
            PrintDate = "June 3, 2009";
            if (PrintMonth == "01") {
                PrintDate = "January " + PrintDay + ", " + PrintYear;
            }
            if (PrintMonth == "02") {
                PrintDate = "February " + PrintDay + ", " + PrintYear;
            }
            if (PrintMonth == "03") {
                PrintDate = "March " + PrintDay + ", " + PrintYear;
            }
            if (PrintMonth == "04") {
                PrintDate = "April " + PrintDay + ", " + PrintYear;
            }
            if (PrintMonth == "05") {
                PrintDate = "May " + PrintDay + ", " + PrintYear;
            }
            if (PrintMonth == "06") {
                PrintDate = "June " + PrintDay + ", " + PrintYear;
            }
            if (PrintMonth == "07") {
                PrintDate = "July " + PrintDay + ", " + PrintYear;
            }
            if (PrintMonth == "08") {
                PrintDate = "August " + PrintDay + ", " + PrintYear;
            }
            if (PrintMonth == "09") {
                PrintDate = "September " + PrintDay + ", " + PrintYear;
            }
            if (PrintMonth == "10") {
                PrintDate = "October " + PrintDay + ", " + PrintYear;
            }
            if (PrintMonth == "11") {
                PrintDate = "November " + PrintDay + ", " + PrintYear;
            }
            if (PrintMonth == "12") {
                PrintDate = "December " + PrintDay + ", " + PrintYear;
            }
            ret = PrintDate;
         }
       }
     });
    return ret;
}

/*function readCustomEventDataForRaceIndex(id) {
    

    
    
    $.post('/CustomEvent.aspx?m=2&i=' + id, $('#event').serialize(), function(a_objResponse) {
        async: false;
        //if (a_objResponse.status) {
            //return (id);
            //date = a_objResponse.customGroup.startDate;
            //alert(date);
            //return (date);
            return ("may 8, 2009");
        //}
        //else {
            //alert('faliure!');
        //}
    }, 'json');
    
}*/

function InsertCustomRaceData(clinicId,parentEventId) {
	//$('#divStatus').html('Loading, please wait...');
	
	//alert($('#frmMain').serialize());

	$.post('/CustomRace.aspx?m=1', $('#event').serialize(), function(a_objResponse){
		$('#divStatus').html('');
		
		if (a_objResponse.status == "true") {
			newURL = 'CreateEvent.aspx?groupId=' + parentEventId + '&action=raceAdded';
			window.location = newURL;
		}
		
		else {
			alert("There was an error in creating your event.  Please try again.")
		}
		
		//$('#divAjaxResponseArticles').html(a_objResponse);
	}, 'json');
}

function UpdateCustomRaceData(id) {
	//$('#divStatus').html('Loading, please wait...');
	
	//alert($('#frmMain').serialize());

	$.post('/CustomRace.aspx?m=3&i='+id, $('#event').serialize(), function(a_objResponse){
		$('#divStatus').html('');
		
		if (a_objResponse.status == "true") {
			newURL = 'RaceProfile.aspx?groupId='+id;
			window.location = newURL;
		}
		
		else {
			alert("There was an error in creating your event.  Please try again.")
		}
		
		//$('#divAjaxResponseArticles').html(a_objResponse);
	}, 'json');
}

function ReadCustomRaceData(id,view) {
	//$('#divStatus').html('Loading, please wait...');
	
	//alert($('#frmMain').serialize());

    $.post('/CustomRace.aspx?m=2&i=' + id, $('#event').serialize(), function(a_objResponse) {
        $('#divStatus').html('');

        function clientCallBack(responseBatch) {
            document.getElementById("parentLink").innerHTML = responseBatch.Responses[0].CommunityGroup.Title;
            document.getElementById("parentLink").href = 'EventProfile.aspx?groupId=' + communityGroupKey;
        }

        if (a_objResponse.status) {
            if (view == "CreateEventPreview") {
                document.getElementById("headline").value = a_objResponse.customGroup.headline;
                if (a_objResponse.customGroup.feeAmount == "yes") {
                    document.getElementById("feeAmount").checked = true;
                }

                document.getElementById("feeAmount").value = a_objResponse.customGroup.feeAmount;
                document.getElementById("deadline").value = a_objResponse.customGroup.deadline;
                document.getElementById("howToRegister").value = a_objResponse.customGroup.howToRegister;

                racelength = a_objResponse.customGroup.raceLength;
                //alert(a_objResponse.customGroup.raceLength);
                if (racelength == "5k" || racelength == "10k" || racelength == "15k" || racelength == "HalfMarathon" || racelength == "Marathon") {
                    document.getElementById(racelength).selected = true;
                }
                else {
                    document.getElementById("raceLengthOther").style.display = "inline";
                    document.getElementById("raceLengthOther").value = racelength;
                }

                //alert(a_objResponse.customGroup.time);

                time = a_objResponse.customGroup.time.split(" ");
                timeNums = time[0].split(":");
                time1 = "t1_" + timeNums[0];
                time2 = "t2_" + timeNums[1];
                ampm = time[1];
                //alert(time1+" || "+time2+" || "+ampm);
                document.getElementById(time1).selected = true;
                document.getElementById(time2).selected = true;
                document.getElementById(ampm).selected = true;
                document.getElementById("date").value = a_objResponse.customGroup.date;
                document.getElementById("routeInfoStash").value = a_objResponse.customGroup.routeInfo;

                //var requestBatch = new RequestBatch();
                //communityGroupKey = a_objResponse.customGroup.parentEventId;
                //requestBatch.AddToRequest(new CommunityGroupKey(communityGroupKey));  
                //requestBatch.BeginRequest(serverUrl, clientCallBack);

                //function clientCallBack(responseBatch) {
                ////    alert(responseBatch.Responses[0].CommunityGroup.Title);
                //    document.getElementById("parentLink").innerHTML = responseBatch.Responses[0].CommunityGroup.Title;
                //    document.getElementById("parentLink").innerHTML = responseBatch.Responses[0].CommunityGroupKey.Key;
                //}

            }
            else {
                //alert("McFly?");
                document.getElementById("groupStatus").innerHTML = a_objResponse.customGroup.headline;
                if (a_objResponse.customGroup.feeAmount.indexOf("$") > 0) {
                    clinicCost = a_objResponse.customGroup.feeAmount;
                }
                else {
                    clinicCost = "$" + a_objResponse.customGroup.feeAmount;
                }
                document.getElementById("clinicCost").innerHTML = clinicCost;
                document.getElementById("deadline").innerHTML = a_objResponse.customGroup.deadline;
                document.getElementById("howToRegister").innerHTML = a_objResponse.customGroup.howToRegister;
                //alert();
                document.getElementById("groupLastUpdated").innerHTML = a_objResponse.customGroup.date;

                var requestBatch = new RequestBatch();
                communityGroupKey = a_objResponse.customGroup.parentEventId;
                //alert(communityGroupKey);
                requestBatch.AddToRequest(new CommunityGroupKey(communityGroupKey));
                //alert(serverUrl);
                requestBatch.BeginRequest(serverUrl, clientCallBack);


            }


            //mapping data

            if (a_objResponse.customGroup.mappingData != "" && a_objResponse.customGroup.mappingData != "58" && a_objResponse.customGroup.mappingData != "43.66290452383666,-79.32746887207031|43.65818541118326,-79.34484958648682") {

                //alert(a_objResponse.customGroup.mappingData);

                $(".MappingDataInput").val(a_objResponse.customGroup.mappingData);

                document.getElementById("googleMap").style.display = "block";

            }



        }

        else {
            //alert('faliure!');
        }

        //$('#divAjaxResponseArticles').html(a_objResponse);
    }, 'json');
}

function approveRace(raceID) {
    var raceKey = new CommunityGroupKey(raceID);
    var requestBatch = new RequestBatch();
    requestBatch.AddToRequest(raceKey);
    requestBatch.BeginRequest(serverUrl, updateCommunityGroup);

    function updateCommunityGroup(responseBatch) {
        //console.dir(responseBatch);
        group = responseBatch.Responses[0].CommunityGroup;
        CategoriesSplit = group.Categories.split("|");
        if (CategoriesSplit[2] == "isapproved") {
            CategoriesSplit[2] = "pendingrelease";
        }
        else {
            CategoriesSplit[2] = "isapproved";
        }
        if (CategoriesSplit[3] != "homepagefeature") {
            CategoriesSplit[3] = "notpromoted";
        }
        //alert(CategoriesSplit[3]);
        var newTags = CategoriesSplit[0] + "|" + CategoriesSplit[1] + "|" + CategoriesSplit[2] + "|" + CategoriesSplit[3];
        requestBatch.AddToRequest(new UpdateCommunityGroupAction(raceKey, group.Title, group.Description, newTags, new CommunityGroupVisibility(group.CommunityGroupVisibility), group.GroupBookmarks, new Section(group.Section)));
        requestBatch.BeginRequest(serverUrl, finishedApprovingGroup);
    }
    function finishedApprovingGroup(responseBatch) {
        //console.dir(responseBatch);
        if (CategoriesSplit[2] == "isapproved") {
            document.getElementById("approvalStatusLink").innerHTML = "Un-Approve";
        }
        else {
            document.getElementById("approvalStatusLink").innerHTML = "Approve Race";
        }
        
        window.location.reload();
    }
}

function promoteRaceToHomepage(raceID) {
    var raceKey = new CommunityGroupKey(raceID);
    var requestBatch = new RequestBatch();
    requestBatch.AddToRequest(raceKey);
    requestBatch.BeginRequest(serverUrl, updateCommunityGroup);

    function updateCommunityGroup(responseBatch) {
        group = responseBatch.Responses[0].CommunityGroup;
        CategoriesSplit = group.Categories.split("|");
        if (CategoriesSplit[3] == "homepagefeature") {
            CategoriesSplit[3] = "notpromoted";
        }
        else {
            CategoriesSplit[3] = "homepagefeature";
        }
        if (CategoriesSplit[2] != "isapproved") {
            CategoriesSplit[2] = "pendingrelease";
        }
        //alert(CategoriesSplit[3]);
        var newTags = CategoriesSplit[0] + "|" + CategoriesSplit[1] + "|" + CategoriesSplit[2] + "|" + CategoriesSplit[3];
        requestBatch.AddToRequest(new UpdateCommunityGroupAction(raceKey, group.Title, group.Description, newTags, new CommunityGroupVisibility(group.CommunityGroupVisibility), group.GroupBookmarks, new Section(group.Section)));
        requestBatch.BeginRequest(serverUrl, finishedApprovingGroup);
    }
    function finishedApprovingGroup(responseBatch) {
        //console.dir(responseBatch);
        if (CategoriesSplit[3] == "homepagefeature") {
            document.getElementById("DiscussionStickUnStick").innerHTML = "Remove from Front Page";
        }
        else {
            document.getElementById("DiscussionStickUnStick").innerHTML = "Post to Front Page";
        }

        window.location.reload();
    }
}

//Group Memebrship Functions

function JoinGroup() {
	var requestBatch = new RequestBatch();	
	
	groupKeyValue = document.getElementById("groupKey").value;
	userKey = currentProfileID;

	try {
	    //AjaxService.BookmarkGroupRuns(groupKeyValue, currentProfileID);
	    AjaxService.ClearRunCache(currentProfileID);
	}catch(err){ }
	
	//membershipTier = "Member";
	//isBanned = "False";
	
	//requestBatch.AddToRequest(new UpdateCommunityGroupMembershipAction(new CommunityGroupKey(groupKey), new UserKey(userKey), new MembershipTier(membershipTier), isBanned));
	requestBatch.AddToRequest(new RequestCommunityGroupMembershipAction(new CommunityGroupKey(groupKeyValue), new UserKey(userKey))); 
	requestBatch.BeginRequest(serverUrl, myCallbackMethod);
	
	function myCallbackMethod(responseBatch) {
		//console.dir(responseBatch);
	    var referrerType = "";
	    ref = document.location.href;
	    if (ref.indexOf("GroupProfile") != -1) {
	        referrerType = "GroupProfile.aspx";
		    pageTracker._trackPageview("/PluckEvent/JoinedGroup/");
	    }
	    else if (ref.indexOf("ClinicProfile") != -1) {
	        referrerType = "ClinicProfile.aspx";
		    pageTracker._trackPageview("/PluckEvent/JoinedRetailClinic/");
	    }
	    else if (ref.indexOf("EventProfile") != -1) {
	        referrerType = "EventProfile.aspx";
	    }
	    else if (ref.indexOf("RaceProfile") != -1) {
	        referrerType = "RaceProfile.aspx"
	    }
		document.getElementById("JoinGroup").style.display = "none";
		document.getElementById("InviteFriendToGroup").style.display = "block";
		document.getElementById("InviteLink").href = "InviteFriends.aspx?slPage=inviteFriend&slGroupKey=" + groupKeyValue + "&cancelUrl=" + referrerType + "%3FgroupID%3D" + groupKeyValue;
		document.getElementById("SendMessageToGroup").style.display = "block";
		document.getElementById("RemoveGroup").style.display = "block";	
	}  
	
}

function RequestMembershipInPrivateGroup(groupKey,el,creatorID) {
    var requestBatch = new RequestBatch();
	groupKeyObject = new CommunityGroupKey(groupKey);
	userKey = new UserKey(currentProfileID);
	
	subject = "loverunningmore.ca - Someone would like to join your group!";
	body = "Please review the pending membership request at http://loverunningmore.ca/PendingGroupMembers.aspx?groupId=" + groupKey;
	
	requestBatch.AddToRequest(new EmailContentWithUserIDAction(new UserKey(creatorID),subject,body));
	requestBatch.AddToRequest(new EmailContentWithUserIDAction(new UserKey("27"),subject,body));
	requestBatch.AddToRequest(new RequestCommunityGroupMembershipAction(groupKeyObject, userKey));
	requestBatch.BeginRequest(serverUrl, myCallbackMethod);
	function myCallbackMethod(responseBatch) {
	    var msg = new Array();
        for (var i=0; i<responseBatch.Messages.length;i++) {
	        msg.push(responseBatch.Messages[i].Message);
        }
	    if (msg[0].toLowerCase() == "ok") {
	        privateGroupLink = "privateGroupLink" + el;
	        document.getElementById(privateGroupLink).innerHTML = "Request sent.";
	    } else {
		    document.getElementById(privateGroupLink).innerHTML = "Please try again.";	
	    } 
	}
}

function RemoveGroup() {
	var requestBatch = new RequestBatch();
	
	groupKey = document.getElementById("groupKey").value;
	userKey = currentProfileID;
	membershipTier = "Member";
	//isBanned = "False";
	requestBatch.AddToRequest(new DeleteContentAction(new CommunityGroupMembershipKey(new CommunityGroupKey(groupKey), new UserKey(userKey))));
	//requestBatch.AddToRequest(new DeleteContentAction(new CommunityGroupMembershipKey(new CommunityGroupKey(groupKey))), new UserKey(userKey));
	//requestBatch.AddToRequest(new DeleteContentAction(new CommunityGroupMembershipKey(new CommunityGroupKey(groupKey)), new UserKey(userKey))); 
	//requestBatch.AddToRequest(new UpdateCommunityGroupMembershipAction(new CommunityGroupKey(groupKey), new UserKey(userKey), new MembershipTier(membershipTier), isBanned));
	//requestBatch.AddToRequest(new RequestCommunityGroupMembershipAction(new CommunityGroupKey(groupKey), new UserKey(userKey))); 
	requestBatch.BeginRequest(serverUrl, myCallbackMethod);
	
	function myCallbackMethod(responseBatch) {
		//console.dir(responseBatch);
		document.getElementById("JoinGroup").style.display = "block";
		document.getElementById("InviteFriendToGroup").style.display = "none";
		document.getElementById("SendMessageToGroup").style.display = "none";
		document.getElementById("RemoveGroup").style.display = "none";

		AjaxService.RemoveGroupRuns(document.getElementById("groupKey").value, currentProfileID);
	}  
	
}

function JoinRace() {
	var requestBatch = new RequestBatch();	
	
	groupKeyValue = document.getElementById("groupKey").value;
	userKey = currentProfileID;
	
	try{
	    AjaxService.ClearRunCache(currentProfileID);
	}catch(err){ }
	
	//membershipTier = "Member";
	//isBanned = "False";
	
	//requestBatch.AddToRequest(new UpdateCommunityGroupMembershipAction(new CommunityGroupKey(groupKey), new UserKey(userKey), new MembershipTier(membershipTier), isBanned));
	requestBatch.AddToRequest(new RequestCommunityGroupMembershipAction(new CommunityGroupKey(groupKeyValue), new UserKey(userKey))); 
	requestBatch.BeginRequest(serverUrl, myCallbackMethod);
	
	function myCallbackMethod(responseBatch) {
		//console.dir(responseBatch);
		document.getElementById("JoinGroup").style.display = "none";
		document.getElementById("InviteFriendToGroup").style.display = "block";
		document.getElementById("InviteLink").href = "InviteFriends.aspx?slPage=inviteFriend&slGroupKey=" + groupKeyValue + "&cancelUrl=GroupProfile.aspx%3FgroupID%3D" + groupKeyValue;
		document.getElementById("RemoveGroup").style.display = "block";	
        pageTracker._trackPageview("/PluckEvent/JoinedRace/");
	}  
	
}

function RemoveRace() {
	var requestBatch = new RequestBatch();
	
	groupKey = document.getElementById("groupKey").value;
	userKey = currentProfileID;
	membershipTier = "Member";
	//isBanned = "False";
	requestBatch.AddToRequest(new DeleteContentAction(new CommunityGroupMembershipKey(new CommunityGroupKey(groupKey), new UserKey(userKey))));
	//requestBatch.AddToRequest(new DeleteContentAction(new CommunityGroupMembershipKey(new CommunityGroupKey(groupKey))), new UserKey(userKey));
	//requestBatch.AddToRequest(new DeleteContentAction(new CommunityGroupMembershipKey(new CommunityGroupKey(groupKey)), new UserKey(userKey))); 
	//requestBatch.AddToRequest(new UpdateCommunityGroupMembershipAction(new CommunityGroupKey(groupKey), new UserKey(userKey), new MembershipTier(membershipTier), isBanned));
	//requestBatch.AddToRequest(new RequestCommunityGroupMembershipAction(new CommunityGroupKey(groupKey), new UserKey(userKey))); 
	requestBatch.BeginRequest(serverUrl, myCallbackMethod);
	
	function myCallbackMethod(responseBatch) {
		//console.dir(responseBatch);
		document.getElementById("JoinGroup").style.display = "block";
		document.getElementById("InviteFriendToGroup").style.display = "none";
		document.getElementById("RemoveGroup").style.display = "none";
	}  
	
}

function InviteFriendToGroup() {
	var requestBatch = new RequestBatch();
	
	groupKey = document.getElementById("groupKey").value;
	userKey = currentProfileID;
	//membershipTier = "Member";
	//isBanned = "False";
	
	//requestBatch.AddToRequest(new UpdateCommunityGroupMembershipAction(new CommunityGroupKey(groupKey), new UserKey(userKey), new MembershipTier(membershipTier), isBanned));
	requestBatch.AddToRequest(new RequestCommunityGroupMembershipAction(new CommunityGroupKey(groupKey), new UserKey(userKey))); 
	requestBatch.BeginRequest(serverUrl, myCallbackMethod);
	
	function myCallbackMethod(responseBatch) {
		//console.dir(responseBatch);
	}  
	
}

// A few form-handling functions
function escapeText(a_strID) {
	var strValue = $(a_strID).text($(a_strID).val()).html();	
	return strValue.replace(/'/g, "\\'");
}

function unescapeText(a_strText) {
	if (a_strText != undefined) {
	    return a_strText.replace(/\\'/g, "'");
	}
}

function adjustImageNames(a_strImagePath) {
	var strSearch = 'small';
	var strReplace = 'medium';
	return a_strImagePath.toLowerCase().replace(strSearch, strReplace);
}

//Real-time Status updates

function SwapStatus() {
	if (document.getElementById("pluckStatus").style.display == "none") {
		document.getElementById("PluckStatusInput").style.display = "block";
		document.getElementById("pluckStatus").style.display = "none";
	}
	else {
		document.getElementById("pluckStatus").style.display = "none";
		document.getElementById("PluckStatusInput").style.display = "block";
	}
}

function changeStatus(mood) {
	//alert("Why refresh?");
	var requestBatch = new RequestBatch();
	// add the userKey to the request  
	var userKey = new UserKey(currentProfileID);
	requestBatch.AddToRequest(userKey);
	requestBatch.BeginRequest(serverUrl, userCallback);

	function userCallback(responseBatch) {
		//console.dir(responseBatch);
		var user = responseBatch.Responses[0].User;
		var aboutMe = user.AboutMe;
		var userLocation = user.Location;
		var gender = user.Sex;
		var extendedProfile = user.ExtendedProfile;
		extendedProfile["Mood"] = mood;
		extendedProfile["status"] = document.getElementById("status").value;
		var requestBatch2 = new RequestBatch();
		requestBatch2.AddToRequest(new UpdateUserProfileAction(userKey, aboutMe, userLocation, "", "4/29/1980", gender, "SharedWithFriends", true, true, true, true, "ca6707af-3223-4147-8500-b865c897cc28", null, extendedProfile));
		requestBatch2.BeginRequest(serverUrl, moodCallback);

		function moodCallback(responseBatch) {
			//console.dir(responseBatch);
		}
	}
	
	if (document.getElementById("pluckStatus").style.display == "none") {
		document.getElementById("PluckStatusInput").style.display = "none";
		document.getElementById("pluckStatus").style.display = "block";
	}
	else {
		document.getElementById("pluckStatus").style.display = "none";
		document.getElementById("PluckStatusInput").style.display = "block";
	}
	
	document.getElementById("pluckStatus").innerHTML = document.getElementById("status").value;
	if (mood == "love") {
		document.getElementById("sectionHead").style.backgroundImage = "url(/images/headers/love-bg.png)";
	}
	else {
		document.getElementById("sectionHead").style.backgroundImage = "url(/images/headers/hate-bg.png)";
	}

	$.get('/UserMood.aspx?m=' + mood, '', function(a_objResponse){}, 'json');	
}

//Love/Hate Comments 
function startComment(mood) {
	if (mood == "love") {
		document.getElementById("commentText").value = "I LOVE this route because... ";	
	}
	else if (mood == "hate") {
		document.getElementById("commentText").value = "I HATE this route because... ";
	}
	document.getElementById("commentText").focus();
}

function days_between(date1, date2) {
		
		var one_day=1000*60*60*24; 
		var x=date1.split("/");     
        var y=date2.split("/");
  //date format(Fullyear,month,date) 


        var date1=new Date(x[2],x[0],(x[1]-1));
  
        var date2=new Date(y[2],y[0],(y[1]-1))
        var month1=x[1]-1;
        var month2=y[1]-1;
        
        //Calculate difference between the two dates, and convert to days

               
        return Math.ceil((date2.getTime()-date1.getTime())/(one_day)/7);
		//alert(_Diff);
	//startdate = new Date();
	
	
    // The number of milliseconds in one day
    //var ONE_DAY = 1000 * 60 * 60 * 24;

    // Convert both dates to milliseconds
    //var date1_ms = date1.getTime();
    //var date2_ms = date2.getTime();

    // Calculate the difference in milliseconds
    //var difference_ms = Math.abs(date1_ms - date2_ms);
    
    // Convert back to days and return
    //alert(Math.round(difference_ms/ONE_DAY));
	//return Math.round(difference_ms/ONE_DAY);

}


function sendPM() {
	subject = document.getElementById("pmSubject").value;
	content = document.getElementById("pmContent").value;
	toId = document.getElementById("groupLeaderId").value;
	var recipientUserKeyList = new Array();
	recipientUserKeyList[0] = new UserKey(toId);

	var requestBatch = new RequestBatch();

	requestBatch.AddToRequest(new PrivateMessageSendAction(subject,content,recipientUserKeyList));

	requestBatch.BeginRequest(serverUrl, callBack);

	function callBack(responseBatch) {
		//console.dir(responseBatch);
		document.getElementById("pmBox").style.display = "none";
		document.getElementById("sendPMLink").innerHTML = "Message sent.";
	}
}

function writeSystemMessages() {
	//$('#divStatus').html('Loading, please wait...');
	
	//alert($('#frmMain').serialize());
	$.post('/Administration/MessagesFromNB.aspx', $('#frmMessageBroadcast').serialize(), function(a_objResponse){
		$('#divStatus').html('');

		if (a_objResponse.status == "true") {
			newURL = '/News.aspx';
			window.location = newURL;
		}
		
		else {
			alert("There was an error in adding your message.  Please try again.")
		}
		
		//$('#divAjaxResponseArticles').html(a_objResponse);
	}, 'json');
}

function getSystemMessages() {
	$('#sysMsgContainer').html('Checking for new messages...');

	$.get('/Administration/Check.aspx', '', function(a_objResponse) {
		if (a_objResponse.status) {
			$('#sysMsgContainer').html('');
			
			jQuery.each(a_objResponse.sys_msg, function(i, val) {
				strHTML = '<div class="notification">';
				strHTML += '<img src="images/icons/large/special_message_LRM_or_NB.gif" height="32" width="32" alt="" />';
				strHTML += '<strong>' + unescapeText(this.msb_subject) + '</strong> (' + this.msb_date + ') ';
				strHTML += unescapeText(this.msb_body) + ' ';
				
				if (this.msb_url !== '') {
					strHTML += '<a href="' + this.msb_url + '">Read More...</a>'
				}
				
				strHTML += '</div>';
						
				$('#sysMsgContainer').append(strHTML);
			});
		}
		
		else {
			$('#sysMsgContainer').html('You have no system messages.');
		}
		
	}, 'json');	
}

function getMood() {
    $.get('/UserMood.aspx?m=read', '', function(a_objResponse) {
        if (a_objResponse.status) {
            love = parseInt(a_objResponse.num_love);
            hate = parseInt(a_objResponse.num_hate);
            total = love + hate;
            //alert(total);
            if (total > 100) {
                hate = hate - 1;
            }
            if (total < 100) {
                love = love + 1;
            }
            strHTML = '<span class="love_mood">' + love + '% LOVE</span>';
            strHTML += '<span class="hate_mood">/' + hate + '% hate</span>';

            $('#spnMood').html(strHTML);
        }

        else {
            strHTML = '<span class="love_mood">0%</span>';
            strHTML += '<span class="hate_mood">/0%</span>';

            $('#spnMood').html(strHTML);
        }
    }, 'json');	
}

/*function validateCreateGroup() {
	var error = '';
	
	if ($('#groupName').val() == '') error += '- ' + $('#groupName').attr('title') + ' is required.\n';
	if ($('#headline').val() == '') error += '- ' + $('#headline').attr('title') + ' is required.\n';
	if ($('#city').val() == '') error += '- ' + $('#city').attr('title') + ' is required.\n';
	if ($('#postal').val() == '') error += '- ' + $('#postal').attr('title') + ' is required.\n';
	
	if (error) { alert('The following error(s) occurred:\n'+error); }
	else { sendGroupRequest(); }
}

function validateCreateClinic() {
	var error = '';
	
	if ($('#groupName').val() == '') error += '- ' + $('#groupName').attr('title') + ' is required.\n';
	if ($('#headline').val() == '') error += '- ' + $('#headline').attr('title') + ' is required.\n';
	if ($('#startdate').val() == '') error += '- ' + $('#startdate').attr('title') + ' is required.\n';
	if ($('#enddate').val() == '') error += '- ' + $('#enddate').attr('title') + ' is required.\n';
	if ($('#runDistance').val() == -1) error += '- ' + $('#runDistance').attr('title') + ' is required.\n';
	if ($('#city').val() == '') error += '- ' + $('#city').attr('title') + ' is required.\n';
	if ($('#postal').val() == '') error += '- ' + $('#postal').attr('title') + ' is required.\n';
	if ($('#isRetailer').attr('checked')) {
		if ($('#r_name').val() == '') error += '- ' + $('#r_name').attr('title') + ' is required.\n';
		if ($('#r_city').val() == '') error += '- ' + $('#r_city').attr('title') + ' is required.\n';
		if ($('#r_postal').val() == '') error += '- ' + $('#r_postal').attr('title') + ' is required.\n';
		if ($('#r_phone').val() == '') error += '- ' + $('#r_phone').attr('title') + ' is required.\n';
	}
	
	if (error) { alert('The following error(s) occurred:\n'+error); }
	else { sendGroupRequest(); }
}

function validateCreateEvent() {
	var error = '';
	
	if ($('#groupName').val() == '') error += '- ' + $('#groupName').attr('title') + ' is required.\n';
	if ($('#headline').val() == '') error += '- ' + $('#headline').attr('title') + ' is required.\n';
	if ($('#AboutEvent').val() == '') error += '- ' + $('#AboutEvent').attr('title') + ' is required.\n';
	if ($('#startdate').val() == '') error += '- ' + $('#startdate').attr('title') + ' is required.\n';
	if ($('#enddate').val() == '') error += '- ' + $('#enddate').attr('title') + ' is required.\n';
	if ($('#province').val() == -1) error += '- ' + $('#province').attr('title') + ' is required.\n';
	if ($('#city').val() == '') error += '- ' + $('#city').attr('title') + ' is required.\n';

	if (error) { alert('The following error(s) occurred:\n'+error); }
	else { sendGroupRequest('addRace'); }
}

function validateCreateRace() {
	var error = '';
	
	if ($('#groupName').val() == '') error += '- ' + $('#groupName').attr('title') + ' is required.\n';
	if ($('#headline').val() == '') error += '- ' + $('#headline').attr('title') + ' is required.\n';
	if ($('#date').val() == '') error += '- ' + $('#date').attr('title') + ' is required.\n';
	
	if ($('#fee').attr('checked')) {
		if ($('#feeAmount').val() == '') error += '- ' + $('#feeAmount').attr('title') + ' is required.\n';
	}
	
	if ($('#deadline').val() == '') error += '- ' + $('#deadline').attr('title') + ' is required.\n';

	if (error) { alert('The following error(s) occurred:\n'+error); }
	else { sendGroupRequest(); }
}*/

function blankUsername() {
    if (document.getElementById("txtLoginUserName").value == "username") {
        document.getElementById("txtLoginUserName").value = "";
    }
}

function white_space(str)
{
     strFixed = str.replace(/^\s*|\s*$/g,'');
     return strFixed;
}
  
function writeActivity(OwnerID,ActorName,ActorID,Action,ItemTitle,ItemURL) {
    //alert("writeActivity fired.");
	$.post('/WriteActivity.aspx?m=1&OwnerID=' + OwnerID + '&ActorName=' + ActorName + '&ActorID=' + ActorID + '&Action=' + Action + '&ItemTitle=' + ItemTitle + '&ItemURL=' + ItemURL + '', $('#group').serialize(), function(a_objResponse){
		$('#divStatus').html('');
		
		if (a_objResponse.status) {
            //pageTracker._trackPageview("/PluckEvent/CreatedGroup/");
            newURL = 'GroupProfile.aspx?slGroupKey=' + id;
            window.location = newURL;
		}
		
		else {
			alert("There was an error in creating your clinic.  Please try again.")
		}
		
		//$('#divAjaxResponseArticles').html(a_objResponse);
	}, 'json');
}

function readActivity() {
	$('#userActivityContainer').html('Checking for community activities...');
    
    strHTML = '';
    
     function renderUserData(responseBatch) {
	    userPic = responseBatch.Responses[0].User.ImageUrl;
        //return userPic;
        //alert(userPic);
        strHTML += '<div class="notification">';
	    strHTML += '<a href="ViewPersona.aspx?userid=' + ActorID + '"><img src="' + userPic + '" height="32" width="32" alt="" /></a>';
	    strHTML += '<a href="ViewPersona.aspx?userid=' + ActorID + '">' + ActorName + '</a> ' + Action + ', <a href="' + ItemURL + '">' + ItemTitle + '</a>';
	    strHTML += '<br>';
	    strHTML += '<span class="time">on ' + Timestamp + '</span>';
	    strHTML += '</div>';
	    $('#userActivityContainer').html(strHTML);
	    
    }
    
	$.get('/WriteActivity.aspx?m=2&OwnerID=' + currentProfileID, '', function(a_objResponse) {
		if (a_objResponse.status) {
			$('#userActivityContainer').html('');
			
			//userActivityResponse = a_objResponse.userActivity;
			
			jQuery.each(a_objResponse.userActivity, function(i, val) {
			    
			    
			    ActorID = white_space(this.ActorID);
			    ActorName = white_space(this.ActorName);
			    Action = white_space(this.Action);
			    ItemURL = white_space(this.ItemURL);
			    ItemTitle = white_space(this.ItemTitle);
			    Timestamp = white_space(this.Timestamp);
			    
			    //var requestBatch = new RequestBatch();  
	            //var userKey = new UserKey(ActorID);
	            //requestBatch.AddToRequest(userKey);   
	            //setTimeout(function(){requestBatch.BeginRequest(serverUrl, renderUserData);},5000);
	            
	            //requestBatch.BeginRequest(serverUrl, renderUserData);
	            
	            strHTML += '<div class="notification">';
	            strHTML += '<a href="ViewPersona.aspx?userid=' + ActorID + '"><img src="http://sitelifestage.loverunningmore.ca/ver1.0/Content/images/no-user-image.gif" height="32" width="32" alt="" /></a>';
	            strHTML += '<a href="ViewPersona.aspx?userid=' + ActorID + '">' + ActorName + '</a> ' + Action + ', <a href="' + ItemURL + '">' + ItemTitle + '</a>';
	            strHTML += '<br>';
	            strHTML += '<span class="time">on ' + Timestamp + '</span>';
	            strHTML += '</div>';
	            
	            $('#userActivityContainer').html(strHTML);
			    
			});
			
			//responseObject = eval('(' + a_objResponse + ')');
			//alert(a_objResponse.userActivity.length);
	        /*for (z=0;z<a_objResponse.userActivity.length;z++) {
	            ActorID = white_space(a_objResponse.userActivity[z].ActorName);
	            var requestBatch = new RequestBatch();  
	            var userKey = new UserKey(ActorID);
	            requestBatch.AddToRequest(userKey); 
	            requestBatch.BeginRequest(serverUrl, renderUserData);
	        }*/
			
		}
		
		else {
			$('#userActivityContainer').html('No current activities');
		}
		
	}, 'json');	
	
}

function findNewLocalRunners() {
    //alert("writeActivity fired.");
	$.post('/DisplayNewLocalRunners.aspx?postalCode=' + currentPostalCode + '', $('#group').serialize(), function(a_objResponse){
		//$('#divStatus').html('');
		strHTML = "";
		if (a_objResponse.status) {
            jQuery.each(a_objResponse.newLocalRunner, function(i, val) {
            //newURL = 'GroupProfile.aspx?slGroupKey=' + id;
            //window.location = newURL;
                if (this.UserName != undefined && this.ProfileID != currentProfileID) {
                    strHTML += '<div class="notification">';
	                strHTML += '<a href="ViewPersona.aspx?userid=' + this.ProfileID + '"><img src="http://sitelifestage.loverunningmore.ca/ver1.0/Content/images/no-user-image.gif" height="32" width="32" alt="" /></a>';
	                strHTML += '<a href="ViewPersona.aspx?userid=' + this.ProfileID + '">' + this.UserName + '</a> from your community recently joined loverunningmore.ca!';
	                //strHTML += '<br>';
	                //strHTML += '<a href="PrivateMessaging.aspx">Send a message</a> <span class="time">(ed: I think we need to make them be friends first)</span>';
	                //strHTML += '<span class="time">on ' + Timestamp + '</span>';
	                strHTML += '</div>';
	            }
	            
	            $('#localRunners').html(strHTML);
            });
		}
		
		else {
			alert("There was an error in creating your clinic.  Please try again.")
		}
		
		//$('#divAjaxResponseArticles').html(a_objResponse);
	}, 'json');
}