//####### Copyright Mavice LLC 2009 – www.mavice.com ########

var mailToPersonaName = null;
var mailToPersonaId = null;
var mailTab = "inbox";

var currentPersonaName = null;
var currentPersonaId = null;
var currentAccountId = null;
var isMe = false;
var isTrueFriend = false;
var isClubFriend = false;
var trueFriends = new Array();
var tab = $.query.get("tab");

var dummyAccounts = "Anna,Emilie,Sara,Olivia";

var decoratePageTheme = "";
if(cookieSet("decoratePageTheme"))
    decoratePageTheme = $.cookie('decoratePageTheme');

$(document).ready(function(){
    getUserDetails(initPage);
});

function getUserDetails(callback){
    $.ajax({
        url: "getUserDetails.action?name="+$.query.get("name"),
        type: "GET",
        dataType: "xml",
        success: function(data, textStatus){
            isTrueFriend = ($(data).find("root isTrueFriend").text() == "1");
            isClubFriend = ($(data).find("root isClubFriend").text() == "1");
            trueFriends = $(data).find("root trueFriends").text().split(',');
            trueFriends.pop();
     
            currentAccountId = $(data).find("root currentAccountId").text();
            currentPersonaId = $(data).find("root currentPersonaId").text();
            currentPersonaName = $(data).find("root currentPersonaName").text();

            if((currentPersonaId == personaId && currentPersonaId) || !$.query.get("name"))
                isMe = true;
            
            if(!currentPersonaId){
                currentPersonaName = personaName;
                currentPersonaId = personaId;
                currentAccountId = accountId;
            }

            if(callback)
                callback();
        }
    });
}

function friend_added(){
    initMyFriends();
    initMyMail();
}

function initPage(){
    var friendsActiveTab = 0;
    if(isMe && is_logged_in)
        friendsActiveTab = 1;
    
    var socializeActiveTab = 1;
    if(tab == "mail")
        socializeActiveTab = 0;

    if(!isMe || !is_logged_in){
        // Change "My Profile" string to "About <Username>"
        if(!isMe){
            $("#myprofile_accordion div.handle:last .label .label_padding")
                .text($("#myprofile_container .titleOther").text().replace("[PersonaName]", currentPersonaName));
        }
        else{
            $("#myprofile_accordion div.handle:last .label .label_padding")
                .text($("#myprofile_container .titleAnon").text());
        }
           
        // Change "My News" string to "News"
        $("#socialize_accordion div.handle:first .label .label_padding")
            .text($("#mynews_container .titleOther").text());

        // Change "My News" string to "News"
        $("#friends_accordion div.handle:last .label .label_padding")
            .text($("#myfriends_container .titleOther").text());

        // Hide the decorate page section
        $("#myprofile_accordion div.handle:first")
            .hide()
            .next()
            .hide();
        
        // Hide the mymail section
        $("#socialize_accordion div.handle:first")
            .hide()
            .next()
            .hide();
        
        $("#friends_accordion .section").css("height", "415px");
        $("#friends_accordion .section .scrollbox .body").css("height", "415px");
        
        $("#profile_content").css("height", "538px");

        $('#profile_content .left .head .inner').html($('#profile_content .left .head .titleOther').html());
        $('#profile_content .middle .head .inner').html($('#profile_content .middle .head .titleOther').html());
    }

    new Accordion("#myprofile_accordion", {active_tab: 1, event_type: "click"});
    new Accordion("#friends_accordion", {active_tab: friendsActiveTab, event_type: "click"});
    new Accordion("#socialize_accordion", {active_tab: socializeActiveTab, event_type: "click"});
    
    new VerticalScrollBox("#myprofile_scrollbox", 200);
    new VerticalScrollBox("#decoratepage_scrollbox", 200);
    new VerticalScrollBox("#clubfriends_scrollbox", 200);
    new VerticalScrollBox("#myfriends_scrollbox", 200);
    new VerticalScrollBox("#mymail_scrollbox", 200);
    new VerticalScrollBox("#mynews_scrollbox", 200);

    //adjust_scrollbox_height("#mymail_scrollbox", 30);

    if(is_logged_in){
        // These sections are only shown when logged in and isMe
        if(isMe){
            initMyMail();
            initDecoratePage();
        }
    }
    else
        $('div#notLoggedIn').show("fast");

    if(is_logged_in || !isMe)
        initStatusBar();
    
    // These sections are always shown
    initMyFriends();
    initMyProfile();
    initClubFriends();
    initMyNews();

    initDecoratePage();
    var enterFriendCodeRetainer = $("input#codeEntry").val();

    // Set up the mail tabs
    $("div#mymailtabs .inbox").addClass("inbox_on");
    $("div#mymailtabs .inbox").click(function(){
        myMailChangeToInbox();
    });
    $("div#mymailtabs .sent").click(function(){
        myMailChangeToSent();
    });
    $("div#mymailtabs .create").click(function(){
        myMailChangeToCreate();
    });
    
    //////////// MAIN MYMAIL BUTTONS /////////////

    $("div#mymail_inbox_friends_listing div.friend_container a").live("click", function(event){
        event.preventDefault();

        mailToPersonaId = $(this).siblings(".friendPersonaId").text();
        mailToPersonaName = $(this).siblings(".friendName").text();
        myMailChangeToCreateDetail(); 
    });

    $("div#mymail_sent_friends_listing div.friend_container a").live("click", function(event){
        event.preventDefault();
        
        mailToPersonaId = $(this).siblings(".friendPersonaId").text();
        mailToPersonaName = $(this).siblings(".friendName").text();
        myMailChangeToCreateDetail();
    });
    
    $("div#mymail_create_friends_listing div.friend_container a").live("click", function(event){
        event.preventDefault();

        mailToPersonaId = $(this).siblings(".friendPersonaId").text();
        mailToPersonaName = $(this).siblings(".friendName").text();
        myMailChangeToCreateDetail();  
    });
    
    $("div#mymail_inbox_listing .messages .message .information .summary").live("click", function(event){
        event.preventDefault();
        myMailChangeToInboxDetail($(this).children(".messageId").text());
    });

    $("div#mymail_sent_listing .messages .message .information .summary").live("click", function(event){
        event.preventDefault();
        myMailChangeToSentDetail($(this).children(".messageId").text());
    });
    
    $("#mailCreateDetailSend").live("click", function(event){
        event.preventDefault();

        var to = mailToPersonaId;
        var message = $("#mymail_create_message").attr("value");
        var errorElement = "#mymail_create_error";

        myMailSend(to, message, errorElement);
    });

    $("#mailCreateDetailCancel").live("click", function(event){
        event.preventDefault();
        $("#mymail_create_message").attr("value", "");
        myMailChangeToCreate();
    });
    
    $("#mailInboxDetailSend").live("click", function(event){
        event.preventDefault();

        mailToPersonaId = $("#mymail_inbox_detail .detailPersonaId").text();
        mailToPersonaName = $("#mymail_inbox_detail .detailPersonaName").text();

        var to = mailToPersonaId;
        var message = $("#mymail_reply_message").attr("value");
        var errorElement = "#mymail_reply_error";

        myMailSend(to, message, errorElement);
    });

    $("#mailInboxDetailDelete").live("click", function(event){
        event.preventDefault();
        myMailDelete($("#mymail_inbox_detail .detailMessageId").text(), "#mymail_reply_error", "inbox");
    });
    
    $("#mailInboxDetailClose").live("click", function(event){
        event.preventDefault();
        myMailChangeToInbox();
    });

    $("#mailSentDetailEmail").live("click", function(event){
        event.preventDefault();
        
        mailToPersonaId = $("#mymail_sent_detail .detailPersonaId").text();
        mailToPersonaName = $("#mymail_sent_detail .detailPersonaName").text();

        myMailChangeToCreateDetail();
    });

    $("#mailSentDetailDelete").live("click", function(event){
        event.preventDefault();
        myMailDelete($("#mymail_sent_detail .detailMessageId").text(), "#mymail_sent_detail_error", "sent");
    });

    $("#mailSentDetailClose").live("click", function(event){
        event.preventDefault();
        myMailChangeToSent();
    });
    
    var friend_code_default_text = $("#friend_code").val();
    $("#friend_code").focus(function(){
        if($(this).val() == friend_code_default_text)
            $(this).val("");
    }).blur(function(){
        if($(this).val() == "")
            $(this).val(friend_code_default_text);
    });
    
   $('a#myFriendsGetCodeButton').live("click", function() {
		generateFriendCode();
		return false;
   });
   
	
	// Decorate page ---------------------------
   $('#decoratePage_container ul.themes li').click(function(event){
        event.preventDefault();

        var themeIndex = $('#decoratePage_container ul.themes li').index(this) + 1;
        var cssFileName = getThemeFileName(themeIndex);

        $.ajax({
            url: "ss.action?service=/v2/m1/xml/casual/charmgirls/profile/updateProfile&template=setWithStatus&noflash=1&referer=home"+getCredentials(),
            type: "POST",
            dataType: "xml",
            data: {
                theme: cssFileName
            },
            success: function(data, textStatus){
                if(sharedServicesSuccess(data)){
                    setPageTheme(cssFileName);

                    // set cookie
                    decoratePageTheme = cssFileName;
                    $.cookie('decoratePageTheme', cssFileName);

                    refreshDecoratePageWidget();
                    logActivity("PageLook");
                }
                else{
                    onscreenPopup('changeThemeError', errorTitle, errorMessage, closeButton, '#', "decoratePage");
                }
                
            }
        });
	});

    // My Friends 1st page ---------------------
    $('#codeEntry').livequery("focus", function() {
        if ($('#codeEntry').val() == enterFriendCodeRetainer)
            $('#codeEntry').val('');
    });
    $('#codeEntry').livequery("blur", function() {
        if($('#codeEntry').val() == '')
            $('#codeEntry').val(enterFriendCodeRetainer);
    });
    $(function() {
        $("#codeEntry").livequery('keypress',function (e) {
            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                submitFriendCode($('#codeEntry').val());
                return false;
            }
            else{
                return true;
            }
        });
    });
    
    $('a#myFriendsCodeSubmit').live('click',function() {
      submitFriendCode($('#codeEntry').val());
      $('#codeEntry').val(enterFriendCodeRetainer);
      $('#codeEntry').blur();
      return false;
    });
   
   // switching friends page
    $('#myFriendsAddFriendsButton').live("click", function(event){
        event.preventDefault();

        $('#myfriends_listing_container').fadeOut('medium',function() {
            $('#myfriends_listing_container').css('display','none');
            $('#myfriends_addfriend_container').fadeIn('medium');
            refresh_arrow_visibility("#myfriends_scrollbox");
        });
    });
    
    $('#addFriendBackButton').live("click", function(event){
        event.preventDefault();

        $('#myfriends_addfriend_container').fadeOut('medium',function() {
            $('#myfriends_listing_container').fadeIn('medium');
        });
    });
   
    // Start Edit Profile -----------------------
    $('#editProfile').live('click',function(event){
        event.preventDefault();
        
        profileEdit();
        return false;
    });
   
   $('#saveProfile').live('click',function() {
      // Gather data fields
      var aboutMe = $('#profileEditAboutMe').val();
      var favBand = $('#profileEditFavBand').val();
      var favBook = $('#profileEditFavBook').val();
      var favMovie = $('#profileEditFavMovie').val();
      var favShow = $('#profileEditFavShow').val();
      var quote = $('#profileEditQuote').val();
      
      // set visible profile to new values
      $('#profileReadAboutMe').html(aboutMe);
      $('#profileReadFavBand').html(favBand);
      $('#profileReadFavBook').html(favBook);
      $('#profileReadFavMovie').html(favMovie);
      $('#profileReadFavShow').html(favShow);
      $('#profileReadQuote').html(quote);
      // return form to read only
      profileSave();
      return false;
   });
	
	// Start links
	$('#editorProfileStart1,#editorProfileStart2,#editorProfileStart3').live('click',function() {
		$('div#myprofile_container div.start').hide("fast");
		profileEdit();
		return false;
	});
    // End Edit Profile --------------------------


    /////// MY PROFILE REPORT ABUSE ////////
    $('#reportAbuseLink').live('click',function(event){
        event.preventDefault();

        $("#abuser").html(currentPersonaName);
        $("#reporter").html(personaName);
        $('#reportAbusePopup').show();
    });

    $('#reportAbusePopupClose,#reportAbuseCancelButton').live('click',function() {
        resetReportAbuse();
        return false;
    });

	 $("#reportAbuseSubmitButton").live('click',function(event){
        event.preventDefault();

        var submit = true;
        if($("#violationType").val() == ""){
            submit = false;
            $('#reportAbuseResponse').html($('#reportAbuseViolationReq').html());
        }
        if($("#violationComments").val() == ""){
            submit = false;
            $('#reportAbuseResponse').html($('#reportAbuseCommentReq').html());
        }        
        
        if(!submit)
            return;
        
	    $.ajax({
	        url: "ss.action?service=/v2/m1/xml/casual/charmgirls/profile/flagProfileAsInappropriate&template=setWithStatus&referer=profile&noflash=1"+getCredentials(),
	        type: "POST",
	        dataType: "xml",
	        data: {
	            complaintType: $("#violationType").val(),
	            flaggedProfileAccountPersonaId: currentPersonaId,
	            comment: ($("#violationComments").val() ? $("#violationComments").val() : " ")
	        },
	        success: function(data, textStatus){
	            if(sharedServicesSuccess(data)){
                    $('#reportAbuseResponse').html($('#reportAbuseSubmitted').html());
                    setTimeout(function() {
                        resetReportAbuse();
                    },500);
                }
                else{
                    $('#reportAbuseResponse').html(errorMessage);
                }
	        }
	    });
    });
    
    /////// MY MAIL REPORT ABUSE ///////
    $("#mailInboxDetailReportAbuse").live("click", function(event){
        event.preventDefault();

        $("#myMailAbuser").html($("#mymail_inbox_detail .detailPersonaName").text());
        $("#myMailReporter").html(personaName);
        $('#myMailReportAbusePopup').show();
    });

    $('#myMailReportAbusePopupClose, #mailReportAbuseCancelButton').live('click',function() {
        resetMailReportAbuse();
        return false;
    });

	 $("#mailReportAbuseSubmitButton").live('click',function(event){
        event.preventDefault();

        var submit = true;
        if($("#myMailViolationType").val() == ""){
            submit = false;
            $('#myMailReportAbuseResponse').html($('#myMailReportAbuseViolationReq').html());
        }
        if($("#myMailViolationComments").val() == ""){
            submit = false;
            $('#myMailReportAbuseResponse').html($('#myMailReportAbuseCommentReq').html());
        }        
        
        if(!submit)
            return;
            
	    $.ajax({
	        url: "ss.action?service=/v2/m1/xml/casual/charmgirls/messaging/flagMessageAsInappropriate&template=setWithStatus&referer=profile&noflash=1"+getCredentials(),
	        type: "POST",
	        dataType: "xml",
	        data: {
	            complaintType: $("#myMailViolationType").val(),
	            flaggedMessageId: $("#mymail_inbox_detail .detailMessageId").text(),
	            comment: ($("#myMailViolationComments").val() ? $("#myMailViolationComments").val() : " ")
	        },
	        success: function(data, textStatus){
	            if(sharedServicesSuccess(data)){
                    $('#myMailReportAbuseResponse').html($('#myMailReportAbuseSubmitted').html());
                    setTimeout(function() {
                        resetMailReportAbuse();
                    },500);
                }
                else{
                    $('#myMailReportAbuseResponse').html(errorMessage);
                }
	        }
	    });
    });

	//////// MY PROFILE REMOVE FRIEND ////////
    $('#removeAsFriendButton').live('click',function(event) {
        event.preventDefault();
        $("#removeAsFriendPopup .friendInner .for_abuse").html($("#removeAsFriendPopup .friendInner .for_abuse").html().replace("[PersonaName]", currentPersonaName));
        $('#removeAsFriendPopup').show();
    });
    
    $('#removeAsFriendPopupClose,#removeAsFriendCancelButton').live('click',function(event) {
        event.preventDefault();
        resetRemoveAsFriend();
    });
    
    $('#removeAsFriendSubmitButton').live('click',function(event) {
        event.preventDefault();
        
        var url = null;
        if(isClubFriend)
            url = "ss.action?service=/v2/m1/xml/casual/charmgirls/friend/stopFollow&template=setWithStatus&referer=profile&noflash=1&followerPersonaId="+currentPersonaId+getCredentials();
        else if(isTrueFriend)
            url = "ss.action?service=/v2/m1/xml/casual/charmgirls/friend/removeFriend&template=setWithStatus&referer=profile&noflash=1&friendPersonaId="+currentPersonaId+getCredentials();
        
        if(url != null){
            $.ajax({
                url: url,
                type: "POST",
                dataType: "xml",
                success: function(data, textStatus){
                    if(sharedServicesSuccess(data)){
                        $('#removeAsFriendResponse').html($('#removeAsFriendRemoved').html().replace("[PersonaName]", currentPersonaName));
                        setTimeout(function() {
                            location.href = "profile.action?name="+currentPersonaName;
                        },500);
                    }
                    else{
                        $('#removeAsFriendResponse').html(errorMessage);
                    }
                }
            });
        }
    });
   
   	// Viewing other person's profile
	$("#myProfileAddAsFriend").live("click", function(event){
	    event.preventDefault();
        addAsClubFriend(currentPersonaId);
	});
	
	 // end other profile functionality
    var flashvars = {
        contentpath: $("#profile_flash .srcFile").text(),
        accountId: (currentAccountId ? currentAccountId : 0),
        xmlpath: $("#profile_flash .xmlFile").text(),
        requestorId: "casual-charmgirlsclub",
        username: (currentPersonaName ? currentPersonaName : 0),
        personaId: (currentPersonaId ? currentPersonaId : 0),
        isMe: (isMe ? 1 : 0),
        ssbase: "/clothing.action?service="
    };
    var params = {
        wmode: "opaque",
        allowFullScreen: "false",
        allowScriptAccess: "always"
    };
    var attributes = {
        name: "flash_swf"
    };
    swfobject.embedSWF("Shell.swf", "flash_swf", "954", "588", "9.0.0.0", "expressInstall.swf", flashvars, params, attributes);
}


function resetReportAbuse(){
    $('#reportAbusePopup').slideUp("fast",function() {
        $('#violationComments').val('');
        $('#violationType option:first').attr('selected','selected');
        $('#reportAbuseResponse').html('');
    });
    $('#myMailReportAbusePopup').slideUp("fast",function() {
        $('#violationComments').val('');
        $('#violationType option:first').attr('selected','selected');
        $('#reportAbuseResponse').html('');
    });
}

function resetMailReportAbuse(){
    $('#myMailReportAbusePopup').slideUp("fast",function() {
        $('#myMailViolationComments').val('');
        $('#myMailViolationType option:first').attr('selected','selected');
        $('#myMailReportAbuseResponse').html('');
    });
}

function resetRemoveAsFriend()
{
	$('#removeAsFriendPopup').hide();
    $('#removeAsFriendResponse').html('');
}

function getThemeFileName(themeIndex){
    return $('#decoratePage_container ul.themes li:nth-child(' + themeIndex + ') div.themeFile').html();
}

function prepareThemePath(themeIndex){
    if (themeIndex == null)
        return '';
        
    var internalCssFile = getThemeFileName(themeIndex);
	return prepareThemePathFromFilename(internalCssFile);
}

function refreshDecoratePageWidget(){
	var themeIndex = 0;

	var selectedImage = '<img src="images/profile/decorate/selected.png" width="29" height="29" alt="Selected" />';
	$("#decoratePage_container ul.themes li").each(function() {
        themeIndex++;
        
        var selector = $(this).children(".select_theme");
        var isCurrentTheme = (decoratePageTheme == getThemeFileName(themeIndex));

		if(isCurrentTheme){
		    $(this).addClass('onstate');
            selector.fadeOut("fast",function() {
                selector.html(selectedImage);
                selector.fadeIn("fast");
            });
        }
        else{
            $(this).removeClass('onstate');
            selector.fadeOut("fast",function() {
                selector.html($("#decoratePageSelectedThemeText").html());
                selector.fadeIn("fast");
            });
        }
    });
}

/* Another user has given the logged in user a friend code
 * and now the logged in user adds the other person as a true friend
 * @param code A seven digit alphanumeric code
 */
function submitFriendCode(code){
    code = $.trim(code);
    $.post("ss.action?service=/v2/m1/xml/casual/charmgirls/friend/acceptFriend&code="+code+"&referer=profile"+getCredentials(), {}, function(data, textStatus){
        if($(data).find("response status").text() == "success"){
            var friendPersonaName = $(data).find("response application friendPersonaName").text();
            if(friendPersonaName != ""){
                awardUser("friend_add_"+friendPersonaName, function(data){
                    var msg = $(data).find("root message").text();
                    var charm = $(data).find("root charms item[1] assets[size=1] BAS").text();
                    
                    showAwardPopup(msg, charm, 300, 900);
                });
            }

            setTimeout(function(){
                getUserDetails(friend_added);
            },1500);
        }
        else{
            $("#myfriends_add_error").html(friendCodeFailure);
        }
    }, "xml");
}

function profileEdit(){
    $('#editProfile').hide("fast");
    $('#saveProfile').show("fast");
    $('div.profileRead').hide("fast",function() {
        $('div.profileEdit').show("fast");
    });
    $('#myprofile_container').css('background-color','#96daed');
}

function profileSave(){
    $("#myProfileAjaxLoading").html(ajaxLoading());
    
    // check for various issues with the free-form text
    var validateArr = new Array();
    validateArr[0] = "profileEditQuote";
    validateArr[1] = "profileEditAboutMe";
    validateArr[2] = "profileEditFavShow";
    validateArr[3] = "profileEditFavBand";
    validateArr[4] = "profileEditFavBook";
    validateArr[5] = "profileEditFavMovie";
    
    var isValid = true;
    var errorMsg = "";
    for(var i=0; i<validateArr.length; i++){
        var field = $("#"+validateArr[i]);
        var maxLength = parseInt(field.attr("maxlength"));
        var val = field.attr("value");

        if(val.length > maxLength){
            isValid = false;
            var fieldLabel = field.parent().parent().siblings("dt").html().replace(":", "");
            
            errorMsg = $("#sharedServicesMessages .fieldTooLong").html();
            errorMsg = errorMsg.replace("[FieldName]", fieldLabel);
            break;
        }
    }

    if(!isValid){
        $("#myProfileAjaxLoading").html("");
        onscreenPopup('editProfileResult', errorTitle, errorMsg, closeButton,'#','myProfile');
        return;
    }

    $.ajax({
        url: "ss.action?service=/v2/m1/xml/casual/charmgirls/profile/updateProfile&template=setWithStatus&noflash=1"+getCredentials(),
        type: "POST",
        data: {
            // Pass a space if the field is empty so it will be updated
            quote: ($("#profileEditQuote").attr("value") ? $("#profileEditQuote").attr("value") : ""),
            aboutMe: ($("#profileEditAboutMe").attr("value") ? $("#profileEditAboutMe").attr("value") : ""),
            favShow: ($("#profileEditFavShow").attr("value") ? $("#profileEditFavShow").attr("value") : ""),
            favBand: ($("#profileEditFavBand").attr("value") ? $("#profileEditFavBand").attr("value") : ""),
            favBook: ($("#profileEditFavBook").attr("value") ? $("#profileEditFavBook").attr("value") : ""),
            favMovie: ($("#profileEditFavMovie").attr("value") ? $("#profileEditFavMovie").attr("value") : "")
        },
        dataType: "xml",
        success: function(data, textStatus){
            $("#myProfileAjaxLoading").html("");
            if(sharedServicesSuccess(data)){
                $('#saveProfile').hide("fast");
                $('#editProfile').show("fast");
                $('div.profileEdit').hide("fast",function() {
                    $('div.profileRead').show("fast");
                });
                $('#myprofile_container').css('background-color','#edf5fa');

                awardUser("profile_save_info", function(data){
                    var msg = $(data).find("root message").text();
                    var charm = $(data).find("root charms item[1] assets[size=1] BAS").text();
                    
                    showAwardPopup(msg, charm, -50, 900);
                });
            }
            else{
                onscreenPopup('editProfileResult', errorTitle, errorMessage, closeButton,'#','myProfile');
            }
        }
    });
}

function initMyProfile(){
    if(is_logged_in || !isMe){
        $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/profile/getProfileDetails&template=getProfile&noflash=1&referer=profile"+getCredentialsForCurrentUser(), {}, function(data, textStatus){
            $("#myprofile_container").html($(data).find("#myprofile_container").html());

            if(!is_logged_in || (!isMe && !isTrueFriend)){
                $("#myprofile_container h2:eq(1)").hide();
                $("#myprofile_container .freeform").hide();
            }

            if(is_logged_in){
                if(isMe){
                    $("#editProfile").show();
                }
                else{
                    if(isTrueFriend || isClubFriend)
                        $("div#myProfileReportAbuseRemoveFriend").show();
                    else
                        $("div#myProfileAddAsFriend").show();
                }
            }
            else{
                $("#myProfileNotLoggedIn").show();
            }

            $("#myProfileElement_points").html($("#points_stat").html());
            $("#myprofile_container .inner").show();
            $("#myprofile_container").show();

            setTimeout(function(){
                refresh_arrow_visibility("#myprofile_scrollbox");
            }, 500);
        }, "html");
    }
    else{
        $("myprofile_container .inner").hide();
        $("#myProfileNotLoggedIn").show();
        $("#myprofile_container").show();
        refresh_arrow_visibility("#myprofile_scrollbox");
    }
}

function initMyFriends(){
    $("#myfriends_container").hide();
    $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/friend/getFriends&template=getFriends&noflash=1&referer=profile&pageSize=1000"+getCredentialsForCurrentUser(), {}, function(data, textStatus){
        $("#myfriends_container").html($(data).find("#myfriends_container").html());
        
        if(!isMe || !is_logged_in)
            $("#myfriends_add_panel .addFriendsControls").hide();
        
        $("#myfriends_container").show();
        refresh_arrow_visibility("#myfriends_scrollbox");
    }, "html");
}

function initClubFriends(){
    $("#clubfriends_friends_listing").hide();
    $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/friend/getFollowedUsers&template=getFollowedUsers&noflash=1&referer=profile&pageSize=1000"+getCredentialsForCurrentUser(), {}, function(data, textStatus){
        $("#clubfriends_container").html($(data).find("#clubfriends_container").html());
        if(!isMe)
            $("#clubfiends_addfriends").hide();
        
        $("#clubfriends_friends_listing").show();
        $("#clubfriends_container").show();
        refresh_arrow_visibility("#clubfriends_scrollbox");
    }, "html");
}

function addAsClubFriend(newPersonaId){
    $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/friend/startFollow&template=setWithStatus&noflash=1&referer=profile&followAccountPersonaId="+newPersonaId+getCredentials(), {}, function(data, textStatus){
        if(sharedServicesSuccess(data)){
            setTimeout(function() {
                location.href = "profile.action?name="+currentPersonaName;
            },500);
        }
        else{
            $("#addAsFriendError").text(errorMessage);
        }
    }, "xml");
}

function initMyNews(){
    $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/activity/getAllActivities&template=getActivities&noflash=1&referer=profile"+getCredentialsForCurrentUser(), {}, function(data, textStatus){
        $("#mynews_container").html($(data).find("#mynews_container").html());
        $("#mynews_container").show();
        refresh_arrow_visibility("#mynews_scrollbox");
    }, "html");
}

function initMyMail(){
    initMyMailFriends();
    initMyMailInbox();
    initMyMailSent();
    myMailChangeToInbox();
}

function initMyMailFriends(){
    $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/friend/getFriends&template=getMailFriends&noflash=1&referer=profile&pageSize=1000"+getCredentialsForCurrentUser(), {}, function(data, textStatus){
        $("#mymail_inbox_friends .friends_listing").html($(data).find("#friends_listing").html());
        $("#mymail_sent_friends .friends_listing").html($(data).find("#friends_listing").html());
        $("#mymail_create_friends .friends_listing").html($(data).find("#friends_listing").html());
    }, "html");
}

function initMyMailInbox(){
    $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/messaging/getInboxMessages&template=getInboxMessages&noflash=1&referer=profile"+getCredentialsForCurrentUser(), {}, function(data, textStatus){
        $("#mymail_inbox_listing").html($(data).find("#mymail_inbox_listing").html());
    }, "html");
}

function initMyMailSent(){
    $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/messaging/getSentMessages&template=getSentMessages&noflash=1&referer=profile"+getCredentialsForCurrentUser(), {}, function(data, textStatus){
        $("#mymail_sent_listing").html($(data).find("#mymail_sent_listing").html());
    }, "html");
}

function myMailSend(to, message, errorElement){
    $(errorElement).html(ajaxLoading());

    $.ajax({
        url: "ss.action?service=/v2/m1/xml/casual/charmgirls/messaging/sendMessage&template=setWithStatus&noflash=1&referer=profile"+getCredentials(),
        type: "POST",
        dataType: "xml",
        data: {
            friendAccountPersonaId: to,
            message: message
        },
        success: function(data, textStatus){
            if(sharedServicesSuccess(data)){
                $(errorElement).html("");
                initMyMailSent();
                myMailChangeToCreate();
            }
            else{
                $(errorElement).html(errorMessage);
            }                
        }
    });
}

function myMailDelete(messageId, errorElement, dest){
    $(errorElement).html(ajaxLoading());
    
    $.ajax({
        url: "ss.action?service=/v2/m1/xml/casual/charmgirls/messaging/deleteMessageById&template=setWithStatus&noflash=1&referer=profile"+getCredentials()+"&messageId="+messageId,
        type: "POST",
        dataType: "xml",
        success: function(data, textStatus){
            if(sharedServicesSuccess(data)){
                $(errorElement).html("");
                
                if(dest == "inbox"){
                    initMyMailInbox();
                    myMailChangeToInbox();                
                }
                else if(dest == "sent"){
                    initMyMailSent();
                    myMailChangeToSent();
                }
            }
            else{
                $(errorElement).html(closeButton);
            }                
        }
    });
}

function initDecoratePage(){
    if($.cookie("decoratePageTheme") == null){
        $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/profile/getProfile"+getCredentials(), {}, function(data, textStatus){
            decoratePageTheme = $(data).find("response application theme").text();
            $.cookie("decoratePageTheme", decoratePageTheme);
            refreshDecoratePageWidget();
            $("#decoratePage_container").show();
            refresh_arrow_visibility("#decoratepage_scrollbox");
        }, "xml");
    }
    else{
        refreshDecoratePageWidget();
        refresh_arrow_visibility("#decoratepage_scrollbox");
        $("#decoratePage_container").show();
    }
}

function generateFriendCode(){
    $.post("ss.action?service=/v2/m1/xml/casual/charmgirls/friend/generateFriendCode&x=1"+getCredentials(), {}, function(data, textStatus){
        var code = $(data).find("response application code code").text();
        $('#myfriends_option2_code').html(code);
        $('#myfriends_option2_code_container').fadeIn();
    }, "xml");  
}

function myMailChangeToInboxTab(){
    if(mailTab != "inbox"){
        var tab = "div#mymailtabs .inbox";
        $(tab).siblings(".sent").removeClass("sent_on");
        $(tab).siblings(".create").removeClass("create_on");
        if(!$(tab).hasClass("inbox_on"))
            $(tab).addClass("inbox_on");

        mailTab = "inbox";
    }
}

function myMailChangeToSentTab(){
    if(mailTab != "sent"){
        var tab = "div#mymailtabs .sent";
        $(tab).siblings(".inbox").removeClass("inbox_on");
        $(tab).siblings(".create").removeClass("create_on");
        if(!$(tab).hasClass("sent_on"))
            $(tab).addClass("sent_on");

        mailTab = "sent";
    }
}

function myMailChangeToCreateTab(){
    if(mailTab != "create"){
        var tab = "div#mymailtabs .create";
        $(tab).siblings(".sent").removeClass("sent_on");
        $(tab).siblings(".inbox").removeClass("inbox_on");
        if(!$(tab).hasClass("create_on"))
            $(tab).addClass("create_on");

        mailTab = "create";
    }
}

function myMailChangeToInboxListing(){
    $("#mymail_sent").hide();
    $("#mymail_create").hide();
    $("#mymail_scrollbox .body").scrollTop("0px");

    $("#mymail_inbox_detail").hide();
    $("#mymail_inbox_listing").show();
    $("#mymail_inbox_friends").show();
    $("#mymail_inbox").show();
    
    refresh_arrow_visibility("#mymail_scrollbox");
    myMailChangeToInboxTab();
}

function myMailChangeToInboxDetail(messageId){
    $("#mymail_sent").hide();
    $("#mymail_create").hide();    
    $("#mymail_scrollbox .body").scrollTop("0px");

    $("#mymail_inbox_listing").hide();
    $("#mymail_inbox_friends").hide();

    $("#mymail_inbox_detail").hide();
    $("#mymail_inbox_detail").html(ajaxLoading());
    $("#mymail_inbox_detail").show();
        
    $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/messaging/getMessageById&template=getInboxMessageById&noflash=1&referer=profile"+getCredentials()+"&messageId="+messageId, {}, function(data, textStatus){
        $("#mymail_inbox_detail").html($(data).find("#mymail_inbox_detail").html());
        
        var awardId = $("#mymail_inbox_detail .awardId").text();

        // Don't show the report abuse link if this is an award message
        if(awardId)
            $("#mailInboxDetailReportAbuse").hide();
        else
            $("#mailInboxDetailReportAbuse").show();
        
        $("#mymail_inbox_detail").show();        

        if($.inArray($("#mymail_inbox_detail .detailPersonaId").text(), trueFriends) == -1 || isDummyAccount($(data).find("#mymail_inbox_detail .detailPersonaName").text()))
            $("#mailInboxDetailSend").hide();
        else
            $("#mailInboxDetailSend").show();

        $("#mymail_inbox").show();
        refresh_arrow_visibility("#mymail_scrollbox");
        myMailChangeToInboxTab();
        
        mailToPersonaId = $(data).find("#mymail_inbox_detail .detailPersonaId").text();

        // Check for award id and attempt to award the user
        if(awardId)
            awardUser(awardId, null);

    }, "html");
}

function myMailChangeToInbox(){
    myMailChangeToInboxListing();
}

function myMailChangeToSentListing(){
    $("#mymail_inbox").hide();
    $("#mymail_create").hide();
    $("#mymail_scrollbox .body").scrollTop("0px");
    

    $("#mymail_sent_detail").hide();    
    $("#mymail_sent_listing").show();
    $("#mymail_sent_friends").show();
    $("#mymail_sent").show();
    refresh_arrow_visibility("#mymail_scrollbox");
    myMailChangeToSentTab();
}

function myMailChangeToSentDetail(messageId){
    $("#mymail_inbox").hide();
    $("#mymail_create").hide();    
    $("#mymail_scrollbox .body").scrollTop("0px");
    
    $("#mymail_sent_listing").hide();
    $("#mymail_sent_friends").hide();

    $("#mymail_sent_detail").hide();
    $("#mymail_sent_detail").html(ajaxLoading());
    $("#mymail_sent_detail").show();

    $.get("ss.action?service=/v2/m1/xml/casual/charmgirls/messaging/getMessageById&template=getSentMessageById&noflash=1&referer=profile"+getCredentials()+"&messageId="+messageId, {}, function(data, textStatus){
        $("#mymail_sent_detail").html($(data).find("#mymail_sent_detail").html());
        $("#mymail_sent_detail").show();        

        if($.inArray($("#mymail_sent_detail .detailPersonaId").text(), trueFriends) == -1)
            $("#mailSentDetailEmail").hide();
        else
            $("#mailSentDetailEmail").show();

        $("#mymail_sent").show();
        refresh_arrow_visibility("#mymail_scrollbox");
        myMailChangeToSentTab();
    }, "html");
}

function myMailChangeToSent(){
    myMailChangeToSentListing();
}

function myMailChangeToCreateFriends(){
    $("#mymail_sent").hide();
    $("#mymail_inbox").hide();
    $("#mymail_scrollbox .body").scrollTop("0px");
    
    $("#mymail_create_to")
        .attr("value", "")
        .attr("readonly", true);
        
    $("#mymail_create_detail").hide();
    $("#mymail_create_friends").show();
    $("#mymail_create").show();
    refresh_arrow_visibility("#mymail_scrollbox");
    myMailChangeToCreateTab();
}

function myMailChangeToCreateDetail(){
    $("#mymail_sent").hide();
    $("#mymail_inbox").hide();
    $("#mymail_scrollbox .body").scrollTop("0px");

    $("#mymail_create_to")
        .attr("value", mailToPersonaName)
        .attr("readonly", true);
        
    $("#mymail_create_friends").hide();
    $("#mymail_create_message").attr("value", "");
    $("#mymail_create_detail").show();
    $("#mymail_create_message").focus();
    $("#mymail_create").show();
    refresh_arrow_visibility("#mymail_scrollbox");
    myMailChangeToCreateTab();
}

function myMailChangeToCreate(){
    myMailChangeToCreateFriends();
}

function initStatusBar(){
    // Set up the status bar
    var ssCall = "ss.action?service=/v2/m1/xml/casual/charmgirls/general/getUserStatus&template=getUserStatus&noflash=1&referer=home"+getCredentialsForCurrentUser();
    $.get(ssCall, {}, function(data, textStatus){
        $("#statusbar").html($(data).find("#statusbar").html());
	    if(isMe){
            if($("#statusbar .status .message").text().match(/^\s*$/))
                $("#changeStatusNow").text($("#headerMessages .changeStatusInstructions").text());
            else
                $("#changeStatusNow").text(changeStatusText);
	    }
	    else{
		    $('#statusbar .welcome .label').hide();
		    $('#statusbar .welcome .username').hide();
		    $('#statusbar #changeStatusNow').hide();
		    
		    $("#statusbar .welcome .labelOther").html($(data).find("#statusbar .welcome .labelOther").html().replace("[PersonaName]", currentPersonaName));
            $("#statusbar .welcome .labelOther").show();

	        if(!isTrueFriend)
	            $("#statusbar .status").hide();
	    }
	        
        $("#statusbar").slideDown();
    }, "html");
}

function getCredentialsForCurrentUser(){
    if(!currentAccountId)
        return getCredentials();

    var ret = "&requestorId=casual-charmgirlsclub";
    if(currentAccountId)
        ret += "&accountId="+encode(currentAccountId);
    if(currentPersonaId)
        ret += "&personaId="+currentPersonaId;

    return ret;
}

function isDummyAccount(name){
    return (dummyAccounts.indexOf(name) != -1)
}
