﻿//event bindings
$(function() {
	$("#areaLogin").bind("click", function() {
		
		$("#divLoginPopup").slideToggle();
		$(".imgBtnSignIn").slideToggle();
		
		return false;
	});
	
	
	$(".btnSignInExpanded").bind("click", function() {		
		AuthenticateUser();
		return false;
	});
	
	//on enter of the username/password fields	
	$(".row2 .Textbox").bind("keydown", function(e) {
		 if (e.keyCode == 13) {
			AuthenticateUser();
			return false;
		 }
	});
	
	
			
});


///GENERIC IFRAME DIALOG FUNCTION
function showIFrameDialog(title, url, height, width) {
	url = ResolveUrl(url);
	$("#dlgReusableTitle").text(title);
	$("#" + reusableDialogID).Show({iframeUrl:url, height:height, width:width});
}

function hideIFrameDialog() {
	setTimeout(function() {
	$("#" + reusableDialogID).Hide();
	}, 50);
}

function showAjaxProgess() 
{
	$("#AjaxProgress").show();
}

//function to show the Ajax progress indicator
function hideAjaxProgess() 
{
	$("#AjaxProgress").hide();
}


function showForgotPasswordDialog() 
{
	showIFrameDialog("Forgot Password", "~/Dialogs/ForgotPassword.aspx", 120, 350);
}


function AuthenticateUser() 
{
	var username = $get("txtLoginUserName").value;
	var password = $get("txtLoginPassword").value;
	if (username == "" || password == "") {
		alert("Please enter your username and password.");
		return;
	}
	showAjaxProgess();	
	AjaxService.SignInUser(username, password, SignInUser_Success, SignInUser_Failure);
}

function SignInUser_Success(result) {
	hideAjaxProgess();
	if (result == -1) {
	
		//login failed
		SignInUser_Failure(null);		
	} else {
			
		//login was successful - set the currentProfileID and load the user's info
		currentProfileID = result + "";
				
		//call pluck to get the groups for this user		
		var requestBatch = new RequestBatch();  		
		var groupPage = new CommunityGroupMembershipPage(new UserKey(currentProfileID), 10, 1	);				
		requestBatch.AddToRequest(groupPage);
			
		// initiate the request.  The response will be passed to the SignInUser_GetGroups_Success() method.  
		requestBatch.BeginRequest(serverUrl, SignInUser_GetGroups_Success);   						
		
	}
}


function SignInUser_GetGroups_Success(responseBatch) {
///after the user has authenticated, we need to get their group membership before we 
	
	if (responseBatch.Responses.length > 0) {
		addUsersGroupIDsToCookie(responseBatch.Responses[0])
	}
	
	//go to the runcentre.
	if (location.href.indexOf("GroupProfile") != "-1") { 
	    location.href = window.location;
	} else {
	    location.href = "/News.aspx";
	}
	
}

function SignInUser_Failure(args) {
	hideAjaxProgess();
	alert("Your username or password was not recognised.\nPlease try again.");
}


function LoadWeatherFromLatLon(lat, lon, imgPath) 
{
	AjaxService.GetWeatherDataFromLatLong(lat, lon, GetWeather_Success, GetWeather_Failed, imgPath);
}
function LoadWeatherFromPostal(postalCode, imgPath) 
{

	AjaxService.GetWeatherDataFromPostalCode(postalCode, GetWeather_Success, GetWeather_Failed, imgPath);
}
function GetWeather_Success(w, imgPath) {
	
	
	var cityImage = "<img src='/Handlers/ImageText.ashx?t=" + escape(w.City) + "'/>"; 
	
	$("#weatherCityName").html(cityImage);
	
	
	var imgUrl = imgPath + "/large/" + w.Icon.replace(".gif", ".png");
	var tHtml = "<div class='TodayWeatherImage'><img src='" + imgUrl + "'/></div>";
	tHtml += "<div class='TodayTemp'>" + w.CurrentTemp + "&deg;</div>";
	tHtml += "<div class='TodayWindLabel'>Wind:</div>";
	tHtml += "<div class='TodayWind'>" + w.WindDir + "</div>";
	tHtml += "<div class='TodayWind'>" + w.WindSpeed + " km/h</div>";
			
	$("#today").html(tHtml);
	
	
	//forecast
	var foreHtml = "";
	for (var i=0; i<w.Days.length; i++) {
		foreHtml += GetWeatherForecastDayHTML(w.Days[i], imgPath);			
	}	
	
	$("#forecast").html(foreHtml);
	
}

function GetWeatherForecastDayHTML(d, imgPath) {

	var imgUrl = imgPath + "/small/" + d.Icon;
	var dayImg = imgPath + "/days/" + d.DayName.toLowerCase() + ".gif";
	html = "<div class='WeatherDay' title='"+ d.Description + "'>";
	html += "<div class='DayName'><img src='"  + dayImg + "'/></div>";
	html += "<div class='DayImage'><img src='" + imgUrl + "'/></div>";
	html += "<div class='DayTemp'>";
	html += "<span class='High'>" + d.High + "&deg;</span>&nbsp;";
	html += "<span class='Low'>" + d.Low + "&deg;</span>&nbsp;";
	html += "</div>";
	
	
	html += "</div>"
	return html;

}


function GetWeather_Failed(error) {
	$("#cityName").text("Could not load weather.");
}

function SetPersonalBests(user, oneKM, fiveKM, tenKM, halfMarathon, marathon)
{
    AjaxService.SetPersonalBests(user, oneKM, fiveKM, tenKM, halfMarathon, marathon, SetPersonalBests_Success, SetPersonalBests_Failure);
}

function SetPersonalBests_Success(values)
{
    //alert(values[0] + "\n" + values[1]);
    $('.OneKMBest').text(values[0]);
    $('.FiveKMBest').text(values[1]);
    $('.TenKMBest').text(values[2]);
    $('.HalfMarathonBest').text(values[3]);
    $('.MarathonBest').text(values[4]);
    $(".UpdateBestsButtonContainer").show();
    $(".Bests").show();
    $(".Bests2").show();
}

function SetPersonalBests_Failure(error)
{
    alert("Personal Bests could not be updated: " + error);
    $(".UpdateBestsButtonContainer").show();
    $(".Bests").show();
    $(".Bests2").show();
}

function GetUpdatedTrackingData(user)
{
    AjaxService.GetUpdatedTrackingData(user, GetUpdatedTrackingData_Success, GetUpdatedTrackingData_Failure);
}

function GetUpdatedTrackingData_Success(values)
{
    $(".ThisMonthDistance").text(values[0]);
    $(".ThisMonthTime").text(values[1]);
    $(".YearToDateDistance").text(values[2]);
    $(".YearToDateTime").text(values[3]);
    $(".WeeklyAverageDistance").text(values[4]);
    $(".WeeklyAverageTime").text(values[5]);
    $(".Pace5KM").text(values[6]);
    $(".Pace10KM").text(values[7]);
}

function GetUpdatedTrackingData_Failure(error)
{
}

var profileid;
var imgpath;
function LoadRecommendedRoutes(profileID, imgPath) {
    profileid = profileID;
    imgpath = imgPath;
    var requestBatch = new RequestBatch();
    var userKey = new UserKey(profileID);
    requestBatch.AddToRequest(userKey);
    requestBatch.BeginRequest(serverUrl, getTwoNearestRoutes);
}

function getTwoNearestRoutes(responseBatch) {
    if (responseBatch.Responses.length == 0) {
        GetRoutes_NoRoutesDisplaying();
        return;
    }

    var user = responseBatch.Responses[0].User;

    if (user.ExtendedProfile.terrain != undefined)
        terrain = user.ExtendedProfile.terrain;
    else
        terrain = '';

    AjaxService.GetTwoNearestRoutes(profileid, terrain, GetRoutes_Success, GetRoutes_Failed, imgpath);
 }


function GetRoutes_Success(r, imgPath) {

    var tHtml;

    if (r.length == 2) {
        tHtml = '<div style="min-height:10px;_height:10px;clear:left;" />';
        tHtml += '<a href="RouteDetails.aspx?RouteID=' + r[0].RouteID + '">';
        tHtml += '<div class="Route1">';
        tHtml += '<div class="Icon">';
        tHtml += '<img alt="icon" src=' + imgPath + ' />';
        tHtml += '</div>'
        tHtml += '<div class="Right">';
        tHtml += '<div class="Name">' + r[0].RouteName + '</div>'
        tHtml += '<div class="Location">' + r[0].City + '&nbsp;' + r[0].Province + '</div>'
        tHtml += '<div class="Distance">distance: ' + r[0].DistanceKM + 'km' + '</div>';
        tHtml += '</div>';
        tHtml += '</a>';
        tHtml += '</div>';
        tHtml += '<div style="min-height:4px;_height:4px;clear:left;font-size:0px;display:block;"></div>';
        tHtml += '<div class="SeparateLine"></div>';
        tHtml += '<div style="min-height:4px;_height:4px;clear:left;font-size:0px;display:block;"></div>'
        tHtml += '<a href="RouteDetails.aspx?RouteID=' + r[1].RouteID + '">';        
        tHtml += '<div class="Route2">';
        tHtml += '<div class="Icon">';
        tHtml += '<img alt="icon" src=' + imgPath + ' />';
        tHtml += '</div>'
        tHtml += '<div class="Right">';
        tHtml += '<div class="Name">' + r[1].RouteName + '</div>'
        tHtml += '<div class="Location">' + r[1].City + '&nbsp;' + r[1].Province + '</div>'
        tHtml += '<div class="Distance">distance: ' + r[1].DistanceKM + 'km' + '</div>';
        tHtml += '</div>';
        tHtml += '</a>';
        tHtml += '</div>';
    } else
        if (r.length == 1) {
            tHtml = '<div style="min-height:10px;_height:10px;clear:left;" />';
             tHtml += '<a href="RouteDetails.aspx?RouteID=' + r[0].RouteID + '">';
            tHtml += '<div class="Route1">';
            tHtml += '<div class="Icon">';
            tHtml += '<img alt="icon" src=' + imgPath + ' />';
            tHtml += '</div>'
            tHtml += '<div class="Right">';
            tHtml += '<div class="Name">' + r[0].RouteName + '</div>'
            tHtml += '<div class="Location">' + r[0].City + '&nbsp;' + r[0].Province + '</div>'
            tHtml += '<div class="Distance">distance: ' + r[0].DistanceKM + 'km' + '</div>';
            tHtml += '</div>';
             tHtml += '</a>';
            tHtml += '</div>';
    } else {
    tHtml = '<div style="min-height:10px;_height:10px;clear:left;" />';
    tHtml += '<div class="NoRoute">No recommended routes yet.</div>';
    }

    $("#RecommendedRoutes").html(tHtml);
}

function GetRoutes_Failed(error) {

    GetRoutes_NoRoutesDisplaying();
}

function GetRoutes_NoRoutesDisplaying() {
    var tHtml;

    tHtml = '<div style="min-height:10px;_height:10px;clear:left;" />';
    tHtml += '<div class="NoRoute">No recommended routes yet.</div>';

    $("#RecommendedRoutes").html(tHtml);
}



function SwitchLinksOnRouteSelector() {
	
	//switch the route select link to show the route details in a dialog
	$(".RouteSelectionLink").bind("click", function(e) {
		var url = $(this).attr("href");
		url = url.toLowerCase().replace("routedetails.aspx", "Dialogs/RouteDetailsDialog.aspx");			
		showIFrameDialog("Route Details", url, 510, 650);
		return false;
	});
}