var total = 0;
var friends = 0;
var followers = 0;
var FBLoggedIn = 0;
var emailProvider = "";
var totalContacts = 0;
var currentUserName = "";
var currentUserPicture = "";
var currentUserID = "";
var currentProject = "";
var selectedUserImage = "";
var IsUser = "0";
var currentEntity = "";

$(document).ready(function () {

    $("#SignInLnk").fancybox({
        'titleShow': false,
        'centerOnScroll': false,
        'scrolling': 'no',
        'onStart': (function () { $("#youtubeVid").hide() }),
        'onClosed': (function () { $("#youtubeVid").show() })
    });

    $("#searchTerm").focus(function () {
        if ($(this).val() == "search for people and projects...") {
            $(this).val("");
            $(this).css("color", "#000000");
        }
    });

    $("#searchTerm").blur(function () {
        if ($(this).val() == "") {
            $(this).val("search for people and projects...");
            $(this).css("color", "#666");
        }
    });

    $("#searchTerm").keypress(function (event) {
        if (event.keyCode == '13') {
            event.preventDefault();
            Search();
        }
    });

    $("#searchAll").focus(function () {
        if ($(this).val() == "search...") {
            $(this).val("");
            $(this).css("color", "#000000");
        }
    });

    $("#searchAll").blur(function () {
        if ($(this).val() == "") {
            $(this).val("search...");
            $(this).css("color", "#666");
        }
    });

    $("#searchAll").keypress(function (event) {
        if (event.keyCode == '13') {
            event.preventDefault();
            SearchAll();
        }
    });

    $("#searchUser").focus(function () {
        if ($(this).val() == "search for your friends...") {
            $(this).val("");
            $(this).css("color", "#000000");
        }
    });

    $("#searchUser").blur(function () {
        if ($(this).val() == "") {
            $(this).val("search for your friends...");
            $(this).css("color", "#666");
        }
    });

    $("#searchUser").keypress(function (event) {
        if (event.keyCode == '13') {
            event.preventDefault();
            SearchForUsers();
        }
    });

    $("#searchUsers").focus(function () {
        if ($(this).val() == "search for your friends...") {
            $(this).val("");
            $(this).css("color", "#000000");
        }
    });

    $("#searchUsers").blur(function () {
        if ($(this).val() == "") {
            $(this).val("search for your friends...");
            $(this).css("color", "#666");
        }
    });

    $("#searchUsers").keypress(function (event) {
        if (event.keyCode == '13') {
            event.preventDefault();
            SearchForFriends();
        }
    });
    

    //add functionality to listing
    (function () {
        //make all <li> elements clickable - use the anchor inside to get the location
        var l = $('ul.list');
        if (l.length == 0) return;
        $('li', l).click(function () {
            var a = $(this).find('a');
            if (a.length == 0) return;
            window.location = a.attr('href');
        });

    })();

    //add external link text to external links
    (function () {
        var l = $('a[rel="external"]');
        if (l.length == 0) return;
        l.each(function () {
            var span = document.createElement('span');
            span.innerHTML = ' ' + $.STD.text.externlLink;
            l.append(span).addClass('external');

        });
    })();
    
    //insert the video player
    (function () {
        if (!$('#heroVideo').length) return false;

        var $holdingImgUrl = $('#holdingImgUrl');
        var $videoUrl = $('#videoUrl');
        var $headline = $('#headline');

        if (!$holdingImgUrl.length || !$videoUrl.length) return false;

        var flashvars =
		{
		    appUrl: $.STD.flash.heroApp,
		    holdingImgUrl: $holdingImgUrl.val(),
		    videoUrl: $videoUrl.val(),
		    headline: $headline.val(),
		    autoPlay: "false",
		    bufferTime: "1"
		};

        var params =
		{
		    menu: "false",
		    wmode: "transparent",
		    allowFullScreen: "true"
		};

        var attributes = {};

        swfobject.embedSWF($.STD.flash.heroLoader, "heroVideo", "583", "475", "9.0.115", "expressInstall.swf", flashvars, params, attributes);

        //Now loop through and add the update videos
        var i = 1;

        for (i = 1; i < 11; i++) {
            
            if (!$('#heroVideo' + i).length) break;

            flashvars =
		    {
		        appUrl: $.STD.flash.heroApp,
		        holdingImgUrl: $('#holdingImgUrl' + i).val(),
		        videoUrl: $('#videoUrl' + i).val(),
		        headline: $('#headline' + i).val(),
		        autoPlay: "false",
		        bufferTime: "1"
		    };
		    
		    swfobject.embedSWF($.STD.flash.heroLoader, "heroVideo" + i, "583", "475", "9.0.115", "expressInstall.swf", flashvars, params, attributes);
		}

    })();
        
});

function tinyURL(e) {
    if (e.target.tagName == 'A') {
        var el = $(e.target);
    }
    else {
        var el = $(e.target).closest('a');
    }

    if (!el.hasClass('tinyURL')) {
        el.addClass('tinyURL');
        $.ajax({
            type: "GET",
            url: "/shrinkurl",
            data: "url=" + window.location.href,
            async: false,
            success: function (newurl) {
                var r = el.attr('href').replace(window.location.href, newurl);
                el.attr('href', r);
            }
        });
    }
}

function SetProjectVideo(videoUrl, headline, holdingImgUrl, searchString, description) {

    //Set the description and the headline
    $("#projVideoHeadline").html(headline);
    $("#videoProjectText").html("<br />" + description);
    $("#projVideoPoster").attr("src", holdingImgUrl);
    $("#projVideoTitle").html(searchString);

	var flashvars = 
	{
		appUrl: $.STD.flash.heroApp,
		holdingImgUrl: holdingImgUrl,
		videoUrl: videoUrl,
		headline: headline,
		autoPlay: "true",
		bufferTime: "1"
	};
													
	var params = 
	{
		menu: "false",
		wmode: "transparent",
		allowFullScreen: "true"
	};
		
	var attributes = {};

	swfobject.embedSWF($.STD.flash.heroLoader, "projVideo", "583", "475", "9.0.115", "expressInstall.swf", flashvars, params, attributes);	

}

function Search() {
    $("#searchGo").hide();
    $("#progressGo").show();
    //window.setTimeout(ShowResultsPage, 2000);
    ShowResultsPage();
}

function SearchForUsers() {
    $("#searchGo2").hide();
    $("#progressGo2").show();
    //window.setTimeout(ShowResultsPage, 2000);
    window.location = "/Project/Search?p=1&s=" + $("#searchUser").val();
}

function SearchForFriends() {
    $("#progressGo4").show();
    //window.setTimeout(ShowResultsPage, 2000);
    window.location = "/Project/Search?p=1&s=" + $("#searchUsers").val();
}

function SearchAll() {
    $("#progressGo4").show();
    //window.setTimeout(ShowResultsPage, 2000);
    window.location = "/Project/Search?p=1&s=" + $("#searchAll").val();
}

function ShowResultsPage() {
    window.location = "/Project/Search?p=1&s=" + $("#searchTerm").val();
}

function DoSearch(searchterm) {
    $("#searchTerm").val(searchterm);
    Search();
}

function AddDonation() {

    //Validate the information
    if ($("#first_name").val() == "") {
        $("#errorMsgDonate").html("Please tell us your name");
        return false;
    }

    if ($("#form_GrossAmount").val() == "") {
        $("#errorMsgDonate").html("Please enter the amount you want to give");
        return false;
    }

    $("#progress").show();

    //Now add a record to the donation table
    var timeStamp = new Date().getTime();
    var text = $("#friend_msg").val();
    var name = $("#first_name").val() + " " + $("#sur_name").val();
    var userId = currentUserID;
    var amount = $("#form_GrossAmount").val();
    var evntOwner = $("#profileID").val();
    var giftID = $("#currentEventID").val();
    var projectName = $("#currentEventProject").val();
   
    //Post the message to the gift donation table
    $.getJSON("/Services/EventService.svc/PostEventMessage", { CommentText: text, AmountDonated: amount, Name: name, ProjectName: projectName, UserID: userId, GiftID: giftID, GiftOwner: evntOwner, TimeStamp: timeStamp }, function (data, status) {
        if (data.d == "1")
            $("#submitDonate").click();
    });

    return true;
}

function SubmitGift() {

    //Validate the information
    if (($("#SenderForename").val() == "") || $("#SenderSurname").val() == "") {
        $("#formError").html("Please tell us your full name");
        return false;
    }

    if ($("#SenderEmail").val() == "") {
        $("#formError").html("Please tell us your email address");
        return false;
    }

    if ($("#form_GrossAmount").val() == "") {
        $("#errorMsgDonate").html("Please enter the amount you want to give");
        return false;
    }

    //Validate the information
    if (($("#RecipientForename").val() == "") || $("#RecipientSurname").val() == "") {
        $("#formError").html("Please tell us the full name of the person receiving the gift");
        return false;
    }

    //Validate the information
    if (($("#RecipientAddressLine1").val() == "") || ($("#RecipientAddressLine2").val() == "") || ($("#RecipientCity").val() == "") || ($("#RecipientPostcode").val() == "") || ($("#RecipientCountry").val() == "")) {
        $("#formError").html("Please tell us the address of the person receiving the gift");
        return false;
    }

    //Validate the information
    if ($("#CardDesign").val() == "") {
        $("#formError").html("Please select the card you want to send");
        return false;
    }

    //Now add a record to the donation table
    var projectId = $("#form_ProjectId").val();
    var amountDonated = $("#form_GrossAmount").val();
    
    //Post the message to the gift donation table
        $.getJSON("/Services/ProjectService.svc/SendGift", {
            GiftedProject: projectId,
            SenderForename: $("#SenderForename").val(),
            SenderSurname: $("#SenderSurname").val(),
            SenderEmail: $("#SenderEmail").val(),
            SenderPhone: $("#SenderPhone").val(),
            RecipientForename: $("#RecipientForename").val(),
            RecipientSurname: $("#RecipientSurname").val(),
            RecipientAddressLine1: $("#RecipientAddressLine1").val(),
            RecipientAddressLine2: $("#RecipientAddressLine2").val(),
            RecipientTown: $("#RecipientTown").val(),
            RecipientCity: $("#RecipientCity").val(),
            RecipientPostcode: $("#RecipientPostcode").val(),
            RecipientCountry: $("#RecipientCountry").val(),
            RecipientEmail: $("#RecipientEmail").val(),
            MessageFrom: $("#MessageFrom").val(),
            MessageText: $("#MessageText").val(),
            MessageTo: $("#MessageTo").val(),
            CardDesign: $("#CardDesign").val(),
            AmountDonated: amountDonated
        }, function (data, status) {
        if (data.d == "1")
            $("#submitDonate").click();
    });

    return true;
}

function CheckMarketingPerms(projectId, donationId) {

    var timeStamp = new Date().getTime();

    if ($("#givePermission").attr("checked")) {

        //Update the donation
        $.getJSON("/Services/ProjectService.svc/GiveMarketingPermission", { ProjectID: projectId, DonationID: donationId, TimeStamp: timeStamp }, function (data, status) {
            
        });
    }
}

function CheckStatus() {

     var txt = $("#errorTxt").html();
     txt = jQuery.trim(txt);

     if (txt != "") {
         $("#popoutErrMsg").click();
         return false;
     }
     else
         $("#progress").show();

    return true;
}

function GetFriendsFollowers() {


    if (document.getElementById("twitterID") != null) {

        var screenName = $("#twitterID").val();

        $.ajax({
            url: 'http://api.twitter.com/1/users/show.json',
            data: { screen_name: screenName },
            dataType: 'jsonp',
            success: function (data) {
                total = data.friends_count;
                followers = total;
                GetFriends();
            }
        });
    }
    else
        GetFriends();
    
	
}

function GetFriends() {

    if (document.getElementById("facebookID") != null) {

        //Now get the friends and add them up
        FB.api('/me/friends', function (response) {
            friends = response.data.length;
            total += friends;
            UpdateFriendsAndFollowers();
        });
    }
    else if (total > 0)
        UpdateFriendsAndFollowers();
    
}

function UpdateFriendsAndFollowers() {

    var timeStamp = new Date().getTime();

    $.getJSON("/Services/UserService.svc/UpdateFriendsAndFollowers", { friendsCount: friends, followerCount: followers, TimeStamp: timeStamp }, function (data, status) {
        $("#friendsFollowers").html(data.d + " friends and followers");
    });
    
}

function AddRating(value) {

    if (value != "undefined") {

        var timeStamp = new Date().getTime();
        var projectId = $("#form_ProjectId").val();

        $.getJSON("/Services/ProjectService.svc/AddRating", { ProjectID: projectId, Rating: value, TimeStamp: timeStamp }, function (data, status) {
            //Do nothing
        });
    }
}

function AddToWishlist() {

    var timeStamp = new Date().getTime();
    var projectId = $("#form_ProjectId").val();

    //Need to check if the current user is signed in, if not present the sign in form with an option to sign up!
    if ($("#Auth").val() == "True") {

        if (currentUserID != "") {
            PublishCommentToFacebook("http://www.seethedifference.org/user/?id=" + currentUserID, currentUserName + " added the project " + currentProject + " to their profile on See The Difference");
        }

        $.getJSON("/Services/UserService.svc/AddProjectToWishlist", { ProjectID: projectId, TimeStamp: timeStamp }, function (data, status) {            
            window.location = "/user/?id=" + currentUserID;
        });
    }
    else {

        //Show the sign in form
        $("#form_CurrentProject").val(projectId);
        $("#form_SelectedProject").val(projectId);
        $("#form_BookmarkProject").val("1");
        $("#form_Bookmark").val("1");
        $("#SignInLnk").click();
        return false;
    }

}


function ForgottenPassword() {

    //Check if the user has typed in their password
    if ($("#form_reset_Email").val() == "") {
        $("#infoMsgTxt").show();
        $("#infoMsgTxt").html("<span style='color:red'>Please enter a valid email address!</span>");
        return false;
    }

    $("#progress").show();

    var timeStamp = new Date().getTime();

    $.getJSON("/Services/UserService.svc/ResendPassword", { emailAddress: $("#form_reset_Email").val(), TimeStamp: timeStamp }, function (data, status) {
        
        $("#progress").hide();
        $("#infoMsgTxt").show();
        
        //Show the message depending on the state
        if (data.d == "0") {
            $("#infoMsgTxt").html("<span style='color:red'>The email you provided does not match our records! Please enter the email address you registered with.</span>");
        }
        else {
            $("#infoMsgTxt").html("<span style='color:blue'>Your password has been sent to the email address.</span>");
        }
    });
}

function NewGiftList(presentType) {

    if (presentType == 0) {
        $("#giftForm_TypeOfGift").val("0");
        $("#bdayGift").show();
        $("#seasonGift").hide();
    }
    else {
        $("#giftForm_TypeOfGift").val("2");
        $("#seasonGift").show();
        $("#bdayGift").hide();
    }

    //show the form
    $("#GiftLnk").click();
    return false;
}

function SetProvider(prov) {
    emailProvider = prov;
}

function GetContacts() {

    $("#emailGetGo").show();

    if (emailProvider == "yahoo") {

        //Need to check if the current user is signed in, if not present the sign in form with an option to sign up!
        $.getJSON("/Services/UserService.svc/GetContacts", { emailAddress: $("#myEmailAddr").val(), Cred: $("#myEmailPwd").val(), Provider: emailProvider }, function (data, status) {
            $("#emailGetGo").hide();

            var object_yahoo = {};
            object_yahoo = eval('(' + data.d + ')');

            var liHtml = "";
            
            for (var i = 0; i < object_yahoo.contacts.length; i++) {
                var row = '<input type="checkbox" id="ecl' + i + '" onclick="UpdateContacts(this)" value="' + object_yahoo.contacts[i].fields[1].data + '">' + object_yahoo.contacts[i].fields[1].data + '<br/>';
                liHtml += row;
            }
            
            $("#giftForm").css("height", "750px");
            $("#inputSelectList").html(liHtml);
            $("#emailSelect").show();
            $.fancybox.resize();
        });
    }
    else {

        //Need to check if the current user is signed in, if not present the sign in form with an option to sign up!
        $.getJSON("/Services/UserService.svc/GetContactList", { emailAddress: $("#myEmailAddr").val(), Cred: $("#myEmailPwd").val(), Provider: emailProvider }, function (data, status) {
            $("#emailGetGo").hide();

            var i = 0;
            var liHtml = "";
            totalContacts = data.d.length;

            $.each(data.d, function () {
                var row = '<input type="checkbox" id="ecl' + i + '" onclick="UpdateContacts(this)" value="' + this + '">' + this + '<br/>';
                liHtml += row;
                i += 1;
            });

            $("#giftForm").css("height", "750px");
            $("#inputSelectList").html(liHtml);
            $("#emailSelect").show();
            $.fancybox.resize();
        });

    }                
}

function UpdateContacts(input) {

    var email = $("#giftForm_EmailList").val();

    if (email != "")
        email += ",";

    if (input.checked) {
        email += input.value;
    }
    else {
        email = email.replace(input.value, "");
    }
    
    $("#giftForm_EmailList").val(email);
}

function GetECardContacts() {

    $("#emailGetGo").show();

    if (emailProvider == "yahoo") {
        //Need to check if the current user is signed in, if not present the sign in form with an option to sign up!
        $.getJSON("/Services/UserService.svc/GetContacts", { emailAddress: $("#myEmailAddr").val(), Cred: $("#myEmailPwd").val(), Provider: emailProvider }, function (data, status) {
            $("#emailGetGo").hide();
            var object_yahoo = {};
            object_yahoo = eval('(' + data.d + ')');

            var liHtml = "";
            var email = "";

            for (var i = 0; i < object_yahoo.contacts.length; i++) {
                
                var row = '<input type="checkbox" id="ecl' + i + '" onclick="UpdateContacts(this)" value="' + object_yahoo.contacts[i].fields[1].data + '">' + object_yahoo.contacts[i].fields[1].data + '<br/>';
                liHtml += row;
            }

            $("#inputSelectList").html(liHtml);
            $("#emailSelect").show();
            $.fancybox.resize();
        });
    }
    else {

        //Need to check if the current user is signed in, if not present the sign in form with an option to sign up!
        $.getJSON("/Services/UserService.svc/GetContactList", { emailAddress: $("#myEmailAddr").val(), Cred: $("#myEmailPwd").val(), Provider: emailProvider }, function (data, status) {
            $("#emailGetGo").hide();
            var i = 0;
            var liHtml = "";
            totalContacts = data.d.length;

            $.each(data.d, function () {
                var row = '<input type="checkbox" id="ecl' + i + '" value="' + this + '">' + this + '<br/>';
                liHtml += row;
                i += 1;
            });

            $("#inputSelectList").html(liHtml);
            $("#emailSelect").show();
            $.fancybox.resize();
        });
    }    
}

function UpdatesEmailContacts() {

    var emails = "";

    for (var i = 0; i < totalContacts; i++) {

        if (document.getElementById("ecl" + i).checked) {

            if (emails != "")
                emails += ",";

            emails += document.getElementById("ecl" + i).value;
        }
            
    }

    //Update the parent box
    $("#form_EmailList").val(emails);
    $.fancybox.close();
}

function LoginFacebook(createPage) {

    FB.login(function (response) {

        if (response.authResponse) {

            // user is logged in and granted some permissions.
            // perms is a comma separated list of granted permissions
            // A user has logged in, and a new cookie has been saved.
            // Use the API to pull back their details
            FB.api('/me', function (resp) {
                $("#form_FacebookID").val(resp.id);
                $("#form_FirstName").val(resp.first_name);
                $("#form_Surname").val(resp.last_name);
                $("#form_Email").val(resp.email);
                $("#form_FacebookUsed").val("1");
                $("#form_ProfilePictureUrl").val("http://graph.facebook.com/" + resp.id + "/picture");

                //Get the friends for the user
                FB.api('/me/friends', function (r) {
                    $("#form_FriendCount").val(r.data.length);

                    if (createPage)
                        $("#signUpBtn").click();
                });
            });
        }

    }, { scope: 'email,user_birthday,publish_stream' });
}

function PublishCommentToFacebook(url, text) {

    var strbody = text;

    if (strbody != "") {

        strbody += " " + url;

        FB.getLoginStatus(function (response) {

            if (response.authResponse) {

                // logged in and connected user, someone you know
                FB.api('/me/feed', 'post', { message: strbody }, function (r) {

                });
                

            } else {

                //Ask the user to login and then post the message
                FB.login(function (r2) {

                    if (r2.authResponse) {

                        // logged in and connected user, someone you know
                        FB.api('/me/feed', 'post', { message: strbody }, function (r3) {

                        });
                    }
                }, { scope: 'email,publish_stream' });
            }
        });
    }    
}


function LoadFBProfile() {

    if ($("#form_ProfilePicture").val() == "/content/images/silhouette50.gif" && $("#form_Name").val() == "") {

        FB.getLoginStatus(function (response) {

            if (response.authResponse) {

                // logged in and connected user, someone you know
                FB.api('/me', function (resp) {
                    currentUserName = resp.first_name + " " + resp.last_name;
                    currentUserPicture = ("http://graph.facebook.com/" + resp.id + "/picture");                    
                });
            }
        });

    }

}

function PostToWall(url) {

    if (document.getElementById("postGiftToFB").checked) {

        //Open the Facebook share window
        window.open("http://www.facebook.com/sharer.php?u=" + url + "&t=" + $("#giftForm_Text").val());
    }
}

function SelectCard(num) {

    //Set the border for all cells to nothing
    for (var i = 1; i < 4; i++) {
        $("#img" + i).attr("style", "border:none");
    }

    //Now select the right image
    $("#img" + num).attr("style", "border:3px solid #ff7626");

    //Set the appropriate value in the form
    $("#CardDesign").val("Design " + num);

}

function SelectImage(num) {

    //Set the border for all cells to nothing
    for (var i = 1; i < 26; i++) {
        $("#img" + i).attr("style", "border:none");
    }

    //Now select the right image
    $("#img" + num).attr("style", "border:3px solid #ff7626");

    //Set the appropriate value in the form
    $("#form_Image").val("http://cdn.seethedifference.org/ecards/ecard-image-" + num + ".jpg");

    var lnkNum = "#lnk" + num;
    $("#form_ProjectUrl").val($(lnkNum).val());

    var typeNum = "#type" + num;
    $("#form_CardType").val($(typeNum).val());

}

function PreviewECard() {
    $("#previewImg").attr("src", $("#form_Image").val());
    $("#previewMsg").html($("#form_Message").val().replace(/\n/g, "<br />"));
    $("#previewUsr").html($("#form_Sender").val());
    $("#previewProjLnk").attr("href", $("#form_ProjectUrl").val());
    $("#cardType").html($("#form_CardType").val());
    $("#previewLnk").click();
}

function UpdateOnFB() {

    var strBody = currentUserName + " has an updated profile on See The Difference - http://www.seethedifference.org/user/?id=" + currentUserID;

    FB.getLoginStatus(function (response) {

        if (response.authResponse) {

            // logged in and connected user, someone you know
            FB.api('/me/feed', 'post', { message: strBody }, function (r) {
                //submit the form
                $("#settingsSaveBtn").click();
            });
        }
        else
            $("#settingsSaveBtn").click();
    });

    return true;
}


function AddAsFriend(userId, name) {
    if ($("#Auth").val() == "True") {

        var timeStamp = new Date().getTime();
        var html = "<div style='width:300px'><p class='greyTextSmaller'>my lovely friends</p><h4>" + name + " is already your friend</h4><p><table><tr><td>Why not add more friends by searching for them using the search box at the top of the page!</td></p></div>";
        $.getJSON("/Services/UserService.svc/AddAsFriend", { FriendID: userId, TimeStamp: timeStamp }, function (data, status) {

            if (data.d != "") {
                html = data.d;

                if (html != "") {
                    var url = "http://www.seethedifference.org/user/?id=" + currentUserID;

                    //Post the comment to Facebook
                    PublishCommentToFacebook(url, currentUserName + " has added " + name + " as their friend on See The Difference");
                }
            }

            $.fancybox(
		    html,
		    {
		        'autoDimensions': false,
		        'transitionIn': 'none',
		        'transitionOut': 'none',
		        'width': 350,
		        'height': 275,
		        'onStart': (function () { $("#youtubeVid").hide() }),
		        'onClosed': (function () { $("#youtubeVid").show() })
		    });


        });

    }
    else {

        //Show the sign in form
        $("#form_SelectedFriend").val(userId);
        $("#form_FriendID").val(userId);
        $("#SignInLnk").click();
        return false;
    }
}

function ShowAllFriends(userId) {

    //Show the box

    $.getJSON("/Services/UserService.svc/GetFriends", { UserID: userId }, function (data, status) {

        var overflow = "";
        if (data.d.length > 50)
            overflow = "overflow-y:scroll;";

        var html = '<div id="friendsList" style="width:475px;height:475px;margin-left:auto;margin-right:auto"><p class="greyTextSmaller">my lovely friends</p><p>Click on an image to see the profile of a user.</p><div style="' + overflow + 'height:400px;width:450px;margin-right:auto;margin-left:auto"><ul id="friendWall">';

        //Add them to box
        $.each(data.d, function (totalCount, item) {
            html += '<li><div style="width:50px;text-align:center"><a href="/user/?id=' + item.FriendUserID + '"><img src="' + item.ProfilePicture + '" alt="' + item.Name + '" title="' + item.Name + '" height="48px" width="48px"></img></a><span style="color:#999; font-size:7pt">' + item.Name + '</span></div></li>';
        });

        html += '</ul></div></div>';

        $.fancybox(
		html,
		{
		    'autoDimensions': false,
		    'width': 520,
		    'height': 520,
		    'transitionIn': 'none',
		    'transitionOut': 'none',
		    'onStart': (function () { $("#youtubeVid").hide() }),
		    'onClosed': (function () { $("#youtubeVid").show() })
		});
    });
}

function DeleteProject(projectId) {
    
    var timeStamp = new Date().getTime();
    $.getJSON("/Services/UserService.svc/DeleteProject", { ProjectID: projectId, TimeStamp: timeStamp }, function (data, status) {

        if (data.d == "1") {
            $("#project_" + projectId).remove();
            $("#manage_proj_" + projectId).remove();
            $("#project_update_" + projectId).remove();
        }

    });
}

function DeleteFriend(friendId) {

    var timeStamp = new Date().getTime();
    $.getJSON("/Services/UserService.svc/DeleteFriend", { FriendID: friendId, TimeStamp: timeStamp }, function (data, status) {

        if (data.d == "1") {
            $("#friend_" + friendId).remove();
            $("#manage_frnd_" + friendId).remove();
        }

    });
}

function UpdateProjectText(projectId) {
    var timeStamp = new Date().getTime();
    var text = $("#proj_note_" + projectId).val();
    $.getJSON("/Services/UserService.svc/AddUserProjectNote", { ProjectID: projectId, Note: text, TimeStamp: timeStamp }, function (data, status) {

        if (data.d == "1") {

            //Update the text against the project
            $("#proj_note_span_" + projectId).html(text);
            $("#proj_note_update_" + projectId).html(text);
        }

    });
}

function GetCurrentUser() {

    $.getJSON("/Services/UserService.svc/GetCurrentUser", null, function (data, status) {

        if (data.d != null) {

            //Update the parameters on the page
            currentUserID = data.d.UserID;
            currentUserName = data.d.FirstName + " " + data.d.Surname;
            currentUserPicture = data.d.ProfilePictureUrl;
        }
        else
            LoadFBProfile();

    });

}


function LoadUserProjects(projectList, userId) {
    
    var list = projectList.split(',');

    $.each(list, function (totalCount, item) {
        LoadProject("doingProjects", item, "doneProjects", true, userId);                
    });    
}

function LoadProject(sourceElem, projectId, sourceElemDone, loadDesc, userId) {

    $.getJSON("/Services/ProjectService.svc/GetProjectDetails", { ProjectID: projectId, UserID: userId }, function (data, status) {

        var project = data.d;

        //Build the markup and push to the list
        var html = '<li><a href="' + project.ProjectUrl + '" class="thumb"><img src="' + project.ThumbnailImage + '" alt="' + project.ProjectName + '" /><span class="details">' + project.ProjectName + '</span><span class="play"></span></a>';
        var raised = '';

        if (project.EventID != null && sourceElemDone != "") {

            if (project.EventMoneyRaised != "" && project.EventMoneyRaised != null)
                raised = '<span class="totalRaised"><a onclick="LoadEventHistory(\'' + project.EventID + '\', \'' + userId + '\')">' + $("#usrName").html() + ' raised  ' + project.EventMoneyRaised + ' for this project</a></span>';
        }

        if (project.UserText == null || project.UserText == "") {
            project.UserText = "I like this project...";
        }

        if (loadDesc) {
            html += '</li><li><span style="font-size:11pt; font-weight:bold;">' + project.ProjectTitle + '</span><p id="proj_note_span_' + project.ProjectId + '" style="font-size:10pt">' + project.UserText + '</p>' + raised + '</li>';
        }
        else
            html += '</li>';

        if (project.FeedbackText != "" && sourceElemDone != "")
            $("#" + sourceElemDone).append(html);
        else
            $("#" + sourceElem).append(html);

        //Add the relevant mark up to the management panel
        if (sourceElemDone != "") {
            var mgtPanel = '<tr id="manage_proj_' + project.ProjectId + '">';
            mgtPanel += '<td style="font-weight:bold" valign="top">' + project.ProjectName + '</td>';
            mgtPanel += '<td><textarea id="proj_note_' + project.ProjectId + '" rows="3" cols="35" onblur="UpdateProjectText(\'' + project.ProjectId + '\')">' + project.UserText + '</textarea></td>';
            mgtPanel += '<td><a onclick="DeleteProject(\'' + project.ProjectId + '\');$(\'#img_proj_note_' + project.ProjectId + '\').attr(\'src\',\'/content/images/ajax-loader.gif\')"><img src="/content/images/delete.png" id="img_proj_note_' + project.ProjectId + '" alt="Delete" title="Remove this project" style="height:32px;width:32px;border:none"></img></a></td></tr>';
            $("#manageProjects").append(mgtPanel);
        }
    });

}

function LoadEventProject(sourceElem, projectId, userId) {

    $.getJSON("/Services/ProjectService.svc/GetProjectDetails", { ProjectID: projectId, UserID: userId }, function (data, status) {

        var project = data.d;

        //Build the markup and push to the list
        var html = '<li><a onclick="$(\'#videoLnk\').click()" class="thumb"><img src="' + project.ThumbnailImage + '" alt="' + project.ProjectName + '" /><span class="details">' + project.ProjectName + '</span><span class="play"></span></a></li>';
        $("#" + sourceElem).append(html);
        
        SetProjectVideo(project.Video, project.ProjectName, project.VideoPoster, project.ProjectTitle, project.ProjectDescription);

    });

}

function LoadRelatedProjects(sourceElem, projectList) {

    $.getJSON("/Services/ProjectService.svc/GetRelatedProjects", { ProjectList: projectList }, function (data, status) {

        var html = '<ul class="project-thumbs">';

        $.each(data.d, function (totalCount, item) {
            //Build the markup and push to the list
            html += '<li><a href="' + item.ProjectUrl + '" class="thumb"><img src="' + item.ThumbnailImage + '" alt="' + item.ProjectName + '" /><span class="details">' + item.ProjectName + '</span><span class="play"></span></a></li>';
        });

        html += '</ul>';
        $("#" + sourceElem).append(html);

    });

}

function LoadEventHistory(eventId, userId) {

    //Show the donation history for the event
    $.getJSON("/Services/EventService.svc/GetEventMessages", { EventID: eventId, UserID: userId }, function (data, status) {

        var total = 0;
        var overflow = "";
        if (data.d.length > 7)
            overflow = "overflow-y:scroll;";

        var html = '<div id="eventCommentList" style="width:725px;height:475px;margin-left:auto;margin-right:auto">';
        html += '<table><tr><td valign="top" align="center">[PRJ]</td><td>';
        html += '<div style="' + overflow + 'height:450px;width:490px;margin-right:auto;margin-left:auto" id="profileComments">';

        //Add them to box
        $.each(data.d, function (totalCount, item) {
            html += '<div class="item type-donorcomment" style="border: 1px solid #aaa;width:450px">';
            html += '<table style="width:100%"><tr><td width="10%">';

            if (item.UserID != null && item.UserID != "") {
                html += '<a href="/user/?id=' + item.UserID + '">';
                html += '<img src="' + item.ProfilePicture + '" alt="' + item.Name + '" title="' + item.Name + '" height="64px" width="64px"></img></a>';
            }
            else
                html += '<img src="' + item.ProfilePicture + '" alt="' + item.Name + '" title="' + item.Name + '" height="64px" width="64px"></img>';

            html += '</td><td align="left" width="70%"><h3>';
            html += item.Name;

            var msg = item.Message;

            if (msg == null)
                msg = ' made a donation to the ' + item.ProjectTitle + ' project';

            html += '</h3><p style="padding-left: 3px; padding-bottom: 3px; font-size:0.8em">' + msg + '</p></td><td width="20%" align="right">';
            html += '<span class="orangeTextSmall">&pound;' + item.Amount.toFixed(2) + '</span>';
            html += '<br /><span class="orangeTextSmaller"> + ' + item.GiftAidAmount.toFixed(2) + ' gift aid</span>';

            html += '</td></tr></table>';
            html += '<p class="posted" style="padding-left:5px;">' + item.DonationDateClient + '</p></div>';
        });

        //Now get the details of the event
        $.getJSON("/Services/EventService.svc/GetEventDetails", { EventID: eventId }, function (data, status) {

            //Build the html on the left
            var innerHtml = '<img src="' + selectedUserPicture + '" alt="" height="128px" width="128px" /><p class="greyTextSmall">On ' + data.d.ActivityDate + ' I raised </p>';
            innerHtml += '<p class="orangeTextLarge">&pound;' + data.d.TotalRaised.toFixed(2) + ' <br /><span class="orangeTextSmall">for</span></p>';
            innerHtml += '<ul id="myEvntProj" class="project-thumbs"></ul>';

            html = html.replace("[PRJ]", innerHtml);
            html += '</div></div></td></tr></table>';

            //Load the project
            LoadProject("myEvntProj", data.d.ProjectID, "", false, userId);

            $.fancybox(
		    html,
		    {
		        'autoDimensions': false,
		        'width': 800,
		        'height': 520,
		        'transitionIn': 'none',
		        'transitionOut': 'none',
		        'onStart': (function () { $("#youtubeVid").hide() }),
		        'onClosed': (function () { $("#youtubeVid").show() })
		    });


        });
    });

}

function AddBadgeToProfile(badge, redirectUrl, badgeName, donorName) {
    $("#form_Badge").val(badge);
    $("#form_NewBadge").val(badge);

    if (document.getElementById("postBadgeToFB").checked) {
        //Post the badge image to Facebook
        PostBadgeToWall(badge, badgeName, donorName);
    }

    if (redirectUrl == "")
        $("#SignInLnk").click();
    else
        window.location = redirectUrl;
}

function PostBadgeToWall(badgelevel, badgeName, donorName)
{
    url = "http://cdn.seethedifference.org/badges/fblevel" + badgelevel + ".png";
    title = donorName + " is now a " + badgeName + " level generous bastard on See The Difference!";
    window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(url) + '&t=' + encodeURIComponent(title), 'sharer', 'toolbar=0,status=0,width=626,height=436');
}

function LoadTab(tabNo) {

    //Hide all tabs
    $("#tab1").hide();
    $("#tab2").hide();
    $("#tab3").hide();
    $("#tab4").hide();
    $("#tab5").hide();

    //Show the selected one
    $("#tab" + tabNo).show();
}


function InitialiseTabs() {

    //Hide all tabs
    $("#tab1").hide();
    $("#tab2").hide();
    $("#tab3").hide();
    $("#tab4").hide();
    $("#tab5").hide();

    //Show the selected one
    for (var i = 1; i < 6; i++) {

        if (document.getElementById("tab" + i) != null) {
            $("#tab" + i).show();
            break;
        }
    }
}

function LoadPanels(stories) {

    //Debug
    //stories = [{ "content": "<div class='slide_inner'><a class='photo_link' href='/how-it-works/'><img class='photo' src='/content/images/topboximage.png' alt='See The Difference' /></a></div>", "content_button": "<div class='thumb'></div>" }, { "content": "<div class='slide_inner'><a class='photo_link' href='/charities/the-connection-at-st-martins/night-centre'><img class='photo' src='http://cdn.seethedifference.org/images/text-pages/panel1.jpg' alt='See The Difference' /></a></div>", "content_button": "<div class='thumb'></div>" }, { "content": "<div class='slide_inner'><a class='photo_link' href='/charities/ButtleUK/cookers'><img class='photo' src='http://cdn.seethedifference.org/images/text-pages/panel2.jpg' alt='See The Difference' /></a></div>", "content_button": "<div class='thumb'></div>" }, { "content": "<div class='slide_inner'><a class='photo_link' href='/charities/nspcc/help-childline-counsel-more-children'><img class='photo' src='http://cdn.seethedifference.org/images/text-pages/panel3.jpg' alt='See The Difference' /></a></div>", "content_button": "<div class='thumb'></div>" }, { "content": "<div class='slide_inner'><a class='photo_link' href='/charities/magic-me/cocktails-in-care-homes'><img class='photo' src='http://cdn.seethedifference.org/images/text-pages/panel4.jpg' alt='See The Difference' /></a></div>", "content_button": "<div class='thumb'></div>"}];

    $("#topBannerPanel").agile_carousel({
        carousel_data: stories,
        slide_height: 305,
        carousel_height: 305,
        carousel_outer_height: 305,
        carousel_outer_width: 765,
        slide_width: 765,
        transition_time: 400,
        timer: 7000,
        continuous_scrolling: true/*,
        control_set_1: "numbered_buttons",
        no_control_set: "hover_previous_button,hover_next_button"*/
    });
}

function SetEmailText(userName, id, ebentTitle, projectTitle) {

    if ($("#emailForm_MessageType").val() == "1") {
        $("#emailForm_MessageText").val("Hi,\n\nI'm " + ebentTitle + " for " + projectTitle + ". It's an amazing cause that means a lot to me. You can find out more about the project I’ve chosen by clicking on the link below, which takes you to my fundraising page and where you can make a donation quickly and securely.\n\nhttp://www.seethedifference.org/user/" + id + "\n\nI'd really appreciate your support. Every penny really does count and if you're a taxpayer you can also make your donation 25% bigger at no extra cost by clicking the gift aid button (the government refunds the tax you paid).\n\nThanks so much and if you can spread the word further using the facebook and twitter buttons on my fundraising page I'd really appreciate that too.\n\nI'll let you know how I get on.\n\nThanks,\n" + userName);
    }
    else {
        $("#emailForm_MessageText").val("Hi,\n\nI just wanted to say a massive thank you for helping me raise money for my charity project. The charity will soon be letting us know just what a difference our money has made, so keep an eye out for an email from See The Difference.\n\nThanks again!\n" + userName);
    }
}
