﻿//$.ajaxSetup({
//    // Disable caching of AJAX responses */
//    cache: false
//});
var suggestion;
var request;
var profileUrl;
$(window).bind('hashchange', function (e) {
    if ($.cookie("f2.tmz") == null) {
        var tmzOff = new Date().getTimezoneOffset();
        $.cookie("f2.tmz", tmzOff.toString(), { expires: 1 });
    }
});
function refreshAds(XMLHttpRequest) {
    if (XMLHttpRequest == undefined || (XMLHttpRequest.readyState == 4 && XMLHttpRequest.status == 200)) {
        var currentTime = new Date();
        var ads = $('iframe.adsense');
        ads.each(function () {
            var ad = $(this).attr('longdesc');
            $(this).attr('src', String.format('/adsense/{0}?s={1}', ad, currentTime.getTime()));
        });
    }
}
showSendMessageToF = function (e) {
    $(e).addClass('hidden');
    $(e).parent().find('.f-mssg').removeClass('hidden');
    $('#f-mssg').focus();
}
sendMessageToF = function (e) {
    var dataString = String.format('mssg={0}', $.URLEncode($('#f-mssg').val()));
    //alert(dataString); return;
    ajaxPost('/account/sendmessagetof', dataString, 'json', function (data, textStatus) {
        closeBoxy(e);
    });
}
//fbLogin = function () {

//    FB.login(function (response) {
//        if (response.session) {
//            if (response.perms) {
//                // user successfully logged in and granted permissions
//                var dataString = String.format('token={0}', response.session.access_token);
//                ajaxPost('/account/signinwithfacebook', dataString, 'json', function (data, textStatus) {
//                    if (data.Success) {
//                        //publishFBWallPost();
//                        window.location = data.RedirectToUrl;
//                    }
//                });
//            } else {
//                // user is logged in, but did not grant any permissions
//                errorBoxy('Cannot Sign In With Facebook', 'You must grant required permissions before you can sign in to Friendango using your Facebook account.');

//            }
//        } else {
//            // user cancelled login
//            errorBoxy('Sign In Cancelled', 'You have cancelled the sign in process.');
//        }
//    }, { perms: "user_about_me,user_birthday,user_location,email,publish_stream,offline_access" });
//}
function publishFBWallPost(token) {
    var params = {};
    params['message'] = 'I have just joined Friendango!';
    params['name'] = 'Friendango® - meet new friends & more';
    params['description'] = 'A simple way to meet new friends.';
    params['link'] = 'http://www.friendango.com/';
    params['picture'] = 'http://www.friendango.com/content/images/f2-icon-80.png';
    //params['access_token'] = token;

    FB.api('/me/feed', 'post', params, function (response) {
        if (!response || response.error) {
            //alert('Error occured');
        } else {
            //alert('Published to stream - you might want to delete it now!');
            window.location = '/?fb_token=' + token;
        }
    });
}
clearOnlineFriends = function (e) {
    $('.online.friend-list .content').html("<li class='nf' style='color:#666;float:none;width:170px;'>No friends are online.</li>");
}
updateOnlineFriend = function (e) {
    //var li = $(String.format(".online.friend-list li[id='{0}']", e.id));

    //    if (li.length > 0) {
    //        if (li.hasClass('available') || li.hasClass('away')) {
    //            li.attr('class', e.s);
    //        } else {
    //            alert('remove');
    //            li.remove();
    //        }
    //    } else if (e.s == 'available' || e.s == 'away') {


    // remove no online friends mssg
    $('.online.friend-list .content li.nf').remove();
    var friendHtml = String.format("<li id='{2}' class='{3}'><div class='pphoto'><a title='Chat with {0}' href='javascript:void(0)' onclick='javascript:jqcc.cometchat.chatWith(\"{2}\");'><img class='photo' alt='{0}' src='{1}'/></a><div class='s'></div></div></li>", e.n, e.a, e.id, e.s);
    $('.online.friend-list .content').append(friendHtml);
    //}
}
refreshPage = function (e) {
    //$(e).removeAttr('id').addClass('ajax-loading').html('Refreshing...');
    window.location.reload(true);
}
fixBG = function () {
    var windowWidth = $('#bd').width();
    var leftPos = parseInt(windowWidth) - 985 - (1800 - 180);
    if (windowWidth <= 985) leftPos = -1619; else if (windowWidth >= 2560) leftPos = 2;
    $('#bd,#hd').css('background-position', leftPos + 'px 0');
    if ($('#content-template').length > 0) {
        var leftOffset = parseInt(windowWidth) - 985;
        if (leftOffset > 0) {
            leftOffset = leftOffset / 2 + 180;
        }
    }
}
$(document).ready(function () {

    // Get ProfileName
    var re = new RegExp(/(\w*[-]?)*/);
    profileUrl = re.exec(window.location.pathname.substr(1))[0];

    fixBG();
    $(window).resize(function () {
        fixBG();
    });

    //$('#user-hd-right, #public-hd-right').corner('top 4px');

    //profileUrl = window.location.pathname.substr(1).split('#', 1)[0];

    // Hide Updating panel
    $('#updating').hide();
    // Ajax Request Start
    $('#updating').ajaxStart(function () {
        $(this).fadeIn('fast');
    });
    // Ajax Request Stop
    $('#updating').ajaxStop(function () {
        $(this).fadeOut('fast');
    });

    $('#quick-search').watermark('watermark', "Search Friendango");

    //    toggleGLocation = function (e) {
    //        var gloc = $('#glocation');
    //        if (gloc.hasClass('hidden')) gloc.removeClass('hidden'); else gloc.addClass('hidden');
    //    }

    checkBoxSwitch = function (eid) {
        var e = $('#' + eid);
        if (e.val() == 'true') e.val('false'); else e.val('true');
    }

    // check for alerts every x milliseconds
    //window.setInterval('checkAlerts()', 1000);

    // Sign In
    signIn = function (e) {
        if (isPosting(this)) return false; // are we posting? abort
        startPosting(this); // set posting var

        ajaxPost('/account/signIn', $('#signin-form').serialize(), 'json', function (data, textStatus) {
            if (data.Success) {
                window.location = data.RedirectToUrl;
            } else {
                window.location = '/account/signin?invalid_signin=1';
                //incorrectUsrPwd(data.Message);
            }
            endPosting(this);
        });
    }
    incorrectUsrPwd = function (mssg) {
        $('#signin-form .mssg div').html(mssg).slideDown('fast');
        $('#password').val('');
    }
    $('form.membership').submit(function (e) {
        e.preventDefault();
    });
    // Request Activation Code
    //    requestActivationCode = function (e) {
    //        if (isPosting(this)) return false; // are we posting? abort
    //        startPosting(this); // set posting var

    //        ajaxPost('/account/requestactivationcode', $('#request-code-form').serialize(), 'json', function (data, textStatus) {
    //            if (data.Success == undefined || !data.Success) {
    //                validateJsonOperationResult(data);
    //                //Recaptcha.reload();
    //            } else {
    //                closeAllErrorPrompts();
    //                confirmActivationCode($('#Email').val());
    //            }

    //            endPosting(this);
    //        });
    //    }
    // Create Account
    createAccount = function (e) {
        $(e).hide();
        $('#creating-your-account').show();

        if (isPosting(this)) return false; // are we posting? abort
        startPosting(this); // set posting var

        ajaxPost('/account/createaccount', $('#new-member-form').serialize(), 'json', function (data, textStatus) {
            if (data.Success == undefined || !data.Success) {
                validateJsonOperationResult(data);
                Recaptcha.reload();

                $('#create-account-btn').show();
                $('#creating-your-account').hide();
            } else {
                window.location = '/#welcome';
            }

            endPosting(this);
        });
    }
    sendConfirmationEmail = function (showInfoBoxy) {
        ajaxGet('/account/sendconfirmationemail', 'html', function (data, textStatus) {
            if (showInfoBoxy) infoBoxy('Confirmation Email Sent', 'A confirmation email has been re-sent to you. Click on the confirmation link in your email to confirm your email address.', 5000);
        });
    }
    sendVerificationEmail = function (showInfoBoxy) {
        ajaxGet('/account/sendverificationemail', 'html', function (data, textStatus) {
            if (showInfoBoxy) infoBoxy('Verification Email Sent', 'A verification email has been sent to you. Click on the verification link in your email to verify your email address.', 5000);
        });
    }
    verifyMemberInfo = function (e) {
        if (isPosting(this)) return false; // are we posting? abort
        startPosting(this); // set posting var
        $(e).attr('disabled', 'disabled');
        ajaxPost('/account/verifymemberinfo', $('#new-member-form').serialize(), 'json', function (data, textStatus) {
            if (data.Success == undefined || !data.Success) {
                validateJsonOperationResult(data);
            } else {
                validateJsonOperationResult(data);
                $('#new-member-form tr.signup-btn').hide();
                $('#new-member-form tr.is-human').show();
                $('#recaptcha_response_field').focus();
            }

            endPosting(this);
        }, function (data, textStatus) { // COMPLETE
            $(e).removeAttr('disabled');
        });
    }
    pleaseConfirmAccount = function () {
        getBoxy('/account/pleaseconfirmaccount', '', function (data) {
            var boxy = $('.info-boxy');
            if (boxy.length > 0) {
                boxy.parents('.boxy-wrapper').effect('bounce');
            }
        });
    }
    //    confirmActivationCode = function (email) {
    //        ajaxGet(String.format('/account/confirmactivationcode?email={0}', email != undefined ? email : ''), 'html', function (data, textStatus) {
    //            $('#membership-container #signup-content').html(data);
    //            $('#activate-form.membership').submit(function (e) {
    //                e.preventDefault();
    //            });
    //        });
    //        closeAllErrorPrompts();
    //    }
    //    activateProfile = function (e) {
    //        if (isPosting(this)) return false; // are we posting? abort
    //        startPosting(this); // set posting var

    //        ajaxPost('/account/activateprofile', $('#activate-form').serialize(), 'json', function (data, textStatus) {
    //            if (data.Success == undefined || !data.Success) {
    //                if (data.Message != undefined) errorBoxy('Activation Failed', data.Message);
    //                validateJsonOperationResult(data);
    //            } else {
    //                window.location = data.RedirectToUrl;
    //            }

    //            endPosting(this);
    //        });
    //    }
    //    createProfile = function (e) {
    //        if (isPosting(this)) return false; // are we posting? abort
    //        startPosting(this); // set posting var
    //        //alert($('#create-profile-form').serialize()); return;
    //        ajaxPost('/account/createprofile', $('#create-profile-form').serialize(), 'json', function (data, textStatus) {
    //            if (data.Success == undefined || !data.Success) {
    //                validateJsonOperationResult(data);
    //                //Recaptcha.reload();
    //            } else {
    //                window.location = data.RedirectToUrl;
    //            }
    //        });

    //        endPosting(this);
    //    }

    // GBtn DropDownList
    //    showOptions = function (e) {
    //        $(this).addClass("active");
    //        alert($(this));
    //        return;
    //        $(this).parent().find('.gbtn-options').css("left", $(this).eq(0).offset().left).css("min-width", "200");
    //        $(this).parent().find('.gbtn-options').toggle();
    //    }
    //    //    $('.gbtn.ddl').live('click', function (e) {
    //    //        
    //    //    });
    //    setDropArrow = function (obj, txt) {
    //        if (obj == undefined) {
    //            $('.gbtn.ddl span span').each(function (e) {
    //                $(this).html(String.format('{0} ▼', $(this).html()));
    //            });
    //        } else {
    //            obj.html(String.format('{0} ▼', txt));
    //        }
    //    }
    //    setDropArrow();
    //    $('.gbtn-options ul li').live('click', function (e) {
    //        $(this).parents('.gbtn-options').hide();
    //        var val = $(this).find('a').attr('value');
    //        var txt = $(this).find('a').html();
    //        setDropArrow($(this).parents('.ddl-action').find('.gbtn.ddl span span'), txt);
    //        $(this).parents('.ddl-action').find('.gbtn-val').val(val).trigger('click');
    //        // remove selected
    //        $(this).parent().find('li').removeClass('selected');
    //        // set selected
    //        $(this).addClass('selected');
    //    })
    //                   .parents('.gbtn-options')
    //                   .blur(function () {
    //                       $(this).parents('.gbtn-options').hide();
    //                   });
    //    $('.gbtn.ddl').blur(function (e) {
    //        $(this).removeClass("active");
    //        if (!$('ul li.highlight').length) $('.gbtn-options').hide();
    //    });
    //    $('.gbtn-options ul li').hover(function (e) {
    //        $(this).toggleClass("highlight");
    //    });
});

checkAlerts = function () {
    ajaxGet('/Alerts/Check', 'html', function (data, textStatus) {
        // If '1' is returned the alerts are no longer in the cache, meaning they need to be updated
        if (data == '1') updateAlerts();
    });
}

updateAlerts = function () {
    ajaxGet('/Alerts/GetAlerts', 'json', function (data, textStatus) {
        var requestsCount = 0;
        var messagesCount = 0;
        var updatesCount = 0;
        var totalUnreadMessagesCount = 0;
        var notificationsCount;
        var reportedCount;
        var notApprovedThreadCount;
        if (data != undefined) { // Noticed an error where this was undefinded (i guess) and crashed the script
            for (var a in data.Alerts) {
                var type = data.Alerts[a].AlertType;
                // UnreadMessages
                if (type == 'unreadmessages') {
                    messagesCount += data.Alerts[a].Count;
                }
                // UnreadUpdates
                if (type == 'unreadupdates') {
                    updatesCount = data.Alerts[a].Count;
                }
                // FriendRequests & Suggestions
                if (type == 'friendrequests' || type == 'friendsuggestions') {
                    requestsCount += data.Alerts[a].Count;
                }
                // Notifications
                if (type == 'notifications') {
                    notificationsCount = data.Alerts[a].Count;
                }
                // Reported
                if (type == 'reported') {
                    reportedCount = data.Alerts[a].Count;
                }
                // Not Approved Threads
                if (type == 'notapprovedthreads') {
                    notApprovedThreadCount = data.Alerts[a].Count;
                }
            }
            totalUnreadMessagesCount = messagesCount + updatesCount;
            // Header
            setHeaderAlert('messages', totalUnreadMessagesCount);
            setHeaderAlert('requests', requestsCount);
            setHeaderAlert('notifications', notificationsCount);
            var isUpdatesSubVisible = $('.home-nav .messages.updates').is(':visible');
            // special case for messages
            if (messagesCount == 0 && updatesCount > 0) $('#main-nav .messages.on').attr('href', '/#messages/updates');
            else $('#main-nav .messages.on').attr('href', '/#messages/inbox');
            // LeftNav
            if (totalUnreadMessagesCount > 0 && !isUpdatesSubVisible) {
                $('.home-nav .messages.inbox span').addClass('count').html('(' + totalUnreadMessagesCount + ')');
            } else if (messagesCount > 0) {
                $('.home-nav .messages.inbox span').addClass('count').html('(' + messagesCount + ')');
            } else {
                $('.home-nav .messages.inbox span').removeClass('count').html('');
            }
            if (updatesCount > 0 && isUpdatesSubVisible) {
                $('.home-nav .messages.updates span').addClass('count').html('(' + updatesCount + ')');
            } else {
                $('.home-nav .messages.updates span').removeClass('count').html('');
            }
            if (requestsCount > 0) {
                $('.home-nav .friends.friendfeed span').addClass('count').html('(' + requestsCount + ')');
            } else {
                $('.home-nav .friends.friendfeed span').removeClass('count').html('');
            }
            if (notificationsCount > 0) {
                $('.home-nav .notifications:not(.settings) span').addClass('count').html('(' + notificationsCount + ')');
            } else {
                $('.home-nav .notifications:not(.settings) span').removeClass('count').html('');
            }
            if (reportedCount > 0) {
                $('.home-nav .admin.reported span').addClass('count').html('(' + reportedCount + ')');
            } else {
                $('.home-nav .admin.reported span').removeClass('count').html('');
            }
            var isPendingApprovalSubVisible = $('.home-nav .forums.pendingapprovalthreads').is(':visible');
            if (notApprovedThreadCount > 0 && !isPendingApprovalSubVisible) {
                $('.home-nav .forums.pendingapprovalthreads span').removeClass('count').html('');
                $('.home-nav .forums.manage span').addClass('count').html('(' + notApprovedThreadCount + ')');
            } else if (notApprovedThreadCount > 0 && isPendingApprovalSubVisible) {
                $('.home-nav .forums.manage span').removeClass('count').html('');
                $('.home-nav .forums.pendingapprovalthreads span').addClass('count').html('(' + notApprovedThreadCount + ')');
            } else {
                $('.home-nav .forums.manage span, .home-nav .forums.pendingapprovalthreads span').removeClass('count').html('');
            }

            var alertsContentBlock = $('#alerts.content-block');
            if (alertsContentBlock.length > 0) {
                alertsContentBlock.replaceWith(data.AlertsContentBlock);
            }
        }
    });
}
setHeaderAlert = function (type, count) {
    if (count > 0) {
        $('#main-nav .' + type).addClass('on').find('.count-out').css('display', 'block');
        $('#main-nav .' + type + ' .count-in').html(count);
    } else {
        $('#main-nav .' + type).removeClass('on').find('.count-out').css('display', 'none');
    }
}

sendPassword = function (e) {
    if (!validateEmail($('#email').val())) {
        $.validationEngine.buildPrompt("#email", 'Invalid Email address', "error");
        return;
    }
    if (isPosting(this)) return false; // are we posting? abort
    startPosting(this); // set posting var

    var dataString = String.format('email={0}', $.URLEncode($('#email').val()));
    //alert(dataString); return;
    ajaxPost('/account/forgotpassword', $('#forgot-pwd-form').serialize(), 'json', function (data, textStatus) {
        if (data.Success) {
            validateJsonOperationResult(data);
            infoBoxy('Password Sent', String.format('We have emailed your password to {0}', $('#email').val()), 2000);
        } else {
            validateJsonOperationResult(data);
            //errorBoxy('Cannot Send Password', 'We could not send you your password.');
        }
        $('#email').val('');
        Recaptcha.reload();
        endPosting(this);
    });
}
function validateEmail(email) {
    var emailPattern = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return emailPattern.test(email);
}
notImplemented = function (e) {
    alert('Sorry, this feature is still in development and will be available soon.')
    return false;
};

imgLazyLoad = function (e) {
    if (e == undefined) e = $("img");
    e.lazyload({ placeholder: "/Content/Images/white.gif" });
}

// Gets querystring parameter value from fragment
getFragmentQS = function (param) {
    return $.deparam.querystring($.param.fragment())[param];
}

disableAction = function (e) {
    // cancels the event
    e.preventDefault();
    return false;
}

//$().dateSelectBoxes('birthmonth', 'birthday', 'birthyear');

// Go Back
goBack = function (e) {
    history.back();
}
// Scrolls page to the top/bottom
scrollTop = function (e) {
    $('html, body').animate({ scrollTop: 0 }, 'fast');
}
scrollBtm = function (e, complete) {
    $('html, body').animate({ scrollTop: $(document).height() }, 'fast', complete);
}
deleteBlogConfirm = function (id) {
    getBoxy(String.format('/Blog/DeleteBlogConfirm?bid={0}', id), '');
}
deleteBlog = function (e, bid) {
    var dataString = String.format('bid={0}', bid);
    ajaxPost('/Blog/DeleteBlog', dataString, 'json', function (data, textStatus) {
        closeBoxy(e);
        // remove delete blog from ui
        $(String.format("#blogs .blog[id='{0}']", bid)).slideUp('fast', function (e) {
            $(this).remove();
        });
    });
}
deleteCommentConfirm = function (cid, coid) {
    getBoxy(String.format('/comment/deletecommentconfirm?cid={0}&coid={1}', cid, coid), '');
}
deleteComment = function (e, cid, coid) {
    closeBoxy(e, function () {
        var dataString = String.format('cid={0}&coid={1}', cid, coid);
        ajaxPost('/comment/deletecomment', dataString, 'json', function (data, textStatus) {
            $(String.format('#{0}', cid)).slideUp('fast');
        });
    });
}
deleteStoryConfirm = function (sid) {
    getBoxy(String.format('/activity/deletestoryconfirm?sid={0}', sid), '');
}
deleteStory = function (e, sid) {
    closeBoxy(e, function () {
        var dataString = String.format('sid={0}', sid);
        ajaxPost('/activity/deletestory', dataString, 'json', function (data, textStatus) {
            $(String.format('#{0}', sid)).slideUp('fast');
        });
    });
}
hideStory = function (e, sid) {
    var dataString = String.format('sid={0}', sid);
//    ajaxPost('/activity/hidestory', dataString, 'json', function (data, textStatus) {
//        $(e).parents('dl.item').slideUp('fast');
//    });
}
//    // Account Settings
//    $('.settings-tab .change-btn').live('click', function () { // Show Edit section
//        hideEditSections($(this)); // hide any open edit sections
//        $(this).parents('dd.text').find('.edit').show(); // show the clicked edit section
//        $(this).parents('dd.text').find('.view').hide(); // hide the clicked view section
//        $(this).parents('li').addClass('selected');
//    });
//    $('.settings-tab .cancel-btn').live('click', function () { // Hide Edit sections / Show View sections
//        hideEditSections($(this));
//    });
//    function hideEditSections(btn) {
//        btn.parents('.tab-content').find('.edit').hide(); // hide any open edit sections
//        btn.parents('.tab-content').find('.view').show(); // show all view sections
//        btn.parents('.tab-content').find('li').each(function () { $(this).removeClass('selected'); });
//    }

// Prep Post Comment
//    $('.comments .post-comment').live('click', function (e) {
//        $(this).find('dt').show();
//        $(this).find('textarea').attr('rows', '2').val('');
//        $(this).find('.action').show();
//    });
//    $('.post-comment-btn').live('click', function (e) {
//        var storyId = $(this).parents('.item').attr('id');
//        var comment = $(this).parents('.post-comment').find('textarea').val();
//        var dataString = 'storyId=' + storyId + '&comment=' + comment + '&isApproved=false';

//        var commentFeed = $(this).parents('.comments').find('.comment-feed');

//        $.ajax({
//            type: "POST",
//            url: "/Activity/PostStoryComment",
//            data: dataString,
//            dataType: 'html',
//            error: function (XMLHttpRequest, textStatus, errorThrown) {
//                //validateResult(XMLHttpRequest);
//                alert(XMLHttpRequest.message);
//            },
//            success: function (data, textStatus) {
//                //validateResult(data);
//                //$('#messaging-content').html('message sent');
//                commentFeed.append(data);
//            }
//        });
//    });

getUploadPhotosActionDataJson = function (e) {
    if (e == undefined) e = $('#upload-photos'); else e = $(e);
    return eval('(' + e.find('.action-data').val() + ')');
}
getActionDataJson = function (e) {
    return eval('(' + $(e).parents('.action').find('.action-data').val() + ')');
}
/*
------------------------------ COMMENTS -> BEGIN ------------------------------
*/
showWriteComment = function (id, linkClick) {
    var comments = $("[coid=" + id + "]");
    comments.find('.top').removeClass('hidden');
    comments.find('.post-comment').removeClass('hidden');
    comments.find('.post-comment .hidden:not(.ajax-loading)').removeClass('hidden').addClass('show');
    comments.find('.post-comment dt').show(); // show current user profile photo
    var textarea = comments.find('.post-comment textarea');
    textarea.attr('rows', '2').addClass('dark-text').focus().autogrow();
    if (textarea.val() == 'Write a comment...') textarea.val('');

    $('body').unbind(); // unbind all clicks
    $("body").click(function (e) {
        var target = e.target;
        $('.comments').removeClass('current');
        if (target.tagName == 'TEXTAREA' || linkClick) {
            $("[coid=" + id + "]").addClass('current');
        }
        hideAllWriteComments();
        if (target.tagName != 'TEXTAREA' && target.tagName != 'INPUT' && target.tagName != 'A') {
            //hideAllWriteComments();
        }
    });
}
hideWriteComment = function (id, hideAll) {
    var comments = $("[coid=" + id + "]");
    if (hideAll) comments.find('.post-comment').addClass('hidden');
    comments.find('.post-comment .show').removeClass('show').addClass('hidden');
    comments.find('.post-comment dt').hide();
    comments.find('.post-comment .action').addClass('hidden');
    comments.find('.post-comment textarea').attr('rows', '1').val('Write a comment...').removeClass('dark-text').css('height', '');
}
hideAllWriteComments = function () {
    $('.comments:not(.current)').each(function () {
        var textarea = $(this).find('.post-comment textarea');
        if (textarea.val() == '') { // close only if nothing in the textares
            $(this).find('.post-comment .show').removeClass('show').addClass('hidden');
            $(this).find('.post-comment dt').hide();
            $(this).find('.post-comment .action').addClass('hidden');
            textarea.attr('rows', '1').val('Write a comment...').removeClass('dark-text').css('height', '');
        }
    });
}
showMoreComments = function (e, start, size) {
    var c = $(e).parents('div.comments');
    $(e).parent().removeClass('more').addClass('ajax-loading').html('Loading...');
    var url = String.format("/Comment/GetMoreComments?coid={0}&start={1}&size={2}", c.attr('coid'), start, size);
    ajaxGet(url, 'html', function (data, textStatus) {
        c.find('.ajax-loading').hide();
        c.find('.comment-feed').prepend(data);
    });
}
postComment = function (e) {
    if (isPosting(this)) return false; // are we posting? abort
    startPosting(this); // set posting var

    $(e).addClass('hidden');
    $(e).parent().find('.ajax-loading').removeClass('hidden');
    $(e).parents('dd').find('textarea').attr('disabled', 'disabled');
    var json = getActionDataJson(e);
    var id = $(e).parents('.comments').attr('coid');
    var dataString =
        'id=' + id +
        '&stype=' + json.stype +
        '&ntype=' + json.ntype +
        '&couid=' + json.couid +
        '&comment=' + $.URLEncode($(e).parents('.post-comment').find('textarea').val());
    ajaxPost("/Comment/Post", dataString, 'json',
        function (data, textStatus) { // SUCCESS
            if (data.Success == undefined || !data.Success) {
                infoBoxy('Your comment could not be added', data.Message);
            } else {
                $(e).parents('.comments').find('.comment-feed').append(data.Message).children(':last').effect('highlight').effect('highlight');
                hideWriteComment(id, false);
            }
        },
        function (XMLHttpRequest, textStatus) { // COMPLETE
            //hideWriteComment(id, false);
            $(e).parent().find('.ajax-loading').addClass('hidden');
            $(e).parents('dd').find('textarea').removeAttr('disabled');

            endPosting(this);
        });
}


/*
------------------------------ COMMENTS -> END ------------------------------
*/



/*
------------------------------ ACTIVITY FEED -> BEGIN ------------------------------
*/
whatsGoingOn = function (e) {
    $('#whats-going-on').val('').autogrow().removeWatermark();
    $('#whats-going-on-insert').show();
    $('#whats-going-on-actions').show();
    $('#whats-going-on-container .shoutout .share-action').removeClass('hidden');
}
closeWhatsGoingOn = function (e) {
    $('#whats-going-on').val('').css('height', '').val("Share what you're thinking. Post a picture, video, or other link here.");
    //$('#whats-going-on-insert').hide();
    $('.compose .share-action').addClass('hidden');
    $('#whats-going-on').one('click', function (e) {
        whatsGoingOn(e);
    });
}
postShoutout = function (e) {
    if (isValidURL($('#whats-going-on').val())) {
        shareLink(e);
        $('#link-txt').val($('#whats-going-on').val());
        $('#whats-going-on').val('')
        getLink(e);
        return false;
    }

    if (isPosting(this)) return false; // are we posting? abort
    startPosting(this); // set posting var

    $(e).addClass('hidden');
    $(e).parent().find('.ajax-loading').removeClass('hidden');
    //$(e).attr('disabled', 'disabled');
    //var tuid = $.deparam.querystring($.param.fragment())['uid'];
    var dataString = String.format('text={0}&purl={1}', $.URLEncode($('#whats-going-on').val()), profileUrl);
    ajaxPost('/activity/postshoutout', dataString, 'json',
    function (data, textStatus) { // SUCCESS
        //validateJsonOperationResult(data);
        if (data.Success == undefined || !data.Success) {
            infoBoxy('Cannot share your post', data.Message);
        } else {
            // Hide "empty" feed message if there
            $('#activity-stream .empty-content').hide();
            $(data.Message).hide().prependTo('#activity-stream').effect('highlight').effect('highlight');
            closeWhatsGoingOn();
        }
        $(e).removeClass('hidden');
        $(e).parent().find('.ajax-loading').addClass('hidden');

        endPosting(this);
    });
}
function isValidURL(url) {
    var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
    return RegExp.test(url);
}
getLink = function (e) {
    if (!isValidURL($('#link-txt').val())) {
        alert('Please make sure you have the complete url (example: "http://www.mywebsite.com/post/this")');
        return false;
    }
    else {
        $('#get-link').addClass('hidden');
        var linkTxt = $('#link-txt').val();
        $('#link-info').removeClass('hidden').html('Getting link info. Please wait...').addClass('ajax-loading');

        // is youtube video?
        if (linkTxt.toLowerCase().indexOf('youtube.com') > -1 && linkTxt.toLowerCase().indexOf('watch') > -1) {
            getYoutubeLink(linkTxt);
        } else {
            var dataString = String.format('url={0}', linkTxt);
            ajaxPost('/php/get_link.php', dataString, 'html',
            function (data, textStatus) { // SUCCESS
                $('#link-info').css('padding', '10px').removeClass('ajax-loading').html(data);
                $('#link-info .images img').hide();
                $('#link-info .images img#1').show();
                $('#cur_image').val(1);    
                if (data != 'I am having trouble getting your link. Please try again.') {
                    $('.compose.link .share-action').removeClass('hidden');
                }
            });
        }
    }
}
getYoutubeLink = function (url) {
    var results = url.match("[\\?&]v=([^&#]*)");
    $.jTube({
        request: 'video',
        requestValue: results[1],
        requestOption: 'info',
        limit: 6,
        page: 1,
        success: function (video) {
            var html = '<div class="images"><a target="_blank" href="' + video.link + '"><img id="1" width="100" src="' + video.thumbnail + '"></a></div>';
            html += '<div class="info"><label class="title"><a target="_blank" href="' + video.link + '">' + video.title + '</a></label><input type="hidden" id="link-title" value="' + video.title + '" />';
            html += '<br clear="all" /><label class="url">' + video.link + '</label><input type="hidden" id="link-url" value="' + video.link + '" />';
            html += '<br clear="all" /><br clear="all" /><label class="desc">' + video.description + '</label><input type="hidden" id="link-desc" value="' + video.description + '" />';
            html += '</div>';
            $('#cur_image').val(1);
            $('#link-info').css('padding', '10px').removeClass('ajax-loading').html(html);
            $('.compose.link .share-action').removeClass('hidden');
        },
        error: function (error) {
            $('#link-info').html(error);
        }
    });
}
// next image
getLinkNextImg = function () {
    var imgNum = $('#cur_image').val();
    if (parseInt(imgNum) < parseInt($('#total_images').val())) {
        $('#link-info .images img').hide();
        imgNum = parseInt(imgNum) + parseInt(1);
        $('#cur_image').val(imgNum);
        $('#link-info .images img#' + imgNum).show();
    }
}
// prev image
getLinkPrevImg = function () {
    var imgNum = $('#cur_image').val();
    if (parseInt(imgNum) > 1) {
        $('#link-info .images img').hide();
        imgNum = parseInt(imgNum) - parseInt(1);
        $('#cur_image').val(imgNum);
        $('#link-info .images img#' + imgNum).show();
    }
}
postLink = function (e) {
    if (isPosting(this)) return false; // are we posting? abort
    startPosting(this); // set posting var

    $(e).addClass('hidden');
    $(e).parent().find('.ajax-loading').removeClass('hidden');
    var dataString = String.format('comment={0}&purl={1}&url={2}&title={3}&desc={4}&imgurl={5}',
        $.URLEncode($('#link-comment').val()),
        profileUrl,
        $.URLEncode($('#link-url').val()),
        $.URLEncode($('#link-title').val()),
        $.URLEncode($('#link-desc').val()),
        $.URLEncode($('#link-info .images img#' + $('#cur_image').val()).attr('src')));
    //alert(dataString); return;
    ajaxPost('/activity/postlink', dataString, 'json',
    function (data, textStatus) { // SUCCESS
        if (data.Success == undefined || !data.Success) {
            infoBoxy('Cannot share your link', data.Message);
        } else {
            // Hide "empty" feed message if there
            $('#activity-stream .empty-content').hide();
            $(data.Message).hide().prependTo('#activity-stream').effect('highlight').effect('highlight');
            shareLink(e);
            closeWhatsGoingOn();
        }
        $(e).removeClass('hidden');
        $(e).parent().find('.ajax-loading').addClass('hidden');

        endPosting(this);
    });
}
shareShoutout = function (e) {
    $(e).parents('ul').find('li').removeClass('selected');
    $(e).parent().addClass('selected');
    $('#whats-going-on-container .compose').addClass('hidden');
    $('#whats-going-on-container .shoutout').removeClass('hidden');//.find('.share-action').removeClass('hidden');
}
shareLink = function (e) {
    $(e).parents('ul').find('li').removeClass('selected');
    $(e).parent().addClass('selected');
    $('#whats-going-on-container .compose').addClass('hidden');
    $('#whats-going-on-container .link').removeClass('hidden'); //.find('.share-action').removeClass('hidden');
    $('#link-txt').val('').watermark('watermark', "http://");
    $('#get-link').removeClass('hidden');
    $('#link-info').addClass('hidden').css('padding','');
    $('.compose.link .share-action').addClass('hidden');
}
sharePhoto = function (e) {
    $(e).parents('ul').find('li').removeClass('selected');
    $(e).parent().addClass('selected');
    $('#whats-going-on-container .compose').addClass('hidden');
    $('#whats-going-on-container .photo').removeClass('hidden');
}
viewMoreStories = function (type) {
    $('#activity-view-older').removeClass('down-mini-arrow').removeClass('clear-box').addClass('ajax-loading').html('Loading older posts...');
    var otd = $('#activity-stream .item.last .oldest-datetime').val();
    //var uid = $.deparam.querystring($.param.fragment())['uid'];
    ajaxGet(String.format("/{0}/Stories?otd={1}&profileUrl={2}", type == undefined ? 'Activity' : type, otd, profileUrl), 'html', function (data, textStatus) {
        $('#activity-stream .item.last').removeClass('last');
        $('#activity-view-older').remove();
        $('#activity-stream').append(data);
    });
}
/*
------------------------------ ACTIVITY FEED -> END ------------------------------
*/

viewMoreBlogs = function (type, uid) {
    $('#blogs-view-older').removeClass('down-mini-arrow').removeClass('clear-box').addClass('ajax-loading').html('Loading older blogs...');
    var otd = $('#blogs .blog.last .oldest-datetime').val();
    ajaxGet(String.format("/Blogs/Get{0}Blogs?otd={1}&uid={2}", type == undefined ? 'Friend' : type, otd, uid), 'html', function (data, textStatus) {
        $('#blogs .blog.last').removeClass('last');
        $('#blogs-view-older').remove();
        $('#blogs').append(data);
    });
}

showMoreFriends = function (e, pid, start, size) {
    var parent = $(e).parent();
    parent.removeClass('clear-box').addClass('ajax-loading').html('Loading more friends...');
    var url = String.format("/Friends/GetMoreFriends?pid={0}&start={1}&size={2}", pid, start, size);
    ajaxGet(url, 'html', function (data, textStatus) {
        parent.addClass('clear-box').removeClass('ajax-loading').html('');
        $('#friend-list').append(data);
    });
}
showMoreMutualFriends = function (e, uid1, uid2, start, size) {
    var parent = $(e).parent();
    parent.removeClass('clear-box').addClass('ajax-loading').html('Loading more friends...');
    var url = String.format("/Friends/GetMoreMutualFriends?uid1={0}&uid2={1}&start={2}&size={3}", uid1, uid2, start, size);
    ajaxGet(url, 'html', function (data, textStatus) {
        parent.addClass('clear-box').removeClass('ajax-loading').html('');
        $('#mutual-friend-list').append(data);
        //parent.remove();
    });
}
showMorePhotos = function (e, aid, pid, start, size) {
    var parent = e == undefined ? $('#show-more-photos') : $(e).parent();
    parent.removeClass('clear-box').addClass('ajax-loading').html('Loading more photos...');
    var url = String.format("/Photos/GetMorePhotos?aid={0}&start={1}&size={2}&pid={3}", aid, start, size, pid);
    ajaxGet(url, 'html', function (data, textStatus) {
        parent.remove();
        $('#photos.view-photos').append(data);
        $(window).unbind('scroll');
    });
}
showMoreAllPhotos = function (e, pid, start, size) {
    var parent = e == undefined ? $('#show-more-photos') : $(e).parent();
    parent.removeClass('clear-box').addClass('ajax-loading').html('Loading more photos...');
    var url = String.format("/Photos/GetMoreAllPhotos?start={0}&size={1}&pid={2}", start, size, pid);
    ajaxGet(url, 'html', function (data, textStatus) {
        parent.remove();
        $('#photos.view-photos').append(data);
        //$(window).unbind('scroll');
    });
}

likeThis = function (e, id, stype, ntype, ouid) {
    $(e).addClass('ajax-loading2').html('');
    //var json = getActionDataJson(e);
    //var id = $(e).parents('.comments').attr('id').substring(6);
    var comments = $("[coid=" + id + "]");
    var dataString = String.format('id={0}&stype={1}&ntype={2}&ouid={3}', id, stype, ntype, ouid);
    ajaxPost("/Activity/Like", dataString, 'json',
        function (data, textStatus) { // SUCCESS
            if (data.Success == undefined || !data.Success) {
                infoBoxy('Your like could not be added', data.Message);
            } else {
                comments.find('.likesbar').html(data.Html);
                comments.find('.top').removeClass('hidden');
                comments.find('.post-comment').removeClass('hidden'); //$(e).parents('.comments').find('.comment-feed').append(data.Message).children(':last').hide().slideDown();
            }
        },
        function (XMLHttpRequest, textStatus) { // COMPLETE
            hideWriteComment(id, false);
            $(e).parent().find('.unlike').removeClass('hidden').removeClass('ajax-loading2').html('Unlike');
            $(e).addClass('hidden');
        });
}
unlikeThis = function (e, id, stype, ntype) {
    $(e).addClass('ajax-loading2').html('');
    //var json = getActionDataJson(e);
    //var id = $(e).parents('.comments').attr('id').substring(6);
    var comments = $("[coid=" + id + "]");
    var dataString = String.format('id={0}&stype={1}&ntype={2}', id, stype, ntype);                // story on item id
    ajaxPost("/Activity/Unlike", dataString, 'json',
    function (data, textStatus) { // SUCCESS
        if (data.Success == undefined || !data.Success) {
            infoBoxy('Your unlike could not be added', data.Message);
        } else {
            comments.find('.likesbar').html(data.Html);
            comments.find('.top').removeClass('hidden');
            comments.find('.post-comment').removeClass('hidden'); //$(e).parents('.comments').find('.comment-feed').append(data.Message).children(':last').hide().slideDown();
        }
    },
    function (XMLHttpRequest, textStatus) { // COMPLETE
        //hideWriteComment(id, false);
        $(e).parent().find('.like').removeClass('hidden').removeClass('ajax-loading2').html('Like');
        $(e).addClass('hidden');
    });
}

// Compose Message
composeMessage = function (puid, pname, threadid) {
    if (puid == undefined) {
        getComposeMessageBoxy(puid, pname, threadid);
    } else {
        var dataString = String.format('uid={0}', puid);
        ajaxPost("/Privacy/CheckSendMessagePrivacy", dataString, 'json',
        function (data, textStatus) { // SUCCESS
            if (data.privacy == 0) {
                getComposeMessageBoxy(puid, pname, threadid);
            } else {
                errorBoxy('Privacy Alert', String.format('{0} only accepts messages from friends{1}', pname, data.privacy == 2 ? ' and friend of friends' : ''));
            }
        });
    }
}
getComposeMessageBoxy = function (puid, pname, threadid) {
    getBoxy('/Messages/Compose', '', function (data) {
        if (puid != undefined && pname != undefined) $('#Recipients').html(String.format("<option class='selected locked' value='{0}'>{1}</option>", puid, pname));

        if (threadid != undefined) { // Branch message reply
            $('#threadid').val(threadid);
            $('#compose-message-form td.text.branch').html(String.format("<input type='hidden' name='subject' id='Subject' value='{0}'>", $('#content-title').text()) + $('#content-title').text());
            $('#compose-message-form td.desc.branch').html('Reply:');
            $('#compose-message-form a.btn.branch').html('Reply');
            $('#compose-message-form #body').focus();
        } else { $('#compose-message-form #subject').focus(); }

        $("#Recipients").fcbkcomplete({
            json_url: "/Friends/GetFriendListAutoComplete",
            cache: false,           // use cache
            filter_case: false,     // case sensitive filter
            filter_hide: true,      // show/hide filtered items
            firstselected: true,    // automatically select first element from dropdown
            //onremove: "testme",   // fire event on item remove
            //onselect: "testme",   // fire event on item selected
            //height: 100,          // max num of element shown before scroll will appear
            filter_selected: true,  // filter selected items from list
            maxitems: 10,           // max item that can be added to the list
            newel: false            // show typed text like a element
        });
        $('#Body').autogrow();
    });
}
composeUpdateMessage = function () {
    getBoxy('/Messages/ComposeUpdateMessage', '', function (data) {
        $('#Subject').focus();
        $('#Body').autogrow();
    });
}

// Error Boxy
errorBoxy = function (title, mssg) {
    infoBoxy(title, mssg, null, true);
}
// Informational Boxy
infoBoxy = function (title, mssg, timeout, isError, completed) {
    closeAllBoxy();
    //var dataString = String.format('mssg={0}&title={1}&isError={2}', $.URLEncode(mssg), $.URLEncode(title), isError == undefined ? false : isError);
    getBoxy(String.format('/UIHelper/InfoBoxy?mssg={0}&title={1}&isError={2}', $.URLEncode(mssg), $.URLEncode(title), isError == undefined ? false : isError), '', function (data) {
        var boxy = $('.info-boxy');
        if (boxy.length > 0) {
            if (isError) boxy.parents('.boxy-wrapper').addClass('error'); // error boxy
            boxy.parents('.boxy-wrapper').effect('bounce');
            if (timeout != undefined) {
                window.setTimeout(function () {
                    closeBoxy('.info-boxy'); // wait, x time and close the info boxy
                    // Callback
                    if (typeof completed == 'function') completed();
                }, timeout);
            } else {
                // Callback
                if (typeof completed == 'function') completed();
            }
        }
    });
}

// Send Message
sendMessage = function (e) {
    var dataString = 'Recipients=' + $('#Recipients').val() + '&Subject=' + $.URLEncode($('#Subject').val()) + '&Body=' + $.URLEncode($('#Body').val()) + '&threadid=' + $('#threadid').val();
    ajaxPost('/Messages/Compose', dataString, 'json', function (data, textStatus) {
        closeAllErrorPrompts();
        validateJsonOperationResult(data);
        if (data.Success) {
            closeAllErrorPrompts();
            closeBoxy(e, function () {
                infoBoxy('Message sent successfully', data.Message, 2000);
            });
        }
    });
}
// Send Update Message
sendUpdateMessage = function (e) {
    var dataString = 'Subject=' + $.URLEncode($('#Subject').val()) + '&Body=' + $.URLEncode($('#Body').val());
    ajaxPost('/Messages/SendUpdateMessage', dataString, 'json', function (data, textStatus) {
        closeAllErrorPrompts();
        validateJsonOperationResult(data);
        if (data.Success) {
            closeAllErrorPrompts();
            closeBoxy(e, function () {
                infoBoxy('Message sent successfully', data.Message, 2000, false, function () {
                    window.location.reload(true);
                });
            });
        }
    });
}

// Change Location
changeLocation = function (type, lcode) {
    getBoxy(String.format('/Localization/ChangeLocation?lcode={0}&type={1}', lcode, type), '', function (data) {
        $('#change-loc-tb').watermark('watermark', "Start typing new location postal code here (ie. 92694)");

        function monkeyPatchAutocomplete() {

            // Don't really need to save the old fn, 
            // but I could chain if I wanted to
            var oldFn = $.ui.autocomplete.prototype._renderItem;

            $.ui.autocomplete.prototype._renderItem = function (ul, item) {
                var re = new RegExp("^" + this.term, "i");
                var t = item.label.replace(re, "<span style='font-weight:bold;color:Blue;'>" + this.term + "</span>");
                return $("<li></li>")
                  .data("item.autocomplete", item)
                  .append(String.format('<a>{0}, {1} ({2})<br>{3}</a>', item.city, item.spcode, t, item.cname))
                  .appendTo(ul);
            };
        }

        monkeyPatchAutocomplete();

        $("#change-loc-tb").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '/Localization/GetLocationListAutoComplete?term=' + request.term,
                    dataType: "json",
                    success: function (data) {
                        response(data);
                    }
                });
            },
            minLength: 2,
            select: function (event, ui) {
                //alert('selected:' + ui.item.code);
                $('#change-loc-tb').addClass('hidden');
                $('#new-location').removeClass('hidden');
                $('#new-location-info').html(String.format('<a>{0}, {1} ({2})<br>{3} <small>▼</small></a>', ui.item.city, ui.item.spcode, ui.item.value, ui.item.cname));
                $('#new-location-city-state').val(String.format('<a>{0}, {1} <small>▼</small></a>', ui.item.city, ui.item.spcode));
                $('#change-btn').focus();
                $('#nlcode').val(ui.item.code);
                $('#new-location').effect('highlight');
                //log(ui.item ? ("Selected: " + ui.item.value + " aka " + ui.item.id) : "Nothing selected, input was " + this.value);
            },
            open: function (event, ui) {
                //alert('opened');
            }
        });

    });
}
setLocation = function (e, type) {
    if ($('#nlcode').val().length > 0) {
        switch (type) {
            case "browse":
                break;
            default:
                break;
        }
        $('#LocationCode').val($('#nlcode').val());
        $('#location-info').html($('#new-location-city-state').val());
        closeBoxy(e);
    }
}
reenterLocation = function (e) {
    $('#nlcode').val('');
    $('#change-loc-tb').val('').removeClass('hidden').watermark('watermark', "Start typing new location postal code here (ie. 92694)");
    $('#new-location').addClass('hidden');
    $('#new-location-info').html('');
}
// Suggest Friends
suggestFriends = function (e) {
    var json = getActionDataJson(e);
    getBoxy(String.format('/Friends/SuggestFriends?userid={0}', json.uid), '', function (data) {
        $.fcbkListSelection("#fcbklist", "695", "50", "3");
    });
}
sendFriendSuggestions = function (e) {
    var groupName = $('#groupname').val();
    groupName = groupName == 'Enter a Group Name' ? '' : groupName;
    var dataString = 'touserid=' + $('#touserid').val() + '&suggesteduserids=' + $('#fcbklist_values').val();
    ajaxPost('/Friends/SuggestFriends', dataString, 'json', function (data, textStatus) {
        closeBoxy('#suggest-friends-form', function () {
            infoBoxy('Friend Suggestions sent successfully', 'Your Friend Suggestions have been sent successfully.', 2000);
        });
    });
}
excludeYouMayKnow = function (e) {
    $(e).parents('.profile').fadeTo('fast', 0.1, function () {
        getNewYouMayKnow($(e).parents('.profile'), getPeopleYouMayKnowIds());
    });
}
getPeopleYouMayKnowIds = function () {
    var selectedIds = [];
    var index = -1;
    $('#people-u-may-know').find(".content .profile").each(function () {
        index++;
        selectedIds[index] = $(this).attr('id');
    });
    return selectedIds.join();
}
getNewYouMayKnow = function (e, excludeIds) {
    var dataString = String.format('excludingUserId={1}&excludeuserids={0}', excludeIds, e.attr('id'))
    ajaxPost('/find/ExcludeYouMayKnow', dataString, 'json', function (data, textStatus) {
        if (data != undefined && data.Success) {
            $(e).replaceWith(data.Html);
        } else {
            Boxy.alert(data.Message);
        }
    });
}
setNotifyType = function (e) {
    var isEmail = $(e).is(':checked');
    $(e).parents('tr').find("td input[type='hidden']").val(isEmail ? '1' : '0');
}
updateNotificationSettings = function (e, email, ac) {
    if (isPosting(this)) return false; // are we posting? abort
    startPosting(this); // set posting var

    var dataString = $(e).parents('#notification-settings-form').serialize();
    if (email != undefined && ac != undefined) dataString += '&email=' + $.URLEncode(email) + '&ac=' + $.URLEncode(ac);
    ajaxPost('/Account/NotificationSettings', dataString, 'json', function (data, textStatus) {
        validateJsonOperationResult(data);
        scrollTop();
        if (data.Success) {
            closeAllErrorPrompts();
        }

        endPosting(this);
    });
}
showMorePeopleYouMayKnow = function (e, getNum) {
    ajaxGet(String.format("/Find/GetPeopleYouMayKnow?getnum={0}&excludeuserids={1}", getNum, getPeopleYouMayKnowIds()), 'html', function (data, textStatus) {
        $('#people-u-may-know .content').append(data);
        $('#show-more-people-u-may-know').hide();
        $(e).parents('.content-block').find('.content').removeClass('no-btm');
    });
}
// Add to Friends
friendRequest = function (e, isSuggestion) {
    if (isSuggestion != undefined) suggestion = $(e).parents('.suggestion');
    var json = getActionDataJson(e);
    var dataString = String.format('uid={0}', json.uid);
    ajaxPost("/Privacy/CheckAddMeAsFriendPrivacy", dataString, 'json',
        function (data, textStatus) { // SUCCESS
            if (data.privacy == 0) {
                dataString = String.format('userid={0}', json.uid);
                closeAllBoxy();
                createBoxy({ closeable: false, draggable: false });
                ajaxPost('/Friends/FriendRequest', dataString, 'json',
                function (data, textStatus) { // SUCCESS
                    boxyDialog.setContent(data.html);
                    boxyDialog.centerAt($(window).width() / 2, 300); // recenter boxy after content has been loaded
                });
            } else {
                infoBoxy('Privacy Alert', 'This user only accepts friend requests from friends of friends', 2000);
            }
        });

}
sendFriendRequest = function (id) {
    var dataString = String.format('userId={0}&message={1}', id, $('#message').val())
    ajaxPost('/Friends/SendRequest', dataString, 'json',
    function (data, textStatus) { // SUCCESS
        if (data.Success) {
            closeBoxy('#friend-request-form', function () {
                if (suggestion == undefined) {
                    infoBoxy('Friend Request sent successfully', data.Message, 2000); // show info boxy
                }
            }); // close the friend request boxy
        } else {
            errorBoxy('Your Friend Request could not be sent', data.Message);
        }
    }, function (data, textStatus) { // COMPLETE
        if (suggestion != undefined) {
            suggestion.find('.action .pending').addClass('hidden');
            suggestion.find('.requested.hidden').removeClass('hidden');
            suggestion.css('background-color', '#edfff2').effect('highlight');
            checkAlerts();
        }
    });
}
albumPrivacy = function (id) {
    getBoxy('/PhotoAlbum/AlbumPrivacy', '', function (data) {
        
    });
}
updateAlbumPrivacy = function (e) {
    changePrivacyLevel(e);
    var dataString = String.format('aid={0}&level={1}', $(e).attr("name"), $(e).val());
    ajaxPost('/PhotoAlbum/UpdateAlbumPrivacy', dataString, 'json', function (data, textStatus) {
        if (data.Success) {
            //infoBoxy('Album Privacy has been updated', data.Message, 2000); // show info boxy
        }
    });
}
toggleBtnToolbar = function (isOn) {
    if (!isOn) $('.btn-toolbar button').addClass('disabled').attr('disabled', 'disabled'); 
    else $('.btn-toolbar button').removeClass('disabled').attr('disabled', '');
}
changePrivacyLevel = function (e) {
    var parent = $(e).parent();
    if ($(e).val() == '0') {
        parent.removeClass('privacy-on').addClass('privacy-off');
    } else {
        parent.removeClass('privacy-off').addClass('privacy-on');
    }
}
editAlbum = function (aid) {
    getBoxy(String.format('/PhotoAlbum/Edit?aid={0}', aid), '', null, function (XMLHttpRequest, textStatus) {
        $('#albumname').focus();
        $('#AlbumDescription').autogrow();
        $('#AlbumLocation').watermark('watermark', "Where did you take these photos?");
    });
}
updateAlbum = function (e) {
    $('#AlbumLocation').removeWatermark();
    var dataString = $('#album-data-form').serialize();
    ajaxPost('/PhotoAlbum/Edit', dataString, 'json', function (data, textStatus) {
        validateJsonOperationResult(data);
        if (data.Success) {
            closeBoxy(e, function () {
                infoBoxy('Album has been updated successfully', data.Message, 2000, false, function () {
                    window.location.reload(true);
                }); // show info boxy
            });
        }
    });
}
uploadPhotos = function (e) {
    getBoxy('/PhotoAlbum/Create', '', null, function (XMLHttpRequest, textStatus) {
        $('#albumname').focus();
        $('#albumdescription').autogrow();
        $('#albumlocation').watermark('watermark', "Where did you take these photos?");
    });
}
moreAlbumData = function (e) {
    $('#album-data-form table .show-more').hide();
    $('#album-data-form table .more').show();
    $('#albumdescription').autogrow();
}
uploadDisablePage = function () {
    // Disable links
    $('#doc3 a').click(function (e) {
        disableAction(e);
    });
    // Disable buttons
    $('#doc3 button').each(function () {
        $(this).addClass('disabled');
        $(this).attr('disabled', 'disabled');
    });
}
uploadEnablePage = function () {
    // Enable links
    $('#doc3 a').unbind('click');
    // Enable buttons
    $('#doc3 button').each(function () {
        $(this).removeClass('disabled');
        $(this).removeAttr('disabled');
    });
}
uploadPhotosTo = function (aid, isNew, adding) {
    ajaxGet('/Photos/PhotoUploadCookieExists', 'json', function (data, textStatus) {
        if (!data.result) {
            getBoxy(String.format('/Photos/UploadPhotos?aid={0}&isNew={1}', aid, isNew), '', null, function (XMLHttpRequest, textStatus) {
                uploadDisablePage();
                // Uploader Events
                var uploader = document.getElementById("photouploader");
                if (uploader != undefined) {
                    uploader.handleselect = function () {
                        setAlbumId(aid, function (XMLHttpRequest, textStatus) { // Set the uploading album id, then start upload
                            // First let's hide tips, select photos button etc...
                            $('#upload-photos .upload-select').hide();
                            $('#uploader').css('height', '200px');
                            $('#uploader').css('overflow', 'auto');
                            $('#upload-photos .action a').hide();
                            if (adding == undefined || !adding) {
                                // if don't adding photos to album reset last uploaded
                                ajaxGet('/Photos/ResetIsLastUpload', 'json', function (data, textStatus) {
                                    startUpload("photouploader");
                                    $('#uploading').removeClass('hidden');
                                });
                            } else {
                                startUpload("photouploader");
                                $('#uploading').removeClass('hidden');
                            }
                        });
                    }
                    uploader.handlepostback = function () {
                        photoUploadCompleted("photouploader");
                    }
                }
            });
        } else {
            getBoxy(String.format('/Photos/DeletePhotoUploadCookie?aid={0}&isNew={1}', aid, isNew));
        }
    });
}
closeUploadPhotosTo = function (e) {
    closeBoxy(e, function () {
        uploadEnablePage();
    });
}
deletePhotoUploadCookie = function (e, aid, isNew) {
    //var dataString = String.format('aid={0}&isNew={1}', aid, isNew);
    ajaxPost('/Photos/DeletePhotoUploadCookie', null, 'json', function (data, textStatus) {
        if (e != undefined) {
            closeBoxy(e, function () {
                uploadPhotosTo(aid, isNew);
            });
        }
    });
}
getProfilePhoto = function (page) {
    ajaxGet(String.format('/EditProfile/GetProfilePhoto?page={0}', page), 'html', function (data, textStatus) {
        $('#uploaded-profile-photo').html(data);
    });
}
getProfilePhotoThumb = function (complete) {
    ajaxGet('/EditProfile/GetProfilePhotoThumb', 'html', function (data, textStatus) {
        $('#profile-photo-thumb').replaceWith(data);
    }, complete);
}
confirmRemoveProfilePhoto = function (e) {
    getBoxy('/EditProfile/ConfirmRemoveProfilePhoto', '');
}
removeProfilePhoto = function (e) {
    closeBoxy(e, function () {
        ajaxGet('/EditProfile/RemoveProfilePhoto', 'html', function (data, textStatus) {
            getProfilePhoto();
            getProfilePhotoThumb();
            // If BrowsePhotos page
            $('#remove-pphoto').hide();
            $('#delete-photo').show();
            $('#make-pphoto').show();
        });
    });
}
makeProfilePhoto = function (pid) {
    var dataString = String.format('pid={0}', pid);
    ajaxPost('/Photos/MakeProfilePhoto', dataString, 'html', function (data, textStatus) {
        getProfilePhoto();
        getProfilePhotoThumb();
        // If BrowsePhotos page
        $('#remove-pphoto').show();
        $('#delete-photo').hide();
        $('#make-pphoto').hide();
    });
}
addToFeaturedProfiles = function (e) {
    var json = getActionDataJson(e);
    var dataString = String.format('uid={0}', json.uid);
    ajaxPost('/featured/addprofile', dataString, 'html', function (data, textStatus) {
        $(e).addClass('hidden');
        $(e).parent().find('.remove-featured').removeClass('hidden');
    });
}
removeFromFeaturedProfiles = function (e) {
    var json = getActionDataJson(e);
    var dataString = String.format('uid={0}', json.uid);
    ajaxPost('/featured/removeprofile', dataString, 'html', function (data, textStatus) {
        $(e).addClass('hidden');
        $(e).parent().find('.add-featured').removeClass('hidden');
    });
}
enableAdminView = function (e) {
    var json = getActionDataJson(e);
    var dataString = String.format('uid={0}', json.uid);
    ajaxPost('/admin/enableadminview', dataString, 'html', function (data, textStatus) {
        window.location.reload(true);
    });
}
disableAdminView = function (e) {
    var json = getActionDataJson(e);
    var dataString = String.format('uid={0}', json.uid);
    ajaxPost('/admin/disableadminview', dataString, 'html', function (data, textStatus) {
        if ($.param.fragment().length > 0) window.location = '/' + profileUrl; else window.location.reload(true);
    });
}
adminSearchMember = function (e) {
    var dataString = String.format('email={0}', $('#search-member').val());
    ajaxPost('/membership/searchmember', dataString, 'html', function (data, textStatus) {
        $('#members').replaceWith(data);
    });
}
adminDeleteAccount = function (e, uid) {
    var json = getActionDataJson(e);
    var rid = json.rid == undefined ? uid : json.rid;
    var r = json.r == undefined ? -1 : json.r;
    getBoxy(String.format('/admin/deleteaccount?rid={0}&r={1}', rid, r), '');
}
adminDisapproveAccount = function (e, uid) {
    var json = getActionDataJson(e);
    uid = uid == undefined ? json.uid : uid;
    var dataString = String.format('uid={0}', uid);
    ajaxPost('/membership/disapproveaccount', dataString, 'json', function (data, textStatus) {
        if (json.uid == undefined) {
            $(e).parents('tr').addClass('disapproved');
            $(e).parents('td').find('.approve').removeClass('hidden');
            $(e).addClass('hidden');
        } else {
            $(e).parent().addClass('disapproved').find('.approve').removeClass('hidden');
            $(e).addClass('hidden');
        }
    });
}
adminApproveAccount = function (e, uid) {
    var json = getActionDataJson(e);
    uid = uid == undefined ? json.uid : uid;
    var dataString = String.format('uid={0}', uid);
    ajaxPost('/membership/approveaccount', dataString, 'json', function (data, textStatus) {
        if (json.uid == undefined) {
            $(e).parents('tr').removeClass('disapproved');
            $(e).parents('td').find('.disapprove').removeClass('hidden');
            $(e).addClass('hidden');
        } else {
            $(e).parent().removeClass('disapproved').find('.disapprove').removeClass('hidden');
            $(e).addClass('hidden');
        }
    });
}
adminUnlockAccount = function (e, uid) {
    var dataString = String.format('uid={0}', uid);
    ajaxPost('/membership/unlockaccount', dataString, 'json', function (data, textStatus) {
        $(e).parent().remove();
    });
}
doAdminDeleteAccount = function (e) {
    var json = getActionDataJson(e);
    if ($.deparam.querystring($('#delete-account-form').serialize())['reason'] == undefined) {
        $.validationEngine.buildPrompt("#reasons", 'Please select a reason', "error");
        return;
    }
    closeAllErrorPrompts();
    $('#delete-account-form .deleting').addClass('hidden');
    $('#delete-account-form #uploading').removeClass('hidden');
    var dataString = String.format('{0}&uid={1}', $('#delete-account-form').serialize(), json.uid);
    ajaxPost('/admin/deleteaccount', dataString, 'json', function (data, textStatus) {
        closeBoxy(e);
        if (json.r == -1) goBack(); else $('#reported tr.' + json.uid).slideUp('fast');
    });
}
adminDeletePhoto = function (e, pid) {
    var json = getActionDataJson(e);
    var rid = pid == undefined ? json.rid : pid;
    var r = json.r == undefined ? -1 : json.r;
    getBoxy(String.format('/admin/deletephoto?pid={0}&r={1}', rid, r), '');
}
doAdminDeletePhoto = function (e, reason, comment) {
    var json = getActionDataJson(e);
    if ($.deparam.querystring($('#delete-photo-form').serialize())['reason'] == undefined) {
        $.validationEngine.buildPrompt("#reasons", 'Please select a reason', "error");
        return;
    }
    closeAllErrorPrompts();
    $('#delete-photo-form .deleting').addClass('hidden');
    $('#delete-photo-form #uploading').removeClass('hidden');
    var dataString = String.format('{0}&pid={1}', $('#delete-photo-form').serialize(), json.pid);
    ajaxPost('/admin/deletephoto', dataString, 'json', function (data, textStatus) {
        closeBoxy(e);
        if ($('#reported').length == 0) goBack(); else $('#reported tr.' + json.pid).slideUp('fast');
    });
}
adminRejectReport = function (e) {
    var json = getActionDataJson(e);
    var dataString = String.format('rid={0}', json.rid);
    ajaxPost('/admin/rejectreport', dataString, 'json', function (data, textStatus) {
        closeAllErrorPrompts();
        closeBoxy(e);
        $('#reported tr.' + json.rid).slideUp('fast');
    });
}
// Report member
reportMember = function (e) {
    var json = getActionDataJson(e);
    getBoxy(String.format('/account/reportmember?ruid={0}', json.uid), '');
}
sendProfileReportAndBlock = function (e, form, isFriend) {
    var json = getActionDataJson(e);
    var reason = $.deparam.querystring(form)['reason'];
    if (reason == undefined) {
        $.validationEngine.buildPrompt("#reasons", 'Please select a reason', "error");
        return;
    }
    var comment = $.deparam.querystring(form)['comment'];
    var block = $.deparam.querystring(form)['block'];
    if (block != undefined) {
        blockMember(e);
        if (isFriend) {
            deleteFriend(json.fid);
        }
    }

    // Now report and close boxy
    sendProfileReport(e, reason, comment);
    closeAllErrorPrompts();
    closeBoxy(e);

    infoBoxy('Report Successfully Submitted', 'We have received your report and will handle it right away. Thank you.', 2000, false, function () {
        if (profileUrl != undefined && isFriend) {
            window.location.reload(true);
        }
    });
}
// Report photo
reportPhoto = function (pid) {
    getBoxy(String.format('/account/reportphoto?rid={0}', pid), '');
}
sendPhotoReport = function (e, form) {
    var json = getActionDataJson(e);
    var reason = $.deparam.querystring(form)['reason'];
    if (reason == undefined) {
        $.validationEngine.buildPrompt("#reasons", 'Please select a reason', "error");
        return;
    }
    var comment = $.deparam.querystring(form)['comment'];

    // Now report and close boxy
    var dataString = String.format('rid={0}&r={1}&c={2}', json.pid, reason, comment);
    ajaxPost('/account/reportphoto', dataString, 'json', function (data, textStatus) {
        closeAllErrorPrompts();
        closeBoxy(e);
        infoBoxy('Report Successfully Submitted', 'We have received your report and will handle it right away. Thank you.', 2000);
    });
}
// Report threadpost
reportThreadPost = function (pid) {
    getBoxy(String.format('/account/reportthreadpost?rid={0}', pid), '');
}
sendThreadPostReport = function (e, form) {
    var json = getActionDataJson(e);
    var reason = $.deparam.querystring(form)['reason'];
    if (reason == undefined) {
        $.validationEngine.buildPrompt("#reasons", 'Please select a reason', "error");
        return;
    }
    var comment = $.deparam.querystring(form)['comment'];

    // Now report and close boxy
    var dataString = String.format('rid={0}&r={1}&c={2}', json.tpid, reason, comment);
    ajaxPost('/account/reportthreadpost', dataString, 'json', function (data, textStatus) {
        closeAllErrorPrompts();
        closeBoxy(e);
        infoBoxy('Report Successfully Submitted', 'We have received your report and will handle it right away. Thank you.', 2000);
    });
}
// Block/Unblock members
blockMember = function (e) {
    var json = getActionDataJson(e);
    var dataString = String.format('buid={0}', json.uid);
    ajaxPost('/account/blockmember', dataString, 'json', function (data, textStatus) {
        $(String.format('#block_{0}', json.uid)).addClass('hidden');
        $(String.format('#unblock_{0}', json.uid)).removeClass('hidden');
    });
}
unblockMember = function (e) {
    var json = getActionDataJson(e);
    var dataString = String.format('buid={0}', json.uid);
    ajaxPost('/account/unblockmember', dataString, 'json', function (data, textStatus) {
        $(e).addClass('hidden');
        $(String.format('#block_{0}', json.uid)).removeClass('hidden');
        infoBoxy('Member Unblocked', 'You have unblocked this member.', 2000);
    });
}
sendProfileReport = function (e, r, c) {
    var json = getActionDataJson(e);
    var dataString = String.format('rid={0}&r={1}&c={2}', json.uid, r, c);
    ajaxPost('/account/reportprofile', dataString, 'json');
}
// Upload Photos
//uploadPhotos = function (aid) {
//    var url = '/Photos/Upload';
//    if (aid != undefined) url = String.format("{0}?aid={1}", url, aid);
//    getBoxy(url, '', null, function (XMLHttpRequest, textStatus) {
//        // Uploader Events
//        var uploader = document.getElementById("photouploader");
//        uploader.handleselect = function () {
//            if ($('[name="upload-to"]:checked').val() == undefined) {
//                alert('you must select upload to');
//                return false;
//            }
//            ajaxGet('/Photos/PreUploadStatus', 'json', function (data, textStatus) {
//                if (data.ready) {
//                    // Hide upload selection related items
//                    $('#upload-photos-content .upload-select').hide();
//                    switch ($('[name="upload-to"]:checked').val()) {
//                        case "existing":
//                            alert('uploading to existing: ' + $('#existing-album').val());
//                            setAlbumId($('#existing-album').val());
//                            break;
//                        default:
//                            createAlbum(uploader);
//                            break;
//                    }
//                } else {
//                    infoBoxy("Cannot Upload Photos", "Your computer setup is not allowing for uploading photos. Please make sure you enable cookies in your browser.");
//                    return;
//                }
//            });

//        }
//        uploader.handlebrowse = function () {
//            if ($('#name').val().length < 1 && $('#create-new').is(':checked')) {
//                infoBoxy("Could not create your photo album", "Please enter your album name. Upload will start immidiately after you confirm your photo selection.");
//                return false;
//            }
//        }
//    });
//}
makeAlbumCover = function (e, pid) {
    if (pid == undefined) {
        // Clear existing album cover
        $('.photo-cover-enabled .photo-container .cover').addClass('hidden');
        $('.photo-cover-enabled .photo-container').removeClass('cover');
        $('.photo-cover-enabled .action').removeClass('hidden');

        var photoElem = $(e).parents('div[pid]');
        if (photoElem.length < 1) photoElem = $(e).parents('li');
        photoElem.find('.photo-container .cover').removeClass('hidden');
        photoElem.find('.photo-container').addClass('cover');

        var pid = $(e).parents('div[pid]').attr('pid');
        if (pid == undefined) {
            pid = $(e).parents('li').attr('id');
            $('#modified').val('true');
        } else {
            markPhotoModified(e);
            $(e).parents('div[pid]').find('.action').addClass('hidden');
        }
        $('#cpid').val(pid);
    } else {
        $('#browse-photo-cover-info').removeClass('hidden');
        $('#make-album-cover').hide();
        $('#delete-photo').hide();

        setAlbumCover(e, pid);
    }
}
setAlbumCover = function (e, pid) {
    var dataString;
    // when browsing photo pid is sent to make cover photo
    if (pid == undefined) {
        dataString = String.format('pid={0}', $('#cpid').val());
    } else {
        dataString = String.format('pid={0}', pid);
    }
    ajaxPost('/PhotoAlbum/SetAlbumCover', dataString);
}
deletePhoto = function (pid, aid, nextPid, prevPid) {
    var dataString = String.format('ids={0}&aid={1}', pid, aid);
    ajaxPost('/Photos/DeletePhotos', dataString, 'json', function (data, textStatus) {
        if (nextPid != undefined || prevPid != undefined) {
            // after photo is deleted when browsing we are going to move to the next one first then to the prev if next one doesn't exist
            if (nextPid != undefined) pid = nextPid; else pid = prevPid;
            window.location = String.format('#browsephotos?pid={0}&aid={1}', pid, aid);
        }
    });
}
addFeaturedPhotos = function (e, ids) {
    var dataString = String.format('ids={0}', ids);
    ajaxPost('/Photos/AddFeaturedPhotos', dataString, 'json', function (data, textStatus) {
        $(e).addClass('hidden');
        $('#featured-photo-info').removeClass('hidden');
    });
}
removeFeaturedPhotos = function (e, ids) {
    var dataString = String.format('ids={0}', ids);
    ajaxPost('/Photos/RemoveFeaturedPhotos', dataString, 'json', function (data, textStatus) {
        $('#featured-photo-info').addClass('hidden');
        $('#feature-photo').removeClass('hidden');
        $(e).parents('li.featured-photo').hide();
    });
}
// Confirm Delete Album
confirmDeleteAlbum = function (aid) {
    getBoxy(String.format('/PhotoAlbum/ConfirmAlbumDelete?aid={0}', aid), '', null);
}
deleteAlbum = function (e, aid) {
    var dataString = String.format('ids={0}', aid);
    ajaxPost('/PhotoAlbum/DeleteAlbums', dataString, 'json', function (data, textStatus) {
        if (data.success) {
            closeBoxy(e, function () {
                infoBoxy('Photo Album Deleted', 'You have successfully deleted your album.', 2000, false, function () {
                    window.location = String.format('/{0}#photos?', profileUrl);
                });
            });
        }
    });
}
updatePhoto = function (pid, aid, description, cover, single) {
    var dataString = String.format('pid={0}&description={1}&cover={2}', pid, $.URLEncode(description), cover);
    ajaxPost('/Photos/UpdatePhoto', dataString, 'json', function (data, textStatus) {
        if (single != undefined && single) {
            window.location = String.format('/{0}#browsephotos?pid={0}{2}&action=photoupdated', profileUrl, data.pid, data.albumIdInUrl);
        }
    });
}
publishAlbum = function (e, purl, aid) {
    var dataString = String.format('aid={0}', aid);
    ajaxPost('/photos/publishalbum', dataString, 'json', function (data, textStatus) {
        $(e).parent().hide();
        $('#publish-btn').hide();
        infoBoxy('Photo Album Successfully Published', 'You have successfully published this album.', 2000, false, function (e) {
            window.location = String.format('/{0}/album?aid={1}{2}', purl, aid);
        });
    });
}
publishAlbumPhotos = function (e) {
    var pageActionJson = eval('(' + $(e).parents('.page-action').find('.page-action-data').val() + ')');
    var aid = pageActionJson.aid;
    var dataString = String.format('aid={0}', aid);
    ajaxPost('/photos/publishalbum', dataString, 'json', function (data, textStatus) {
        $(e).parent().hide();
        $('#publish-btn').hide();
        updateAlbumPhotos(e);
    });
}
updateAlbumPhotos = function (e) {
    if (isPosting(this)) return false; // are we posting? abort
    startPosting(this); // set posting var

    var updated = false;
    var pageActionJson = eval('(' + $(e).parents('.page-action').find('.page-action-data').val() + ')');
    var aid = pageActionJson.aid;
    // Modified photos
    $('#edit-photos div[pid] .modified').each(function () {
        if ($(this).val() == 'true') {
            var photoDIV = $(this).parents('div[pid]');
            var pid = photoDIV.attr('pid');
            photoDIV.find('textarea.caption').removeWatermark();
            var description = photoDIV.find('textarea.caption').val();
            var cover = photoDIV.find('.cover.gbtn.active').length > 0;
            updatePhoto(pid, aid, description, cover);
            updated = true;
        }
    });
    // Deleted photos
    $('#edit-photos div[pid] .deleted').each(function () {
        if ($(this).val() == 'true') {
            var photoDIV = $(this).parents('div[pid]');
            var pid = photoDIV.attr('pid');
            deletePhoto(pid, aid);
            updated = true;
        }
    });
    if (updated) {
        // Set Album Cover Photo
        setAlbumCover(e);
    }
    endPosting(this);
    //if (updated) infoBoxy('Photo Album Updated', 'You have successfully updated your album.', 2000);
    window.location = String.format('/{0}/album?aid={1}{2}', pageActionJson.purl, pageActionJson.aid, updated ? '&updated=1' : '');
}
markPhotoModified = function (e) {
    $(e).parents('div[pid]').find('.modified').val('true');
}
markPhotoDelete = function (e) {
    $(e).parents('div[pid]').find('.deleted').val('true');
    $(e).parents('div[pid]').find('.marked-delete').removeClass('hidden');
    $(e).parents('div[pid]').find('.action').addClass('hidden');
    $(e).parents('div[pid]').find('.textarea.caption').addClass('hidden');
}
unmarkPhotoDelete = function (e) {
    $(e).parents('div[pid]').find('.deleted').val('');
    $(e).parents('div[pid]').find('.marked-delete').addClass('hidden');
    $(e).parents('div[pid]').find('.action').removeClass('hidden');
    $(e).parents('div[pid]').find('.textarea.caption').removeClass('hidden');
}
editPhotoCaption = function (e) {
    $(e).autogrow();
}
savePhotoOrder = function (e) {
    var aid = $.deparam.querystring()['aid'];
    var dataString = String.format('ids={0}&aid={1}', $('#photos').sortable("toArray"), aid);
    ajaxPost('/Photos/SavePhotoOrder', dataString);
}
saveAlbumOrder = function (e) {
    var dataString = String.format('ids={0}', $('#photos').sortable("toArray"));
    ajaxPost('/PhotoAlbum/SaveAlbumOrder', dataString);
}

// Shared ApproveFriends function
approveFriend = function (id, fid, success) {
    var dataString = String.format('uid={0}&fid={1}', id, fid);
    ajaxPost('/Friends/ApproveFriend', dataString, 'json', success);
}
boxyApproveFriend = function (e) {
    var json = getActionDataJson(e);
    approveFriend(json.pid, json.fid, function (data, textStatus) {
        var html = "You have just accepted a friend request.";
        closeBoxy('#friend-request-form', function () {
            infoBoxy('Friend Request Accepted', html, 2000, false, function () {
                if (profileUrl != undefined) window.location = String.format('/{0}', json.pid);
            });
        });
    });
}

// Shared DeleteFriend function
deleteFriend = function (fid, success) {
    var dataString = String.format('fid={0}', fid);
    ajaxPost('/Friends/DeleteFriend', dataString, 'json', success);
}
boxyDeleteFriend = function (e, fid) {
    deleteFriend(fid, function (data, textStatus) {
        closeBoxy(e);
        infoBoxy('Friendship deleted', "You have just deleted a friendship.", 2000, false, function () {
            if (profileUrl != undefined) {
                window.location.reload(true);
            }
        });
    });
}



// Shared DeleteSuggestions function
deleteFriendSuggestions = function (id, success) {
    var dataString = String.format('ids={0}', id)
    ajaxPost('/Friends/DeleteSuggestions', dataString, 'json', success);
}



showPersonalMssg = function (e) {
    $(e).hide();
    $('#personal-mssg').show();
    $('#personal-mssg #message').focus().autogrow();
}

// Call to set the pagers
setPagers = function () {
    if ($('#pgrdata').length > 0) {
        var pgrData = $.deparam($('#pgrdata').val());
        var page = parseInt(pgrData['p']);
        var totalPages = parseInt(pgrData['tp']);
        var totalRows = parseInt(pgrData['tr']);

        // If TotalPages == 0 hide the pagers and return
        if (totalPages == 0) $('.pager').hide();

        $('.pager .nav').hide();
        var summary = String.format("<strong>{0}</strong> - <strong>{1}</strong> of <strong>{2}</strong>", pgrData['f'], pgrData['t'], pgrData['tr']);
        $('.pager .summary').html(summary);

        // First
        if (totalPages > 2 && page > 2) $('.pager .first').show().find('a').attr('href', urlPrefix() + $.param.querystring(fragment, 'page=1'));
        // Previous
        if (page > 1) $('.pager .prev').show().find('a').attr('href', urlPrefix() + $.param.querystring(fragment, 'page=' + (parseInt(page) - 1)));
        // Next
        if (page < totalPages) $('.pager .next').show().find('a').attr('href', urlPrefix() + $.param.querystring(fragment, 'page=' + (parseInt(page) + 1)));
        // Last
        if (page != totalPages) $('.pager .last').show().find('a').attr('href', urlPrefix() + $.param.querystring(fragment, 'page=' + totalPages));
    }
}
// Get url before '#' and if '#' doesn't exist append '#'
urlPrefix = function () {
    return window.location.href.replace($.param.fragment(), '') + (window.location.href.match('#') == undefined ? '#' : '');
}



// Common functions
String.format = function () {
    var s = arguments[0];
    for (var i = 0; i < arguments.length - 1; i++) {
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i + 1]);
    }
    return s;
}
$.fn.outerHtml = function () {
    return $('<div>').append(this.eq(0).clone()).html();
};
// Check if post in progress
isPosting = function (e) {
    return $.data(e, 'posting');
}
// Starting POST
startPosting = function (e) {
    $.data(e, 'posting', true);
}
// Ending POST
endPosting = function (e) {
    $.data(e, 'posting', false);
}
var allDialogs = [];
var boxyDialog;
function createBoxy(options) {
    options = $.extend(options || {});
    var content = "<div style='width:300px;height:100px;background-image:url(/Content/Images/ajax-uploading.gif);background-position:50% 70%;background-repeat:no-repeat;text-align:center;padding:1em 0;color:#333;'><h4>Loading...</h4></div>";
    boxyDialog = new Boxy(content, options);
    boxyDialog.centerAt($(window).width() / 2, 300);
    allDialogs.push(boxyDialog);
    return false;
}
getModalBoxy = function (url, title, success, complete) {
    var options = { closeable: false, title: title, draggable: false, modal: true };
    getBoxy(url, title, success, complete, options);
}
getBoxy = function (url, title, success, complete, options) {
    closeAllBoxy();
    // Create empty content boxy before loading content
    createBoxy(options == undefined ? { closeable: false, title: title, draggable: false, modal: false} : options);
    ajaxGet(url, 'html',
        function (data, textStatus) { // SUCCESS
            boxyDialog.setContent(data);
            boxyDialog.centerAt($(window).width() / 2, 300); // recenter boxy after content has been loaded

            closeAllErrorPrompts();

            if (typeof success == 'function') success(data, textStatus);
        }, function (XMLHttpRequest, textStatus) { // COMPLETE
            //highlightBoxyBorder(1);
            if (typeof complete == 'function') complete(XMLHttpRequest, textStatus);
        });
}
highlightBoxyBorder = function (times) {
    // Highlight the edges after loaded
    for (i = 0; i < times; i++) {
        $('.boxy-wrapper.fixed td.left, .boxy-wrapper.fixed td.right, .boxy-wrapper.fixed td.top, .boxy-wrapper.fixed td.bottom, , .boxy-wrapper.fixed td.bottom-left, , .boxy-wrapper.fixed td.bottom-right, .boxy-wrapper.fixed td.top-left, , .boxy-wrapper.fixed td.top-right').effect('highlight');
    }
}
postBoxy = function (url, dataString, title, success) {
    closeAllBoxy();
    // Create empty content boxy before loading content
    createBoxy({ closeable: false, title: title, draggable: false });
    ajaxPost(url, dataString, 'html', function (data, textStatus) {
        boxyDialog.setContent(data);
        boxyDialog.centerAt($(window).width() / 2, 300); // recenter boxy after content has been loaded
        // Highlight the edges after loaded
        //$('.boxy-wrapper.fixed td.left, .boxy-wrapper.fixed td.right, .boxy-wrapper.fixed td.top, .boxy-wrapper.fixed td.bottom, , .boxy-wrapper.fixed td.bottom-left, , .boxy-wrapper.fixed td.bottom-right, .boxy-wrapper.fixed td.top-left, , .boxy-wrapper.fixed td.top-right').effect('highlight');
        if (typeof success == 'function') success(data);
    });
}
closeBoxy = function (e, complete) {
    if (Boxy.get(e) != undefined) {
        Boxy.get(e).hideAndUnload();
        closeAllErrorPrompts();
    }
    if (typeof complete == 'function') complete();
}
closeAllBoxy = function (e) {
    for (var i = 0; i < allDialogs.length; i++) {
        allDialogs[i].unload();
    }
}
ajaxGet = function (url, dataType, success, complete, cache) {
    ajaxRequest('GET', url, '', dataType, success, complete, cache);
}
ajaxPost = function (url, dataString, dataType, success, complete) {
    ajaxRequest('POST', url, dataString, dataType, success, complete);
}
var authorized = true;
// Global AJAX Request function
ajaxRequest = function (type, url, dataString, dataType, success, complete, cache) {
    request = $.ajax({
        type: type,
        url: url,
        data: dataString,
        cache: cache == undefined ? false : cache,
        dataType: dataType,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.status != 0) {
                if (!isDebug) {
                    errorBoxy('Unexpected error', 'Oh, no way! We are so embarrassed to inform you that your action caused an unexpected error :( Please refresh your page and try again and if the problem persits contact us.');
                } else {
                    Boxy.alert(XMLHttpRequest.responseText);
                }
            }
        },
        success: function (data, textStatus) {
            // handle UNAUTHORIZED request
            if (data == 'unauthorized' && authorized) {
                authorized = false;
                infoBoxy('Unauthorized Access', 'You must be logged in to perform this action', 3000, true, function () {
                    window.location = '';
                });
            }
            // Callback
            if (typeof success == 'function') success(data, textStatus);
        },
        complete: function (XMLHttpRequest, textStatus) { // COMPLETE
            // Execute after request has been completed
            fixBG();
            // Callback
            if (typeof complete == 'function') complete(XMLHttpRequest, textStatus);
        }
    });
}
$.fn.autogrow = function (options) {
    this.filter('textarea').each(function () {
        var $this = $(this),
                minHeight = $this.height(),
                lineHeight = $this.css('lineHeight');
        var shadow = $('<div></div>').css({
            position: 'absolute',
            top: -10000,
            left: -10000,
            width: $(this).width(),
            fontSize: $this.css('fontSize'),
            fontFamily: $this.css('fontFamily'),
            lineHeight: $this.css('lineHeight'),
            resize: 'none'
        }).appendTo(document.body);
        var update = function () {
            var val = this.value.replace(/</g, '&lt;')
                                    .replace(/>/g, '&gt;')
                                    .replace(/&/g, '&amp;')
                                    .replace(/\n/g, '<br/>');
            shadow.html(val);
            $(this).css('height', Math.max(shadow.height() + 20, minHeight));
        }
        $(this).change(update).keyup(update).keydown(update);
        update.apply(this);
    });
    return this;
}
$.fn.watermark = function (css, text) {
    return this.each(function () {
        var i = $(this), w;
        i.focus(function () {
            w && !(w = 0) && i.removeClass(css).data('w', 0).val('');
        })
			.blur(function () {
			    !i.val() && (w = 1) && i.addClass(css).data('w', 1).val(text);
			})
			.closest('form').submit(function () {
			    w && i.val('');
			});
        i.blur();
    });
};
$.fn.blink = function (options) {
    var defaults = { delay: 500 };
    var options = $.extend(defaults, options);

    return this.each(function () {
        var obj = $(this);
        if (obj.attr("timerid") > 0) return;
        var timerid = setInterval(function () {
            if ($(obj).css("visibility") == "visible") {
                $(obj).css('visibility', 'hidden');
            }
            else {
                $(obj).css('visibility', 'visible');
            }
        }, options.delay);
        obj.attr("timerid", timerid);
    });
}
$.fn.unblink = function (options) {
    var defaults = { visible: true };
    var options = $.extend(defaults, options);

    return this.each(function () {
        var obj = $(this);
        if (obj.attr("timerid") > 0) {
            clearInterval(obj.attr("timerid"));
            obj.attr("timerid", 0);
            obj.css('visibility', options.visible ? 'visible' : 'hidden');
        }
    });
}
$.fn.removeWatermark = function () {
    return this.each(function () {
        $(this).data('w') && $(this).val('');
    });
};
$.fn.fadeThenSlideToggle = function (speed, easing, callback) {
    if (this.is(":hidden")) {
        return this.slideDown(speed, easing).fadeTo(speed, 1, easing, callback);
    } else {
        return this.fadeTo(speed, 0, easing).slideUp(speed, easing, callback);
    }
};
$.fn.slideDownFadeIn = function (speed, easing, callback) {
    if (this.is(":hidden")) {
        return this.slideDown(speed, easing).fadeTo(speed, 1, easing, callback);
    } else {
        return this.fadeTo(speed, 0, easing).slideUp(speed, easing, callback).slideDown(speed, easing).fadeTo(speed, 1, easing, callback);
    }
};
$.extend({ URLEncode: function (c) {
    var o = ''; var x = 0; c = c.toString(); var r = /(^[a-zA-Z0-9_.]*)/;
    while (x < c.length) {
        var m = r.exec(c.substr(x));
        if (m != null && m.length > 1 && m[1] != '') {
            o += m[1]; x += m[1].length;
        } else {
            if (c[x] == ' ') o += '+'; else {
                var d = c.charCodeAt(x); var h = d.toString(16);
                o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
            } x++;
        }
    } return o;
},
    URLDecode: function (s) {
        var o = s; var binVal, t; var r = /(%[^%]{2})/;
        while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
            b = parseInt(m[1].substr(1), 16);
            t = String.fromCharCode(b); o = o.replace(m[1], t);
        } return o;
    }
});
jQuery.fn.vibrate = function (conf) {
    var config = jQuery.extend({
        speed: 30,
        duration: 2000,
        frequency: 5000,
        spread: 3
    }, conf);

    return this.each(function () {
        var t = jQuery(this);

        var vibrate = function () {
            var topPos = Math.floor(Math.random() * config.spread) - ((config.spread - 1) / 2);
            var leftPos = Math.floor(Math.random() * config.spread) - ((config.spread - 1) / 2);
            var rotate = Math.floor(Math.random() * config.spread) - ((config.spread - 1) / 2);

            t.css({
                position: 'relative',
                left: leftPos + 'px',
                top: topPos + 'px',
                WebkitTransform: 'rotate(' + rotate + 'deg)'
            });
        };

        var doVibration = function () {
            var vibrationInterval = setInterval(vibrate, config.speed);

            var stopVibration = function () {
                clearInterval(vibrationInterval);
                t.css({
                    position: 'static',
                    WebkitTransform: 'rotate(0deg)'
                });
            };

            setTimeout(stopVibration, config.duration);
        };

        setInterval(doVibration, config.frequency);
    });
};
jQuery.fn.fadeThenSlideToggle = function (speed, easing, callback) {
    if (this.is(":hidden")) {
        return this.slideDown(speed, easing).fadeTo(speed, 1, easing, callback);
    } else {
        return this.fadeTo(speed, 0, easing).slideUp(speed, easing, callback);
    }
};
//// Photo Thumb Resize
//thumbResize = function (thumb, min_width, min_height, orientation) {
//    twidth = $(thumb).width();
//    theight = $(thumb).height();
//    new_height = theight;
//    new_width = twidth;
//    // strange 1px bug on MSIE
//    if ($.browser.msie) {
//        min_width = min_width + 1;
//        min_height = min_height + 1;
//    }
//    //calculate the good size
//    if (orientation == 'landscape') {
//        ratio = min_width / min_height;
//        tratio = twidth / theight;
//        if (tratio > ratio) {
//            new_height = min_height;
//            new_width = parseInt(new_height * tratio);
//        }
//        else {
//            new_width = min_width;
//            new_height = parseInt(new_width / tratio);
//        }
//    }
//    else {
//        ratio = min_height / min_width;
//        tratio = theight / twidth;
//        if (tratio > ratio) {
//            new_width = min_width;
//            new_height = parseInt(new_width * tratio);
//        }
//        else {
//            new_height = min_height;
//            new_width = parseInt(new_height / tratio);
//        }
//    }

//    // resize thumb
//    if (theight != new_height || twidth != new_width) {
//        $(thumb).height(new_height);
//        $(thumb).width(new_width);
//    }
//    // adjust position (vertical and horizontal centering for css cropping)
//    if (new_width > min_width) {
//        moveleft = parseInt((new_width - min_width) / 2);
//        $(thumb).css('left', '-' + moveleft + 'px');
//    }
//    if (new_height > min_height) {
//        movetop = parseInt((new_height - min_height) / 2);
//        $(thumb).css('top', '-' + movetop + 'px');
//    }
//}
//resizeThumbs = function (thumbs, min_width, min_height) {
//    orientation = (min_height > min_width) ? 'portrait' : 'landscape';
//    // hide images before resizing to avoid bad visual effect
//    thumbs.each(function () {
//        $(this).hide();
//    })
//    // use window.load because on document.ready images are not always loaded
//    //$(window).load(function () {
//    thumbs.each(function () {
//        thumbResize(this, min_width, min_height, orientation);
//        $(this).show();
//    });
//    //});
//}

validateJsonOperationResult = function (result, valSummary) {
    if (result.Success && result.RedirectToUrl != null) {
        document.location = result.RedirectToUrl;
    }
    else {
        if (valSummary == undefined) valSummary = $('#val-summary');

        for (var err in result.Values) {
            var propertyName = result.Values[err].PropertyName;
            var errorMessage = result.Values[err].Error;

            if (result.Values[err].IsError) {
                if (propertyName.length > 0) $.validationEngine.buildPrompt("#" + propertyName, errorMessage, "error");

                // Special case for Birthday control
                if (propertyName == 'DateOfBirth') $.validationEngine.buildPrompt("#birthyear", errorMessage, "error");
            } else {
                $.validationEngine.closePrompt("#" + propertyName);

                // Special case for Birthday control
                if (propertyName == 'DateOfBirth') $.validationEngine.closePrompt("#birthyear");
            }
        }

        var addClass = result.Success ? 'success' : 'error';
        var removeClass = result.Success ? 'error' : 'success';
        valSummary.find('span').html(result.Message).removeClass(removeClass).addClass(addClass).fadeIn('fast');
        // auto close only if success
        if (result.Success) {
            window.setTimeout(function () {
                valSummary.find('span').fadeOut(); // wait, x time and close the summary
            }, 5000);
        }
    }
}

closeAllErrorPrompts = function () {
    $.validationEngine.closePrompt(".formError");
}

//validateOperationResult = function (result, valSummary) {
//    // Clear text and remove class for validations
//    //$('.val-error').hide();
//    //$('.val-row').removeClass('val-error-bar');

//    // close all error prompts
//    //$.validationEngine.closePrompt(".formError");
//    //$('.val-item').removeClass('val-error');

//    if (valSummary == undefined) valSummary = $('#val-summary');

//    if (result.Success && result.RedirectToUrl != null) {
//        document.location = result.RedirectToUrl;
//    }
//    else {
//        for (var err in result.Errors) {
//            var propertyName = result.Errors[err].PropertyName;
//            var errorMessage = result.Errors[err].Error;

//            if (errorMessage != undefined) {
//                if (propertyName.length > 0) $.validationEngine.buildPrompt("#" + propertyName, errorMessage, "error");

//                // Special case for Birthday control
//                if (propertyName == 'DateOfBirth') $.validationEngine.buildPrompt("#birthyear", errorMessage, "error");
//            } else {
//                $.validationEngine.closePrompt("#" + propertyName);
//            }

//            //$('li.val_' + propertyName + ', tr.val_' + propertyName).addClass('val-error-bar');
//            //$('label#val_' + propertyName).text(errorMessage).show();
//        }
//    }
//    var addClass = result.Success == true ? 'info-box' : 'error-box';
//    var removeClass = result.Success == false ? 'info-box' : 'error-box';
//    valSummary.html(result.Message).removeClass(removeClass).addClass(addClass).fadeIn('fast');
//}
findContacts = function (email) {
    getBoxy(String.format('/Friends/FindContacts?email={0}', $.URLEncode(email)), '');
}
getContacts = function (e) {
    var email = $('#email_box').val();
    var pwd = $('#password_box').val();
    var prov = $('#provider_box').val();

    if (email.length == 0) {
        alert('Please enter your email');
    }
    if (pwd.length == 0) {
        alert('Please enter your password');
    }
    if (prov.length == 0) {
        alert('Please select a Provider');
    }
    if (email.length == 0 || pwd.length == 0 || prov.length == 0) return;

    $('#uploading').removeClass('hidden');
    $('#find-contacts-form .signin').addClass('hidden');
    var dataString = String.format("{0}&import=Import+Contacts&step=get_contacts", $('#find-contacts-form').serialize());
    //dataString = "email_box=emer.kurbegovic@gmail.com&provider_box=gmail&password_box=xxx&import=Import+Contacts&step=get_contacts";
    ajaxPost('/openinviter/f2.php', dataString, 'html', function (data, textStatus) {
        //alert(data);
        //$('body').append(String.format("<input type='text' id='contact-emails' value='{0}'>", data));
        if (data.indexOf('Login') == 0) {
            errorBoxy('Could not import your contacts', data);
        } else if (data.indexOf('@') > 1) {
            dataString = String.format("emails={0}", $.URLEncode(data));
            postBoxy('/Friends/InviteContacts', dataString, '', function (data) {
                //$.fcbkListSelection("#fcbklist", "695", "50", "3");
            });
        } else {
            errorBoxy('Cannot Import Your Contacts', 'We are unable to import your contacts. Please try again.');
        }
    });
}
processSelectedContacts = function (e, emails, ids) {
    $('#uploading').removeClass('hidden');
    $('#invite-contacts-form .contacts').addClass('hidden');
    boxyDialog.centerAt($(window).width() / 2, 300); // recenter boxy
    //    window.setTimeout(function () {
    //        closeBoxy(e);
    //        infoBoxy('Contact Invitations Completed', 'Your contacts have been successfully invited and/or added to friends.', 4000, false, function () {
    //            window.location = '/#friends/invitehistory';
    //        });
    //    }, 4000);
    //    return;

    var dataString = String.format("emails={0}&ids={1}", emails, ids);
    ajaxPost('/Friends/ProcessSelectedContacts', dataString, 'html', function (data, textStatus) {
        closeBoxy(e);
        infoBoxy('Contact Invitations Completed', 'Your contacts have been successfully invited and/or added to friends.', 3000, false, function () {
            window.location = '/#friends/invitehistory';
        });
    });
}
jQuery.cookie = function (key, value, options) {
    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
