var geograffiti = geograffiti ||
{};
geograffiti.SideBarEvent = {
    SideBarExtended: "geograffiti:sideBarExtended",
    SideBarCollapsed: "geograffiti:sideBarCollapsed",
    VoiceMarkLinkClicked: "geograffiti:voiceMarkLinkClicked",
    GoogleLocalResultLinkClicked: "geograffiti:googleLocalResultLinkClicked",
    VoiceMarksHidden: "geograffiti:voiceMarksHidden",
    VoiceMarksVisible: "geograffiti:voiceMarksVisible",
    GoogleLocalResultsHidden: "geograffiti:googleLocalResultsHidden",
    GoogleLocalResultsVisible: "geograffiti:googleLocalResultsVisible",
    SearchRequested: "geograffiti:searchRequested",
    FilterSearchRequested: "geograffiti:filterSearchRequested",
    ViewProfileLinkClicked: "geograffiti:viewProfileLinkClicked",
    ListenLinkClicked: "geograffiti:listenLinkClicked",
    ResultUserNameClicked: "geograffiti:resultUserNameClicked",
    MouseOverGoogleLocalResult: "geograffiti:mouseOverGoogleLocalResult",
    MouseOverVoiceMarkResult: "geograffiti:mouseOverVoiceMarkResult",
    UserVoiceMarksSearchRequested: "geograffiti:userVoiceMarksSearchRequested",
    ViewGroupVoiceMarksLinkClicked: "geograffiti:viewGroupVoiceMarksLinkClicked",
    GroupVoiceMarksSearchRequested: "geograffiti:groupVoiceMarksSearchRequested",
    MyAccountReady: "geograffiti:myAccountReady"
};
geograffiti.SideBar = function(){
    var isExtended = true;
    var activeElement = null;
    var elementToResize = null;
    var pagingControl = null;
    var contentContainer = null;
    var communityContainer = null;
    var searchResultsContainer = null;
    var accountContainer = null;
    var searchQuery = null;
    var searchingActivityIndicatorMarkup = '<div id="searching-indicator"><div id="searching-indicator-label">Searching...</div><div id="searching-indicator-imagecontainer"><img id="searching-indicator-image" src="/images/searching-indicator-128x15.gif" alt="Search Activity Indicator Image"/></div></div>';
    var loadingAccountActivityIndicatorMarkup = '<div id="searching-indicator"><div id="searching-indicator-label">Loading Your Account...</div><div id="searching-indicator-imagecontainer"><img id="searching-indicator-image" src="/images/searching-indicator-128x15.gif" alt="Activity Indicator Image"/></div></div>';
    var loadingCommunityActivityIndicatorMarkup = '<div id="searching-indicator"><div id="searching-indicator-label">Loading Community...</div><div id="searching-indicator-imagecontainer"><img id="searching-indicator-image" src="/images/searching-indicator-128x15.gif" alt="Search Activity Indicator Image"/></div></div>';
    var loadingLatestGroupsActivityIndicatorMarkup = '<div id="searching-indicator"><div id="searching-indicator-label">Loading Latest Groups...</div><div id="searching-indicator-imagecontainer"><img id="searching-indicator-image" src="/images/searching-indicator-128x15.gif" alt="Search Activity Indicator Image"/></div></div>';
    var loadingGroupInfoActivityIndicatorMarkup = '<div id="searching-indicator"><div id="searching-indicator-label">Loading Group Info...</div><div id="searching-indicator-imagecontainer"><img id="searching-indicator-image" src="/images/searching-indicator-128x15.gif" alt="Search Activity Indicator Image"/></div></div>';
    var carrierCollection = null;
    var handsetCollection = null;
    var myAccountAccordion = null;
    var ContainerType = {
        SearchResults: 0,
        Community: 1,
        Account: 2
    };
    var TabState = {
        Zero: 0,
        One: 1,
        Two: 2,
        Three: 3,
        Four: 4,
        Five: 5
    };
    var currentTabState = TabState.Zero;
    var filterBarElement = null;
    var groupsAccordionOptions = {
        classNames: {
            toggle: "groups_accordion_toggle",
            toggleActive: "groups_accordion_toggle_active",
            content: "groups_accordion_content"
        }
    };
    return {
        adjustContentAreaHeight: function(sideBarHeight){
            var contentHeight = sideBarHeight - 20;
            var style = "height: " + contentHeight + "px;";
            sideBarContent.setStyle(style);
            var searchResultsHeight = contentHeight - $("pagingcontrol").getHeight() - 20;
            contentContainer.setStyle("height: " + searchResultsHeight + "px;")
        },
        applyOptions: function(options){
            var self = this;
            if (options.width && options.height) {
                var style = "width:" + options.width + "px;height:" + options.height + "px;";
                sideBarElement.setStyle(style);
                self.adjustContentAreaHeight(options.height)
            }
            else {
                if (options.width) {
                    var style = "width:" + options.width + "px;";
                    sideBarElement.setStyle(style)
                }
                else {
                    if (options.height) {
                        var style = "height:" + options.height + "px;";
                        sideBarElement.setStyle(style);
                        self.adjustContentAreaHeight(options.height)
                    }
                }
            }
        },
        load: function(){
        },
        populateMyPhones: function(accountData, ba){
            var privateStuff = accountData.profile["private"];
            var phones = privateStuff.voiceUserRecords;
            var voiceUserRecords = new Array();
            ba('<div id="account-myphones-toggle" class="accordion_toggle"><span>My Phones</span></div>');
            ba('<div id="account-myphones-content" class="accordion_content">');
            ba('<div id="account-myphones-container">');
            ba('<div id="phone-table-container">');
            ba('<table id="phone-table">');
            ba("<thead><tr><th>Action</th><th>Number</th><th>Status</th><th></th><th>Carrier</th><th>Model</th></tr></thead>");
            ba("<tbody>");
            for (var i = 0, limit = phones.length; i < limit; ++i) {
                var phone = phones[i];
                voiceUserRecords.push({
                    id: phone.id,
                    verified: phone.status === 1 ? true : false
                });
                ba('<tr id="phone-record-$0"><td id="delete-phone-$1" class="myphones-action-delete">Delete</td><td class="myphones-phone-number">$2</td><td class="myphones-phone-number-status $3">$4</td><td>$5</td><td id="myphones-carrier-$6" class="myphones-carrier"><div>$7</div></td><td id="myphones-handset-type-$8" class="myphones-handset-type"><div>$9</div></td></tr>', phone.id, phone.id, phone.number, phone.status === 1 ? "myphones-phone-number-status-verified" : "myphones-phone-number-status-unverified", function(){
                    if (phone.status === 1) {
                        return "VERIFIED"
                    }
                    else {
                        return "UNVERIFIED"
                    }
                }(), function(){
                    if (phone.status !== 1) {
                        var id = String.format("phone-$0", phone.id);
                        return String.format('<input id="$0" name="phone-$1" type="button" value="Verify" />', id, phone.id)
                    }
                    else {
                        return ""
                    }
                }(), phone.id, function(){
                    if (!String.isNullOrEmpty(phone.carrier)) {
                        return phone.carrier
                    }
                    else {
                        return "Set Carrier"
                    }
                }(), phone.id, function(){
                    if (!String.isNullOrEmpty(phone.handsetName)) {
                        return phone.handsetName
                    }
                    else {
                        return "Select Phone Model"
                    }
                }())
            }
            ba("</tbody>");
            ba("</table>");
            ba("</div>");
            ba('<div id="verify-phone-control">');
            ba('<div id="verify-phone-description">');
            ba("GeoGraffiti will call you and provide a verification code. Type the code into the box below.");
            ba("</div>");
            ba('<form id="verify-phone-form" name="verify-phone-form" action="$0">', gg.ApiUrl.VerifyVerificationCallCode);
            ba('<input id="verify-phone-vid" name="vid" type="hidden" value="" />');
            ba('<input id="verify-phone-code" name="code" type="text" value="" />');
            ba('<input id="verify-phone-submit-button" name="verify-phone-submit-button" type="submit" value="Verify" />');
            ba("</form>");
            ba("</div>");
            ba('<div id="add-phone-control">');
            ba('<div id="add-phone-label">Add Phone Number</div>');
            ba('<form id="addphone-form" name="addphone-form" action="$0">', gg.ApiUrl.AddPhoneNumber);
            ba('<input id="phone-text-field" name="phoneNumber" type="text" /><input id="addphone-submit-button" type="submit" value="Add"/>');
            ba("</form>");
            ba("</div>");
            ba("</div>");
            ba("</div>");
            return voiceUserRecords
        },
        populateMyProfile: function(accountData, ba){
            var publicStuff = accountData.profile["public"];
            var privateStuff = accountData.profile["private"];
            gg.mySystemUserId = publicStuff.systemUserId;
            ba('<div id="account-myprofile-toggle" class="accordion_toggle"><span>My Profile</span></div>');
            ba('<div id="account-myprofile-content" class="accordion_content">');
            ba('<div id="account-myprofile-container">');
            ba('<div id="myprofile-pic-control">');
            ba('<div id="myprofile-pic-frame" class="profile-pic-frame">');
            ba('<img id="myprofile-pic" src="/api/user/$0/pictures/0/thumbnail/medium/?$1" alt="Profile Picture for $2"/>', publicStuff.systemUserId, new Date().getTime(), publicStuff.userName);
            ba("</div>");
            ba('<div id="myprofile-pic-change-control">Change Picture</div>');
            ba('<div id="myprofile-remoting-container" class="hidden"><iframe id="myprofile-remoting-frame" src="about:blank" class="hidden" name="myprofile-remoting-frame"></iframe></div>');
            ba('');
            ba('<div id="myprofile-pic-selector"><p id="myprofile-pic-change-message">Pics should be 120x120 (pixels) max.<\/p><form id="myprofile-pic-select-form" action="$0" method="POST" enctype="multipart/form-data" target="myprofile-remoting-frame"><input id="pictureFile" name="pictureFile" type="file" /><input class="inline" type="submit" value="Upload"/><input class="inline" type="reset" value="Cancel"/></form></div>', gg.ApiUrl.UploadProfilePic);
            ba("</div>");
            ba('<div id="myprofile-top-right">');
            ba('<div id="myprofile-name-container">');
            ba('<span id="myprofile-first-name" class="rightpad-medium">$0</span>', gg.textOrDefault(publicStuff.firstName, "First Name"));
            ba('<span id="myprofile-last-name">$0</span>', gg.textOrDefault(publicStuff.lastName, "<Last Name>"));
            ba("</div>");
            ba('<div id="myprofile-aka-container">aka</div>');
            ba('<div id="myprofile-username-container">');
            ba('<div id="myprofile-username">$0</div>', gg.textOrDefault(publicStuff.userName, "<User Name>"));
            ba("</div>");
            ba('<div id="myprofile-gender-container">');
            ba('<div id="myprofile-gender">$0</div>', gg.textOrDefault(publicStuff.gender, "<Gender>"));
            ba("</div>");
            ba('<div id="myprofile-in-container">in</div>');
            ba('<div id="myprofile-citystatezip-container">');
            ba('<span id="myprofile-city">$0</span><span class="rightpad-small">,</span>', gg.textOrDefault(publicStuff.city, "<City>"));
            ba('<span id="myprofile-state" class="rightpad-small">$0</span>', gg.textOrDefault(publicStuff.region, "<State/Region>"));
            ba('<span id="myprofile-postalcode">$0</span>', gg.textOrDefault(publicStuff.postalCode));
            ba("</div>");
            ba('<div id="myprofile-country-container">');
            ba('<div id="myprofile-country">$0</div>', gg.textOrDefault(publicStuff.country, "<Enter Country>"));
            ba("</div>");
            ba("</div>");
            ba('<div id="public-info-bottom">');
            ba('<div id="myprofile-birthday-container">');
            ba('<span id="myprofile-birthday-label" class="myprofile-label">Birthday: </span>');
            ba('<span id="myprofile-birthday" class="myprofile-value">$0</span>', gg.textOrDefault(publicStuff.dateOfBirth, "<Enter Birthday>"));
            ba("</div>");
            ba("</div>");
            ba('<div id="private-info">');
            ba('<div id="private-info-notice">Private Info (for your eyes only)</div>');
            ba('<div id="myprofile-email-container">');
            ba('<span id="myprofile-email-label" class="myprofile-label">Email: </span>');
            ba('<span id="myprofile-email" class="myprofile-value">$0</span>', gg.textOrDefault(privateStuff.emailAddress, "<Enter Email Address>"));
            ba("</div>");
            ba("</div>");
            ba("</div>");
            ba("</div>")
        },
        createPreferenceInPlaceEditor: function(element, preference){
            new Ajax.InPlaceEditor(element, gg.ApiUrl.SetPreference, {
                clickToEditText: "Edit",
                highlightcolor: "#eddd80",
                cancelControl: "button",
                callback: function(form, value){
                    return String.format("preference=$0&value=$1&echovalue", preference, encodeURIComponent(value))
                }
            })
        },
        populateMyGroups: function(accountData, ba){
            var groups = accountData.groups;
            if (groups) {
                ba('<div id="account-mygroups-toggle" class="accordion_toggle"><span>My Groups</span></div>');
                ba('<div id="account-mygroups-content" class="accordion_content">');
                ba('<table id="mygroups-table">');
                ba("<thead>");
                ba("<tr>");
                ba("<th>Delete</th>");
                ba("<th>Name</th>");
                ba("<th>Owner/Member</th>");
                ba("</tr>");
                ba("</thead>");
                ba("<tbody>");
                groups.each(function(group){
                    ba('<tr id="mygroups-group-$0">', group.id);
                    ba('<td id="mygroups-action-leave-$0" class="mygroups-action mygroups-action-leave">Leave Group</td>', group.id);
                    ba('<td class="mygroups-group-name">$0</td>', group.name);
                    ba('<td class="mygroups-membership">$0</td>', group.isOwner ? "Owner" : "Member");
                    ba("</tr>")
                });
                ba("</tbody>");
                ba("</table>");
                ba("</div>")
            }
        },
        populateMyHood: function(accountData, ba){
            var hood = accountData.hood;
            if (hood) {
                ba('<div id="account-myhood-toggle" class="accordion_toggle"><span>My Hood</span></div>');
                ba('<div id="account-myhood-content" class="accordion_content">');
                ba('<table id="myhood-table">');
                ba("<thead>");
                ba("<tr>");
                ba("<th>Delete</th>");
                ba("<th>Name</th>");
                ba("<th>Listen</th>");
                ba("</tr>");
                ba("</thead>");
                ba("<tbody>");
                hood.each(function(entry){
                    gg.log("The entry is %o", entry);
                    ba('<tr id="myhood-entry-$0-$1-$2">', entry.id, entry.userId, entry.isAnonymous);
                    ba('<td class="myhood-action myhood-action-delete">Delete</td>');
                    ba('<td class="myhood-action-viewprofile $0">$1</td>', !entry.isAnonymous ? "myhood-action" : "", entry.userName);
                    ba('<td class="myhood-action myhood-action-listen">Listen to their Stuff</td>');
                    ba("</tr>")
                });
                ba("</tbody>");
                ba("</table>");
                ba("</div>")
            }
        },
        populateMyFans: function(accountData, ba){
            var fans = accountData.fans;
            if (fans) {
                ba('<div id="account-myfans-toggle" class="accordion_toggle"><span>My Fans</span></div>');
                ba('<div id="account-myfans-content" class="accordion_content">');
                ba('<table id="myfans-table">');
                ba("<thead>");
                ba("<tr>");
                ba("<th>Name</th>");
                ba("<th>Listen</th>");
                ba("</tr>");
                ba("</thead>");
                ba("<tbody>");
                fans.each(function(fan){
                    ba('<tr id="myfans-entry-$0">', fan.id);
                    ba('<td class="myfans-action myfans-action-viewprofile">$0</td>', fan.userName);
                    ba('<td class="myfans-action myfans-action-listen">Listen to their Stuff</td>');
                    ba("</tr>")
                });
                ba("</tbody>");
                ba("</table>");
                ba("</div>")
            }
        },
        populateMyVoiceMarks: function(accountData, ba){
            try {
                var voiceMarks = accountData.voiceMarks;
                if (voiceMarks) {
                    ba('<div id="account-myvoicemarks-toggle" class="accordion_toggle"><span>My VoiceMarks</span></div>');
                    ba('<div id="account-myvoicemarks-content" class="accordion_content">');
                    ba('<table id="myvoicemarks-table">');
                    ba("<thead>");
                    ba("<tr>");
                    ba("<th>Delete</th>");
                    ba("<th>Title</th>");
                    ba("<th>View on Map</th>");
                    ba("</tr>");
                    ba("</thead>");
                    ba("<tbody>");
                    voiceMarks.each(function(nakedVoiceMark){
                        var voiceMark = Object.extend(nakedVoiceMark, geograffiti.VoiceMarkBase);
                        ba('<tr id="myvoicemarks-entry-$0">', voiceMark.id);
                        ba('<td class="myvoicemarks-action myvoicemarks-action-delete">Delete</td>');
                        ba('<td class="myvoicemarks-voicemark-title">$0</td>', voiceMark.getTitle());
                        ba('<td class="myvoicemarks-action myvoicemarks-action-view">Map</td>');
                        ba("</tr>")
                    });
                    ba("</tbody>");
                    ba("</table>");
                    ba("</div>")
                }
            } 
            catch (e) {
                gg.error("ERRRROR %o", e)
            }
        },
        notificationNameToNotificationId: function(name){
            var notificationId = null;
            if (name.include("-new-hood-")) {
                notificationId = 1
            }
            else {
                if (name.include("-new-fan-")) {
                    notificationId = 3
                }
                else {
                    if (name.include("-responses-")) {
                        notificationId = 2
                    }
                }
            }
            return notificationId
        },
        notificationNameToNotificationType: function(name){
            var notificationType = null;
            if (name.startsWith("enable-")) {
                if (name.endsWith("-sms")) {
                    notificationType = 1
                }
                else {
                    if (name.endsWith("-email")) {
                        notificationType = 2
                    }
                    else {
                        if (name.endsWith("-phonecall")) {
                            notificationType = 3
                        }
                    }
                }
            }
            return notificationType
        },
        notificationNameToNotificationFrequency: function(name){
            var notificationFrequency = null;
            return notificationFrequency
        },
        notificationNameToLiteral: function(notificationName, notifications){
            var literal = null;
            var notificationId = this.notificationNameToNotificationId(notificationName);
            var notificationType = this.notificationNameToNotificationType(notificationName);
            notifications.each(function(notification){
                if (notification.notificationId === notificationId && notification.type === notificationType) {
                    literal = notification;
                    throw $break
                }
            });
            return literal
        },
        isNotificationEnabled: function(notificationName, notifications){
            var enabled = false;
            var notificationId = this.notificationNameToNotificationId(notificationName);
            notifications.each(function(notification){
                if (notification.notificationId === notificationId) {
                    enabled = true;
                    throw $break
                }
            });
            return enabled
        },
        getNotificationFrequencyCheckedAttribute: function(notification, frequency){
            var value = "";
            if (notification != null) {
                if (notification.frequency === frequency) {
                    value = 'checked="checked"'
                }
            }
            return value
        },
        populateNotifications: function(accountData, ba){
            var currentForm = null;
            var forms = new Array();
            var notifications = accountData.notifications;
            try {
                ba('<div id="account-notifications-toggle" class="accordion_toggle"><span>Notifications</span></div>');
                ba('<div id="account-notifications-content" class="accordion_content">');
                ba('<div id="notification-new-fan-container">');
                ba('<div id="notification-new-fan-description">When someone becomes my fan, notify me via...</div>');
                ba('<div id="notification-new-fan-email">');
                currentForm = "new-fan-notification-email-form";
                forms.push(currentForm);
                var notification = this.notificationNameToLiteral("enable-new-fan-notification-email", notifications);
                gg.log("The notification is %o", notification);
                ba('<form id="$0" action="$1">', currentForm, gg.ApiUrl.SetNotificationPreferences);
                ba('<div class="notification-name-container">');
                ba('<input type="checkbox"  $0 class="notification-checkbox" id="checkbox-new-fan-notification-email" name="enable-new-fan-notification-email" />', notification != null ? 'checked="checked"' : "");
                ba('<label class="notification-name" for="checkbox-new-fan-notification-email">Email</label>');
                ba("</div>");
                ba("</form>");
                ba("</div>");
                ba('<div id="notification-new-fan-sms">');
                currentForm = "notification-new-fan-sms-form";
                forms.push(currentForm);
                notification = this.notificationNameToLiteral("enable-new-fan-notification-sms", notifications);
                ba('<form id="$0" action="$1">', currentForm, gg.ApiUrl.SetNotificationPreferences);
                ba('<div class="notification-name-container">');
                ba('<input type="checkbox"  $0 class="notification-checkbox" id="checkbox-new-fan-notification-sms" name="enable-new-fan-notification-sms" />', notification != null ? 'checked="checked"' : "");
                ba('<label class="notification-name" for="checkbox-new-fan-notification-sms">SMS</label>');
                ba("</div>");
                ba("</form>");
                ba("</div>");
                ba("</div>");
                ba('<div id="notification-responses-container">');
                ba('<div id="notification-responses-description">When someone responds to my Voice Marks, notify me via...</div>');
                ba('<div id="notification-responses-email">');
                currentForm = "notification-responses-email-form";
                forms.push(currentForm);
                notification = this.notificationNameToLiteral("enable-responses-notification-email", notifications);
                ba('<form id="$0" action="$1">', currentForm, gg.ApiUrl.SetNotificationPreferences);
                ba('<div class="notification-name-container">');
                ba('<input type="checkbox"  $0 class="notification-checkbox" id="checkbox-responses-notification-email" name="enable-responses-notification-email" />', notification != null ? 'checked="checked"' : "");
                ba('<label class="notification-name" for="checkbox-responses-notification-email">Email</label>');
                ba("</div>");
                ba("</form>");
                ba("</div>");
                ba('<div id="notification-responses-sms">');
                currentForm = "notification-responses-sms-form";
                forms.push(currentForm);
                notification = this.notificationNameToLiteral("enable-responses-notification-sms", notifications);
                ba('<form id="$0" action="$1">', currentForm, gg.ApiUrl.SetNotificationPreferences);
                ba('<div class="notification-name-container">');
                ba('<input type="checkbox"  $0 class="notification-checkbox" id="checkbox-responses-notification-sms" name="enable-responses-notification-sms" />', notification != null ? 'checked="checked"' : "");
                ba('<label class="notification-name" for="checkbox-responses-notification-sms">SMS</label>');
                ba("</div>");
                ba("</form>");
                ba("</div>");
                ba("</div>");
                ba("</div>");
                return forms
            } 
            catch (e) {
                gg.error("EXCEPTION......%o", e)
            }
        },
        submitPreferencesForm: function(form){
            form.request({
                onSuccess: function(transport){
                    gg.info("success!!!!---> NOTIFICATION FORM %o", notificationForm)
                },
                onFailure: function(transport){
                    gg.error("failure!!!!---> NOTIFICATION FORM %o", notificationForm)
                }
            })
        },
        disableNotifications: function(notification){
            var url = String.format("$0?$1=off", gg.ApiUrl.SetNotificationPreferences, notification);
            new Ajax.Request(url, {
                onSuccess: function(transport){
                    gg.log("Success disabling notifications of type %s", notification)
                },
                onFailure: function(transport){
                    gg.error("Failure disabling notifications...%o", transport)
                }
            })
        },
        verifyPhoneButtonClicked: function(e, voiceUserId){
            e.stop();
            $("verify-phone-control").setStyle("display:block");
            $("verify-phone-vid").value = voiceUserId;
            new Ajax.Request(String.format("$0?vid=$1", gg.ApiUrl.VerifyPhoneNumber, voiceUserId), {
                onSuccess: function(transport){
                    gg.info("SUCCESS sending verification call!")
                },
                onFailure: function(transport){
                    gg.error("Error sending verification call...%o", transport)
                }
            })
        },
        deletePhoneNumber: function(e){
            e.stop();
            var voiceUserId = e.element().identify().gsub("delete-phone-", "");
            var url = String.format("$0?vid=$1", gg.ApiUrl.DeletePhoneNumber, voiceUserId);
            new Ajax.Request(url, {
                onSuccess: function(transport){
                    var apiResponse = transport.responseText.evalJSON(true);
                    if (apiResponse && apiResponse.deleted) {
                        gg.info("Success deleting phone number %o", apiResponse);
                        var rowId = String.format("phone-record-$0", apiResponse.id);
                        var row = $(rowId);
                        if (row) {
                            var resultRow = row.remove();
                            if (resultRow) {
                                gg.log("Row removed...%o", resultRow)
                            }
                            else {
                                gg.warn("phone row could not be removed...%s", rowId)
                            }
                        }
                        else {
                            gg.warn("Could not find phone recrod row with id %s", rowId)
                        }
                    }
                    else {
                        gg.error("Failure removing phone number according to response...%o", apiResponse)
                    }
                },
                onFailure: function(transport){
                    gg.error("Error removing phone number....%o", transport)
                }
            })
        },
        deleteHoodEntry: function(entryId, userId, isAnonymous){
            var parameters = $H({
                sid: userId,
                isu: !isAnonymous
            });
            new Ajax.Request(gg.ApiUrl.DeleteSubscription, {
                parameters: parameters,
                onSuccess: function(transport){
                    var apiResponse = transport.responseText.evalJSON(true);
                    if (apiResponse.status === 0) {
                        $(String.format("myhood-entry-$0-$1-$2", entryId, userId, isAnonymous)).remove()
                    }
                    else {
                        gg.error("api response reports failure...%o", apiResponse)
                    }
                },
                onFailure: function(transport){
                    gg.error("request failed %o", transport)
                }
            })
        },
        deleteVoiceMark: function(voiceMarkId){
            var parameters = $H({
                vmid: voiceMarkId
            });
            new Ajax.Request(gg.ApiUrl.DeleteVoiceMark, {
                parameters: parameters,
                onSuccess: function(transport){
                    var apiResponse = transport.responseText.evalJSON(true);
                    if (apiResponse.status === 0) {
                        $(String.format("myvoicemarks-entry-$0", voiceMarkId)).remove()
                    }
                    else {
                        gg.error("api response reports failure...%o", apiResponse)
                    }
                },
                onFailure: function(transport){
                    gg.error("request failed %o", transport)
                }
            })
        },
        myHoodListenLinkClicked: function(userId){
            gg.log("my hood listen link clicked");
            var event = sideBarElement.fire(gg.SideBarEvent.ListenLinkClicked, {
                id: userId
            });
            gg.log("fired event %o", event)
        },
        myHoodViewProfileLinkClicked: function(userId){
            gg.log("myhood profile link clicked");
            var event = sideBarElement.fire(gg.SideBarEvent.ViewProfileLinkClicked, {
                id: userId
            });
            gg.log("fired event %o", event)
        },
        myFansItemClicked: function(e){
            e.stop();
            var source = e.element();
            if (source.hasClassName("myfans-action")) {
                var containingRow = $(source.parentNode);
                var id = containingRow.identify();
                gg.log("The id is %s", id);
                if (id.include("myfans-entry-")) {
                    var userId = id.gsub("myfans-entry-", "");
                    gg.log("This is for User %s", userId);
                    if (source.hasClassName("myfans-action-listen")) {
                        gg.log("listen action clicked");
                        var event = sideBarElement.fire(gg.SideBarEvent.ListenLinkClicked, {
                            id: userId
                        });
                        gg.log("fired event %o", event)
                    }
                    else {
                        if (source.hasClassName("myfans-action-viewprofile")) {
                            gg.log("view profile action clicked");
                            var event = sideBarElement.fire(gg.SideBarEvent.ViewProfileLinkClicked, {
                                id: userId
                            });
                            gg.log("fired event %o", event)
                        }
                    }
                }
            }
            else {
                gg.warn("Non-action clicked %s", source)
            }
        },
        myHoodItemClicked: function(e){
            try {
                e.stop();
                var source = e.element();
                if (source.hasClassName("myhood-action")) {
                    var containingRow = $(source.parentNode);
                    var id = containingRow.identify();
                    gg.log("The id is %s", id);
                    if (id.include("myhood-entry-")) {
                        var i = 0;
                        var entryId = null;
                        var userId = null;
                        var isAnonymous = null;
                        id.scan(/\d+|false|true/, function(match){
                            var pattern = match[0];
                            if (i === 0) {
                                entryId = parseInt(pattern)
                            }
                            else {
                                if (i === 1) {
                                    userId = parseInt(pattern)
                                }
                                else {
                                    if (i === 2) {
                                        if (pattern === "false") {
                                            isAnonymous = false
                                        }
                                        else {
                                            if (pattern === "true") {
                                                isAnonymous = true
                                            }
                                        }
                                    }
                                }
                            }
                            i++
                        });
                        gg.log("This is for entry %s", entryId);
                        if (source.hasClassName("myhood-action-listen")) {
                            gg.log("listen action clicked");
                            this.myHoodListenLinkClicked(userId)
                        }
                        else {
                            if (source.hasClassName("myhood-action-delete")) {
                                gg.log("delete action clicked");
                                this.deleteHoodEntry(entryId, userId, isAnonymous)
                            }
                            else {
                                if (source.hasClassName("myhood-action-viewprofile")) {
                                    if (!isAnonymous) {
                                        this.myHoodViewProfileLinkClicked(userId)
                                    }
                                    gg.log("view action clicked")
                                }
                            }
                        }
                    }
                }
                else {
                    gg.warn("Non-action clicked %s", source)
                }
            } 
            catch (e) {
                gg.error(e)
            }
        },
        myVoiceMarksItemClicked: function(e){
            e.stop();
            var source = e.element();
            if (source.hasClassName("myvoicemarks-action")) {
                var containingRow = $(source.parentNode);
                var id = containingRow.identify();
                gg.log("The id is %s", id);
                if (id.include("myvoicemarks-entry-")) {
                    var voiceMarkId = id.gsub("myvoicemarks-entry-", "");
                    gg.log("This is for VM %s", voiceMarkId);
                    if (source.hasClassName("myvoicemarks-action-listen")) {
                        gg.log("listen action clicked")
                    }
                    else {
                        if (source.hasClassName("myvoicemarks-action-delete")) {
                            gg.log("delete action clicked");
                            this.deleteVoiceMark(voiceMarkId)
                        }
                        else {
                            if (source.hasClassName("myvoicemarks-action-view")) {
                                gg.log("view action clicked");
                                var event = sideBarElement.fire(gg.SideBarEvent.VoiceMarkLinkClicked, {
                                    id: voiceMarkId
                                });
                                gg.log("fired event %o", event)
                            }
                        }
                    }
                }
            }
            else {
                gg.warn("Non-action clicked %s", source)
            }
        },
        getNotificationPreferencesAsHash: function(id, checked){
            var hash = null;
            if (id.startsWith("checkbox-new-hood-vms-notification-")) {
                if (id.endsWith("-email")) {
                    hash = $H({
                        "enable-new-hood-vms-notification-email": checked ? true : false,
                        "new-hood-vms-notification-email-frequency": 1
                    })
                }
                else {
                    if (id.endsWith("-sms")) {
                        hash = $H({
                            "enable-new-hood-vms-notification-sms": checked ? true : false,
                            "new-hood-vms-notification-sms-frequency": 1
                        })
                    }
                    else {
                        if (id.endsWith("-phonecall")) {
                            hash = $H({
                                "enable-new-hood-vms-notification-phonecall": checked ? true : false,
                                "new-hood-vms-notification-phonecall-frequency": 1
                            })
                        }
                    }
                }
            }
            else {
                if (id.startsWith("checkbox-new-fan-notification-")) {
                    if (id.endsWith("-email")) {
                        hash = $H({
                            "enable-new-fan-notification-email": checked ? true : false,
                            "new-fan-notification-email-frequency": 1
                        })
                    }
                    else {
                        if (id.endsWith("-sms")) {
                            hash = $H({
                                "enable-new-fan-notification-sms": checked ? true : false,
                                "new-fan-notification-sms-frequency": 1
                            })
                        }
                        else {
                            if (id.endsWith("-phonecall")) {
                                hash = $H({
                                    "enable-new-fan-notification-phonecall": checked ? true : false,
                                    "new-fan-notification-phonecall-frequency": 1
                                })
                            }
                        }
                    }
                }
                else {
                    if (id.startsWith("checkbox-responses-notification-")) {
                        if (id.endsWith("-email")) {
                            hash = $H({
                                "enable-responses-notification-email": checked ? true : false,
                                "responses-notification-email-frequency": 1
                            })
                        }
                        else {
                            if (id.endsWith("-sms")) {
                                hash = $H({
                                    "enable-responses-notification-sms": checked ? true : false,
                                    "responses-notification-sms-frequency": 1
                                })
                            }
                            else {
                                if (id.endsWith("-phonecall")) {
                                    hash = $H({
                                        "enable-responses-notification-phonecall": checked ? true : false,
                                        "responses-notification-phonecall-frequency": 1
                                    })
                                }
                            }
                        }
                    }
                }
            }
            return hash
        },
        setNotificationPreferences: function(id, checked){
            var parameters = this.getNotificationPreferencesAsHash(id, checked);
            new Ajax.Request(gg.ApiUrl.SetNotificationPreferences, {
                parameters: parameters,
                onSuccess: function(transport){
                    gg.log("Notification preferences successfully set!")
                },
                onFailure: function(transport){
                    gg.error("Notification preferences could not bet set!")
                }
            })
        },
        createCarrierEditor: function(element, voiceUserId){
            var carrierEditor = new Ajax.InPlaceCollectionEditor(element, gg.ApiUrl.SetPhoneCarrier, {
                htmlResponse: false,
                cancelControl: "button",
                collection: carrierCollection,
                clickToEditText: "Click to set carrier",
                highlightcolor: "#fcdf35",
                callback: function(form, value){
                    return String.format("vid=$0&carrierid=$1", voiceUserId, value)
                },
                onComplete: function(transport, element){
                    if (typeof transport !== "undefined") {
                        var apiResponse = transport.responseText.evalJSON(true);
                        if (apiResponse && apiResponse.status === 0) {
                            element.update(apiResponse.carrierName)
                        }
                        else {
                            element.update("Error setting carrier")
                        }
                    }
                }
            });
            return carrierEditor
        },
        createHandsetEditor: function(element, voiceUserId){
            var handsetEditor = new Ajax.InPlaceCollectionEditor(element, gg.ApiUrl.SetPhoneHandset, {
                collection: handsetCollection,
                clickToEditText: "Click to set phone model",
                cancelControl: "button",
                highlightcolor: "#fcdf35",
                callback: function(form, value){
                    return String.format("vid=$0&handsetId=$1", voiceUserId, value)
                },
                onComplete: function(transport, element){
                    if (typeof transport !== "undefined") {
                        var apiResponse = transport.responseText.evalJSON(true);
                        if (apiResponse && apiResponse.status === 0) {
                            element.update(apiResponse.handsetName)
                        }
                        else {
                            element.update("Error setting handset")
                        }
                    }
                }
            });
            return handsetEditor
        },
		
		alertLikeAFox : function() {
			gg.warn("ALERT ALERT ALERT FOX FOX FOX");
		},
				
        populateMyServices: function(accountData, ba){
			var self = this;
            var currentForm = null;
            var forms = new Array();
            var notifications = accountData.notifications;
            try {
                ba('<div id="account-myservices-toggle" class="accordion_toggle"><span>My Twitter Status<\/span><\/div>');
                ba('<div id="account-myservices-content" class="accordion_content">');
                
				// Facebook Connect Linking
				ba('<div id="my-services-facebook-container" class="my-services-container">');
				ba('<div id="myservices-facebook-enable-section">');
				ba('<div class="myservices-service-description">Link your Facebook Account?  This will publish your Voice Marks to Facebook for your friends to listen to and let you Sign In using your Facebook account.<\/div>');
				
				var facebookId = accountData.facebookId;
				if (facebookId && facebookId != null) {
					ba('<div>Unlink your Facey Face Account!<\/div>');			
				}
				else {
					ba('<div id="myservices-facebook-connect-button"><fb:login-button id="facey-face-button" autologoutlink="true" length="long" v="2" onlogin="gg.SideBar.alertLikeAFox()"><\/fb:login-button><\/div>');	
				}
				
				//ba('<div id="myservices-facebook-connect-button"><a href="#" onclick="FB.Connect.requireSession(); return false;id="RES_ID_fb_login" class="fbconnect_login_button FBConnectButton FBConnectButton_Medium"><span id="RES_ID_fb_login_text" class="FBConnectButton_Text">Facey Face</span></a><\/div>');
				
				//ba('<div>Crap crap crap<\/div>');
				
				
				
				//FB.Connect.get_status().waitUntilReady(function(status) {
				//	switch (status) {
				//		case FB.ConnectState.connected:
				//			gg.info("Currently connected to Facey Face");
				//			break;
				//		case FB.ConnectState.appNotAuthorized:
				//			gg.info("Currently this bloody app is not authorized!");
				//			break;
				//		case FB.ConnectState.userNotLoggedIn:
				//			gg.info("The bloody user is not logged in.");
				//			break;
				//	}
				//});
				
				
				ba('<\/div>'); // myservices-facebook-enable-section
				ba('<\/div>'); // my-services-facebook-container
				
				// Twitter Linking
                ba('<div id="myservices-twitter-container" class="myservices-service-container">');
                ba('<iframe id="myservices-twitter-remoting-frame" name="myservices-twitter-remoting-frame" src="about:blank" class="hidden"><\/iframe>');
                
                ba('<div id="myservices-twitter-enable-section">');
				ba('<div class="myservices-service-description">Update your Twitter Status when you post a new Voice Mark? You can stop/start this status update at any time.</div>');
                ba('<form id="myservices-enable-twitter-form" action="$0" method="post">', gg.ApiUrl.EnableTwitter);
                var twitterPreferences = accountData.twitterPreferences;
                var checked = twitterPreferences.twitterEnabled && twitterPreferences.statusUpdateEnabled;
                ba('<input type="checkbox" $0 class="myservices-enable-service-checkbox" id="myservices-enable-twitter-checkbox" name="enableTwitter" \/>', checked ? 'checked="checked"' : '');
                ba('<label class="myservices-enable-label" for="myservices-enable-twitter-checkbox">Enable Twitter<\/label>');
                ba('<\/form>');
                ba('<form id="myservices-twitter-preferences-form" action="https://$0$1" method="post" target="myservices-twitter-remoting-frame">', gg.Environment.ServerRunningOn, gg.ApiUrl.UpdateTwitterPreferences);
                ba('<fieldset id="myservices-twitter-credentials">');
                ba('<table id="myservices-twitter-table">');
                ba('<tbody>');
                ba('<tr>');
                ba('<td>');
                ba('<label for="myservices-twitter-username" class="myservices-usernamepassword-label">Twitter User Name<\/label>');
                ba('<\/td>');
                ba('<td>');
                ba('<input id="myservices-twitter-username" type="text" class="myservices-usernamepassword-inputbox small-left-margin" name="twitterUserName" \/>');
                ba('<\/td>');
                ba('<\/tr>');
                ba('<tr>');
                ba('<td>');
                ba('<label for="myservices-twitter-password" class="myservices-usernamepassword-label">Twitter Password<\/label>');
                ba('<\/td>');
                ba('<td>');
                ba('<input id="myservices-twitter-password" type="password" class="myservices-usernamepassword-inputbox small-left-margin" name="twitterPassword" \/>');
                ba('<\/td>');
                ba('<\/tr>');
                ba('<\/tbody>');
                ba('<\/table>');
                ba('<div id="myservices-twitter-button-container" class="centered-contents">');
				ba('<input id="myservices-twitter-enable" name="enableTwitter" type="hidden"\/>');
				ba('<input id="myservices-twitter-auth-value" name="authValue" type="hidden"\/>');
                ba('<input id="myservices-twitter-link-up-button" type="submit" value="Link me up!" class="centered" \/>');
                ba('<\/div>');
                
                ba('<\/fieldset>');
                ba('<\/form>');
                
                var twitterConnectionClass = "not-connected";
                var connectionMessage = "Not Linked";
                if (twitterPreferences.twitterEnabled && twitterPreferences.statusUpdateEnabled && twitterPreferences.credentialsVerified) {
                    twitterConnectionClass = "connected";
                    connectionMessage = "Linked";
                }
                
                ba('<div id="myservices-twitter-connection-status" class="$0">', twitterPreferences.twitterEnabled ? 'visible' : 'hidden');
                ba('<div id="connection-animation-section">');
                ba('<table class="myservices-connection-animation-table">');
                ba('<tr>');
                ba('<td><img id="myservices-geograffiti-tiny-logo" src="/images/gglogo-tiny-32x32.png"\/><\/td>');
                ba('<td><div id="myservices-connection-animation-container" class="$0">$1<\/div><\/td>', twitterConnectionClass, connectionMessage);
                ba('<td><img id="myservices-twitter-tiny-logo" src="/images/twitter-logo-32x32.png" \/><\/td>');
                ba('<\/tr>');
                ba('<\/table>');
                ba('<\/div>');
                ba('<\/div>');
                
                ba('<\/div>');
                
                ba('<\/div>');
                ba('<\/div>');
            } 
            catch (e) {
                gg.error("EXCEPTION......%o", e)
            }
        },
        
        test: function(e){
        
        },
        
        populateAccountTab: function(){
            try {
                var self = this;
                accountContainer.update(loadingAccountActivityIndicatorMarkup);
                pagingControl.update("");
                var buffer = new gg.StringBuffer();
                var ba = buffer.append.bind(buffer);
                new Ajax.Request(gg.ApiUrl.GetAccountData, {
                    onSuccess: function(response){
                        try {
                            var apiResponse = response.responseText.evalJSON(true);
                            if (apiResponse.status === 0) {
                                self.populateMyProfile(apiResponse.accountData, ba);
                                var voiceUserRecords = self.populateMyPhones(apiResponse.accountData, ba);
                                var notificationForms = self.populateNotifications(apiResponse.accountData, ba);
                                self.populateMyServices(apiResponse.accountData, ba);
                                self.populateMyVoiceMarks(apiResponse.accountData, ba);
                                self.populateMyHood(apiResponse.accountData, ba);
                                self.populateMyFans(apiResponse.accountData, ba);
                                self.populateMyGroups(apiResponse.accountData, ba);
                                
                                accountContainer.update(buffer);
                                var picChangeControl = $("myprofile-pic-change-control");
                                picChangeControl.stopObserving("click");
                                picChangeControl.observe("click", function(e){
                                    e.stop();
                                    $("myprofile-pic-selector").setStyle("display:block;")
                                }
.bind(picChangeControl));
                                var picUploadForm = $("myprofile-pic-select-form");
                                picUploadForm.stopObserving("reset");
                                picUploadForm.observe("reset", function(e){
                                    $("myprofile-pic-selector").setStyle("display:none");
                                    gg.log("user cancel on pic upload")
                                });
                                picUploadForm.stopObserving("submit");
                                picUploadForm.observe("submit", function(e){
                                    try {
                                        var remotingFrame = $("myprofile-remoting-frame");
                                        var profilePicFrame = $("myprofile-pic-frame");
                                        var profilePic = $("myprofile-pic");
                                        profilePicFrame.setStyle("border: 1px solid #ededed");
                                        profilePic.src = "/images/ajax-loader-circle-32x32.gif";
                                        profilePic.setStyle("top: 50%; margin-top:-16px; width:32px; height:32px; left: auto;");
                                        if (remotingFrame.attachEvent) {
                                            remotingFrame.attachEvent("onload", function(){
                                                try {
                                                    var result = remotingFrame.contentWindow.document.body.innerHTML.evalJSON(true);
                                                    if (gg.debug) {
                                                        gg.info("iframe content has finished loading! ----> %o", result)
                                                    }
                                                    $("myprofile-pic-selector").setStyle("display:none");
                                                    profilePic.setStyle("top: 0px; left: 0px; margin-top: 0px; width: auto; height: auto");
                                                    profilePicFrame.setStyle("border-style: none;");
                                                    profilePic.src = String.format("/api/user/$0/pictures/0/thumbnail/medium/?$1", apiResponse.accountData.profile["public"].systemUserId, new Date().getTime());
                                                    gg.info("OK!  Pic source was changed!...if it didn't change then we have a caching issue...refresh page now")
                                                } 
                                                catch (e) {
                                                    gg.error("Error in remoting frame load handler...%o", e)
                                                }
                                            })
                                        }
                                        else {
                                            try {
                                                Event.stopObserving(remotingFrame, "load");
                                                Event.observe(remotingFrame, "load", function(e){
                                                    try {
                                                        e.stop();
                                                        var result = remotingFrame.contentDocument.documentElement.textContent.evalJSON(true);
                                                        if (gg.debug) {
                                                            gg.log("%o", remotingFrame.contentDocument.documentElement.textContent);
                                                            gg.info("iframe content has finished loading! ----> %o", result);
                                                        }
                                                        $("myprofile-pic-selector").setStyle("display:none");
                                                        profilePic.setStyle("top: 0px; left: 0px; margin-top: 0px; width: auto; height: auto");
                                                        profilePicFrame.setStyle("border-style: none;");
                                                        profilePic.src = String.format("/api/user/$0/pictures/0/thumbnail/medium/?$1", apiResponse.accountData.profile["public"].systemUserId, new Date().getTime());
                                                        gg.info("OK!  Pic source was changed!...if it didn't change then we have a caching issue...refresh page now");
                                                    } 
                                                    catch (e) {
                                                        gg.error("Error in remoting frame load handler...%o", e)
                                                    }
                                                });
                                            } 
                                            catch (error1) {
                                                var error = error1;
                                                gg.log("Here we go...got an error...");
                                                for (p in error) {
                                                    gg.log("Here is .... %o", p);
                                                }
                                                gg.log("done with error");
                                            }
                                        }
                                    } 
                                    catch (error2) {
                                        gg.info("Error in hidden form submission...%o", error2);
                                    }
                                }
.bind(picUploadForm));
                                
                                self.createPreferenceInPlaceEditor("myprofile-first-name", "firstname");
                                self.createPreferenceInPlaceEditor("myprofile-last-name", "lastname");
                                self.createPreferenceInPlaceEditor("myprofile-username", "username");
                                self.createPreferenceInPlaceEditor("myprofile-gender", "sex");
                                self.createPreferenceInPlaceEditor("myprofile-city", "city");
                                self.createPreferenceInPlaceEditor("myprofile-state", "state");
                                self.createPreferenceInPlaceEditor("myprofile-postalcode", "postalcode");
                                self.createPreferenceInPlaceEditor("myprofile-country", "country");
                                self.createPreferenceInPlaceEditor("myprofile-birthday", "dob");
                                self.createPreferenceInPlaceEditor("myprofile-email", "email");
                                var phoneTable = $("phone-table");
                                var addPhoneForm = $("addphone-form");
                                addPhoneForm.stopObserving("submit");
                                addPhoneForm.observe("submit", function(e){
                                    e.stop();
                                    gg.info("form submission for add phone!!!");
                                    addPhoneForm.request({
                                        onSuccess: function(transport){
                                            var apiResponse = transport.responseText.evalJSON(true);
                                            if (apiResponse && apiResponse.status === 0) {
                                                var voiceUserId = apiResponse.id;
                                                gg.info("success with add number!...%o", apiResponse);
                                                var row = phoneTable.insertRow(-1);
                                                row.writeAttribute("id", String.format("phone-record-$0", voiceUserId));
                                                var actionCell = row.insertCell(-1);
                                                actionCell.innerHTML = "Delete";
                                                actionCell.writeAttribute("id", String.format("delete-phone-$0", voiceUserId));
                                                actionCell.writeAttribute("class", "myphones-action-delete");
                                                var numberCell = row.insertCell(-1);
                                                numberCell.innerHTML = apiResponse.phoneNumber;
                                                numberCell.writeAttribute("class", "myphones-phone-number");
                                                var statusCell = row.insertCell(-1);
                                                statusCell.innerHTML = "UNVERIFIED";
                                                statusCell.writeAttribute("class", "myphones-phone-number-status myphones-phone-number-status-unverified");
                                                var verifyCell = row.insertCell(-1);
                                                var buttonId = String.format("phone-$0", voiceUserId);
                                                verifyCell.innerHTML = String.format('<input id="$0" name="$1" type="button" value="Verify" />', buttonId, buttonId);
                                                var buttonIdElement = $(buttonId);
                                                buttonIdElement.stopObserving("click");
                                                buttonIdElement.observe("click", self.verifyPhoneButtonClicked.bindAsEventListener(self, voiceUserId));
                                                var carrierCell = $(row.insertCell(-1));
                                                carrierCell.writeAttribute("id", String.format("myphones-carrier-$0", voiceUserId));
                                                carrierCell.writeAttribute("class", "myphones-carrier");
                                                carrierCell.innerHTML = String.format("<div>Click to set Carrier</div>");
                                                var modelCell = $(row.insertCell(-1));
                                                modelCell.writeAttribute("id", String.format("myphones-handset-type-$0", voiceUserId));
                                                modelCell.writeAttribute("class", "myphones-handset-type");
                                                modelCell.innerHTML = String.format("<div>Click to set Model</div>");
                                                self.createCarrierEditor(carrierCell.down(), voiceUserId);
                                                self.createHandsetEditor(modelCell.down(), voiceUserId);
                                                actionCell.stopObserving("click");
                                                actionCell.observe("click", self.deletePhoneNumber.bindAsEventListener(self))
                                            }
                                            else {
                                                gg.error("ERROR submitting add phone form...%o", transport)
                                            }
                                        },
                                        onFailure: function(transport){
                                            gg.error("ERROR submitting add phone form...%o", transport)
                                        }
                                    })
                                });
                                var verifyForm = $("verify-phone-form");
                                carrierCollection = new Array();
                                var carriers = $(apiResponse.accountData.availableCarriers);
                                carriers.each(function(carrier){
                                    var carrierRecord = new Array();
                                    carrierRecord.push(carrier.id);
                                    carrierRecord.push(carrier.name);
                                    carrierCollection.push(carrierRecord)
                                });
                                handsetCollection = new Array();
                                var handsets = $(apiResponse.accountData.availableHandsets);
                                handsets.each(function(handset){
                                    var handsetRecord = new Array();
                                    handsetRecord.push(handset.id);
                                    handsetRecord.push(String.format("$0 $1", handset.vendor, handset.model));
                                    handsetCollection.push(handsetRecord)
                                });
                                gg.log("carrier collection is %o", carrierCollection);
                                gg.log("handset collection is %o", handsetCollection);
                                if (voiceUserRecords) {
                                    voiceUserRecords.each(function(record){
                                        var actionCell = $(String.format("phone-record-$0", record.id)).down();
                                        actionCell.stopObserving("click");
                                        actionCell.observe("click", self.deletePhoneNumber.bindAsEventListener(self));
                                        if (!record.verified) {
                                            var buttonId = String.format("phone-$0", record.id);
                                            var buttonIdElement = $(buttonId);
                                            buttonIdElement.stopObserving("click");
                                            buttonIdElement.observe("click", self.verifyPhoneButtonClicked.bindAsEventListener(self, record.id))
                                        }
                                        var carrierEditorElement = $(String.format("myphones-carrier-$0", record.id)).down();
                                        var carrierEditor = self.createCarrierEditor(carrierEditorElement, record.id);
                                        gg.log("The collection editor is %o", carrierEditor);
                                        var handsetEditorElement = $(String.format("myphones-handset-type-$0", record.id)).down();
                                        var handsetEditor = self.createHandsetEditor(handsetEditorElement, record.id)
                                    })
                                }
                                if (verifyForm) {
                                    verifyForm.stopObserving("submit");
                                    verifyForm.observe("submit", function(e){
                                        e.stop();
                                        verifyForm.request({
                                            onSuccess: function(transport){
                                                var apiResponse = transport.responseText.evalJSON(true);
                                                if (apiResponse.verified) {
                                                    gg.info("success verifying the verification code!...%o", apiResponse);
                                                    $("verify-phone-control").setStyle("display:none");
                                                    var row = $(String.format("phone-record-$0", apiResponse.id));
                                                    var statusCell = row.down().next(1);
                                                    var verifyCell = statusCell.next();
                                                    statusCell.innerHTML = "VERIFIED";
                                                    statusCell.toggleClassName("myphones-phone-number-status-unverified");
                                                    statusCell.toggleClassName("myphones-phone-number-status-verified");
                                                    verifyCell.innerHTML = ""
                                                }
                                                else {
                                                    gg.error("Wrong verification code!!!  %o", apiResponse);
                                                    $("verify-phone-control").setStyle("display:none")
                                                }
                                            },
                                            onFailure: function(transport){
                                                gg.error("failure verifying the verification code...%o", transport)
                                            }
                                        })
                                    })
                                }
                                var myGroupsDeleteActions = $$(".mygroups-action-leave");
                                if (myGroupsDeleteActions) {
                                    myGroupsDeleteActions.each(function(deleteAction){
                                        deleteAction.stopObserving("click");
                                        deleteAction.observe("click", function(e){
                                            e.stop();
                                            var groupId = deleteAction.identify().gsub("mygroups-action-leave-", "");
                                            var parameters = {
                                                gid: groupId
                                            };
                                            var tableElement = $("mygroups-table");
                                            var groupRow = $(String.format("mygroups-group-$0", groupId));
                                            new Ajax.Request(gg.ApiUrl.LeaveGroup, {
                                                parameters: $H(parameters),
                                                onSuccess: function(transport){
                                                    var apiResponse = transport.responseText.evalJSON(true);
                                                    if (apiResponse && apiResponse.status === 0) {
                                                        groupRow.remove()
                                                    }
                                                },
                                                onFailure: function(transport){
                                                }
                                            })
                                        })
                                    })
                                }
                                $$('input[type="checkbox"][class="notification-checkbox"]').each(function(checkbox){
                                    gg.log("iterating... %o", checkbox);
                                    var checked = checkbox.checked;
                                    checkbox.stopObserving("click");
                                    checkbox.observe("click", function(e){
                                        var id = e.element().identify();
                                        gg.log("The checkbox being clicked is %s", id);
                                        var currentlyChecked = e.element().checked;
                                        self.setNotificationPreferences(id, currentlyChecked);
                                        if (!currentlyChecked) {
                                        }
                                        else {
                                        }
                                    })
                                });
								
								var accountServicesAccordion = $("account-container");
								accountServicesAccordion.observe("geograffiti:sectionExpanded", function(e) {
									gg.log("My Services Expanded");
									FB.XFBML.Host.parseDomElement(e.element()); 
								});
                                
                                var enableTwitterCheckbox = $("myservices-enable-twitter-checkbox");
                                var enableTwitterForm = $("myservices-enable-twitter-form");
                                var twitterPreferencesForm = $("myservices-twitter-preferences-form");
                                var animationContainer = $("myservices-connection-animation-container");
                                if (enableTwitterCheckbox.checked) {
                                    twitterPreferencesForm.select("input").each(function(inputControl){
                                        inputControl.enable();
                                    });
                                }
                                else {
                                    twitterPreferencesForm.select("input").each(function(inputControl){
                                        inputControl.disable();
                                    });
                                }
                                enableTwitterCheckbox.stopObserving("click");
                                enableTwitterCheckbox.observe("click", function(e){
                                    if (enableTwitterCheckbox.checked) {
                                        $("myservices-twitter-connection-status").writeAttribute("class", "visible");
                                        twitterPreferencesForm.select("input").each(function(inputControl){
                                            inputControl.enable();
                                        });
                                    }
                                    else {
                                        twitterPreferencesForm.select("input").each(function(inputControl){
                                            inputControl.disable();
                                        });
                                    }
                                    
                                    animationContainer.update("");
                                    animationContainer.writeAttribute("class", "connecting");
                                    enableTwitterForm.request({
                                        onSuccess: function(transport){
                                            gg.info("SUCCESS sending enable twitter request %o", transport);
                                            var apiResponse = transport.responseText.evalJSON(true);
                                            if (apiResponse) {
                                                if (apiResponse.status === 0) {
                                                    var prefs = apiResponse.twitterPreferences;
                                                    if (prefs.twitterEnabled && prefs.statusUpdateEnabled && prefs.credentialsVerified) {
                                                        animationContainer.writeAttribute("class", "connected");
                                                        animationContainer.update("Linked");
                                                    }
                                                    else {
                                                        animationContainer.writeAttribute("class", "not-connected");
                                                        animationContainer.update("Not Linked");
                                                    }
                                                }
                                                else {
                                                    gg.error("API Error sending enable twitter request %o with status=%d and details=%o", transport, apiResponse.status, apiResponse.details);
                                                    animationContainer.writeAttribute("class", "not-connected");
                                                    animationContainer.update("Not Linked");
                                                }
                                            }
                                        },
                                        onFailure: function(transport){
                                            gg.error("Failed to send enable twitter request %o", transport);
                                            animationContainer.writeAttribute("class", "not-connected");
                                            animationContainer.update("Not Linked");
                                        }
                                    });
                                });
                                
                                twitterPreferencesForm.observe("submit", function(e){
                                    animationContainer.update("");
                                    animationContainer.writeAttribute("class", "connecting");
                                    var twitterUserName = $F(twitterPreferencesForm["twitterUserName"]);
                                    var twitterPassword = $F(twitterPreferencesForm["twitterPassword"]);
                                    var authValue = base64encode(String.format("$0:$1", twitterUserName, twitterPassword));
									var enable = enableTwitterCheckbox.checked;
									$(twitterPreferencesForm["authValue"]).writeAttribute("value", authValue);
									$(twitterPreferencesForm["enableTwitter"]).writeAttribute("value", "true");
									//$(twitterPreferencesForm["twitterUserName"]).writeAttribute("value", "");
									//$(twitterPreferencesForm["twitterPassword"]).writeAttribute("value", "");
                                    var remotingFrame = $("myservices-twitter-remoting-frame");
                                    if (remotingFrame) {
                                        try {
                                            if (false) {
												gg.log("attaching the onload event for IE");
                                                remotingFrame.attachEvent("onload", function() {
													gg.log("OK... frame is done loading... let's seee... send ajax");
													try {
														var url = String.format("$0?$1", gg.ApiUrl.GetTwitterPreferences, new Date().getTime());
														new Ajax.Request(gg.ApiUrl.GetTwitterPreferences, {
															method: "get",
															onSuccess: function(transport){
																gg.log("ok... got success");
																var apiResponse = transport.responseText.evalJSON(true);
																gg.log("hrmm...what did we get?...%o", apiResponse);
																if (apiResponse) {
																	if (apiResponse.status === 0) {
																		var prefs = apiResponse.twitterPreferences;
																		if (prefs.twitterEnabled && prefs.statusUpdateEnabled && prefs.credentialsVerified) {
																			animationContainer.writeAttribute("class", "connected");
																			animationContainer.update("Linked");
																		}
																		else {
																			animationContainer.writeAttribute("class", "not-connected");
																			animationContainer.update("Not Linked");
																		}
																	}
																	else {
																		gg.error("API Error sending enable twitter request %o with status=%d and details=%o", transport, apiResponse.status, apiResponse.details);
																		animationContainer.writeAttribute("class", "not-connected");
																		animationContainer.update("Not Linked");
																	}
																}
															},
															onFailure: function(transport){
																gg.error("%o", transport);
																animationContainer.writeAttribute("class", "not-connected");
																animationContainer.update("Not Linked");
															}
														});
													}
													catch (e) {
														gg.log("There's an error ... %o", e);
													}
                                                });
												gg.log("done attaching event");
                                            }
                                            else {
                                                Event.stopObserving(remotingFrame, "load");
                                                Event.observe(remotingFrame, "load", function(e){
													gg.log("OK... frame is done loading... let's seee... send ajax");
													var url = String.format("$0?$1", gg.ApiUrl.GetTwitterPreferences, new Date().getTime());
                                                	new Ajax.Request(url, {
                                                        method: "get",
                                                        onSuccess: function(transport){
															gg.log("ok... got success");
                                                            var apiResponse = transport.responseText.evalJSON(true);
															gg.log("hrmm...what did we get?...%o", apiResponse);
                                                            if (apiResponse) {
                                                                if (apiResponse.status === 0) {
                                                                    var prefs = apiResponse.twitterPreferences;
                                                                    if (prefs.twitterEnabled && prefs.statusUpdateEnabled && prefs.credentialsVerified) {
                                                                        animationContainer.writeAttribute("class", "connected");
                                                                        animationContainer.update("Linked");
                                                                    }
                                                                    else {
                                                                        animationContainer.writeAttribute("class", "not-connected");
                                                                        animationContainer.update("Not Linked");
                                                                    }
                                                                }
                                                                else {
                                                                    gg.error("API Error sending enable twitter request %o with status=%d and details=%o", transport, apiResponse.status, apiResponse.details);
                                                                    animationContainer.writeAttribute("class", "not-connected");
                                                                    animationContainer.update("Not Linked");
                                                                }
                                                            }
                                                        },
                                                        onFailure: function(transport){
                                                        	gg.error("%o", transport);
                                            				animationContainer.writeAttribute("class", "not-connected");
                                            				animationContainer.update("Not Linked");
                                                        }
                                                    });
                                                });
                                            }
                                        } 
                                        catch (e) {
											gg.log("something happened...%o", e);
                                            gg.error(e);
                                        }
                                    }
                                });
                                
                                try {
                                    var myVoiceMarksTable = $("myvoicemarks-table");
                                    myVoiceMarksTable.stopObserving("click");
                                    myVoiceMarksTable.observe("click", self.myVoiceMarksItemClicked.bind(self));
                                    var myHoodTable = $("myhood-table");
                                    myHoodTable.stopObserving("click");
                                    myHoodTable.observe("click", self.myHoodItemClicked.bind(self));
                                    var myFansTable = $("myfans-table");
                                    myFansTable.stopObserving("click");
                                    myFansTable.observe("click", self.myFansItemClicked.bind(self))
                                } 
                                catch (e) {
                                    gg.error("filthy error...%o", e)
                                }
                                myAccountAccordion = new accordion("account-container");
                                if (gg.debug) {
                                    gg.info("Created accordion %o", myAccountAccordion)
                                }
                                myAccountAccordion.activate($$("#account-container .accordion_toggle")[0]);
                                if (gg.debug) {
                                    gg.info("activated the accordion")
                                }
                                sideBarElement.fire(gg.SideBarEvent.MyAccountReady)
                            }
                            else {
                            }
                        } 
                        catch (e) {
                            gg.error("SHITTTTT %o", e)
                        }
                    },
                    onFailure: function(response){
                    }
                })
            } 
            catch (e) {
                gg.error("SHIT %o", e)
            }
        },
        userLoggedIn: function(e){
            this.populateAccountTab()
        },
        userDidNotLogIn: function(e){
            this.transitionToStateZero()
        },
        sendUserToLoginScreen: function(){
            document.observe(gg.UserEvent.UserLoggedIn, this.userLoggedIn.bindAsEventListener(this));
            document.observe(gg.UserEvent.UserDidNotLogIn, this.userDidNotLogIn.bindAsEventListener(this));
            gg.userWantsToLogIn()
        },
        createGroupEntry: function(group){
            var entry = new gg.StringBuffer();
            var ba = entry.append.bind(entry);
            ba('<div id="group-toggle-$0" class="groups_accordion_toggle">$1</div>', group.id, group.name);
            ba('<div id="group-content-$0" class="groups_accordion_content">$1</div>', group.id, loadingGroupInfoActivityIndicatorMarkup);
            return entry.toString()
        },
        generateGroupMemberEntry: function(member){
            var buffer = new gg.StringBuffer();
            var ba = buffer.append.bind(buffer);
            ba('<tr id="group-member-entry-$0">', member.id);
            ba('<td class="group-memberlist-profilepic"><img src="/api/user/$0/pictures/0/thumbnail/xtiny/?$1" alt="Profile Pic for $2" class="group-memberlist-profilepic-image" /></td>', member.id, new Date().getTime(), member.userName);
            ba('<td class="group-memberlist-membername"><span id="group-member-firstlast-$0">$1 $2</span></td>', member.id, member.firstName, member.lastName);
            ba('<td class="group-memberlist-aka"><span class="group-member-aka">aka</span></td>');
            ba('<td class="group-memberlist-username"><span id="group-member-username-$0">$1</span></td>', member.id, member.userName);
            ba("</tr>");
            return buffer.toString()
        },
        generateGroupInfoContent: function(groupInfo){
            var self = this;
            var buffer = new gg.StringBuffer();
            var ba = buffer.append.bind(buffer);
            ba('<div id="group-description-$0" class="group-description">', groupInfo.id);
            ba(groupInfo.description);
            ba("</div>");
            ba('<div id="group-actions-$0" class="group-actions-container">', groupInfo.id);
            ba('<a href="$0?gid=$1" class="group-action group-action-join">Join Group</a>', gg.ApiUrl.JoinGroup, groupInfo.id);
            ba('<a id="group-action-view-voicemarks-$0" href="$1/$2" class="group-action group-action-view-voicemarks">View Group\'s Voice Marks!</a>', groupInfo.id, gg.SEOFriendlyUrl.ViewGroupMap, groupInfo.id);
            ba("</div>");
            ba('<div id="group-membercount-container-$0" class="group-membercount-container">', groupInfo.id);
            ba('<div id="group-membercount-label-$0" class="group-membercount-label">...has $1 members</div>', groupInfo.id, groupInfo.memberCount);
            ba("</div>");
            ba('<table id="group-memberlist-$0" class="group-memberlist-table">', groupInfo.id);
            var members = groupInfo.members;
            if (members) {
                members.each(function(member){
                    ba(self.generateGroupMemberEntry(member))
                })
            }
            ba("</table>");
            return buffer.toString()
        },
        createNeedLoginTipContent: function(message){
            var buffer = new gg.StringBuffer();
            var ba = buffer.append.bind(buffer);
            ba('<p class="need-login-tip-message">$0</p>', message);
            ba('<div class="need-login-tip-link">Login!</div>');
            return buffer.toString()
        },
        createNeedLoginTip: function(element, options){
            var defaultOptions = $H({
                message: "You need to login to perform this action.",
                onLogin: gg.EmptyFunction,
                onNoLogin: gg.EmptyFunction
            });
            var mergedOptions = defaultOptions.merge(options);
            try {
                var self = this;
                var targetElement = $(element);
                var tip = null;
                var noLoginHandler = null;
                document.stopObserving(gg.UserEvent.UserLoggedIn);
                var loginHandler = document.observe(gg.UserEvent.UserLoggedIn, function(e){
                    mergedOptions.get("onLogin")();
                    document.stopObserving(gg.UserEvent.UserLoggedIn, loginHandler);
                    document.stopObserving(gg.UserEvent.UserDidNotLogIn, noLoginHandler)
                });
                document.stopObserving(gg.UserEvent.UserDidNotLogIn);
                noLoginHandler = document.observe(gg.UserEvent.UserDidNotLogIn, function(e){
                    mergedOptions.get("onNoLogin")();
                    document.stopObserving(gg.UserEvent.UserLoggedIn, loginHandler);
                    document.stopObserving(gg.UserEvent.UserDidNotLogIn, noLoginHandler)
                });
                targetElement.stopObserving("prototip:shown");
                targetElement.observe("prototip:shown", function(e){
                    try {
                        e.stop();
                        var prototip = e.element().prototip;
                        var loginTipLink = $$(".need-login-tip-link")[0];
                        loginTipLink.stopObserving("click");
                        loginTipLink.observe("click", function(e){
                            e.stop();
                            if (prototip) {
                                prototip.remove();
                                targetElement.stopObserving("prototip:shown");
                                targetElement.stopObserving("prototip:hidden")
                            }
                            gg.userWantsToLogIn()
                        })
                    } 
                    catch (e) {
                        gg.error("error with prototip shown handler %o", e)
                    }
                });
                targetElement.stopObserving("prototip:hidden");
                targetElement.observe("prototip:hidden", function(e){
                    e.stop();
                    gg.log("prototip was hidden - createNeedLoginTip");
                    if (tip) {
                        gg.log("removing the tip");
                        var prototip = e.element().prototip;
                        if (prototip) {
                            prototip.remove();
                            targetElement.stopObserving("prototip:shown");
                            targetElement.stopObserving("prototip:hidden")
                        }
                    }
                });
                tip = new Tip(targetElement, self.createNeedLoginTipContent(mergedOptions.get("message")), {
                    style: "geograffiti",
                    hook: {
                        target: "bottomMiddle",
                        tip: "topMiddle"
                    },
                    offset: {
                        x: 0,
                        y: -10
                    },
                    stem: "topMiddle",
                    title: "Login Needed"
                });
                gg.log("tip created with %o", tip);
                tip.target.prototip.show()
            } 
            catch (e) {
                gg.error("Error in createNeedLoginTip - %o", e)
            }
        },
        updateAndFlashElement: function(element, restore, content, contentClass){
            var targetElement = $(element);
            var previousContent = restore ? targetElement.innerHTML : null;
            targetElement.update(content);
            targetElement.toggleClassName(contentClass);
            targetElement.pulsate({
                afterFinish: function(e){
                    if (restore) {
                        targetElement.update(previousContent);
                        targetElement.toggleClassName(contentClass)
                    }
                }
            })
        },
        sendJoinGroupRequest: function(url, elementToUpdate){
            var self = this;
            new Ajax.Request(url, {
                evalJSON: true,
                onSuccess: function(transport){
                    gg.log("Success joining group...%o", transport);
                    var apiResponse = transport.responseText.evalJSON(true);
                    if (apiResponse.status !== 0) {
                        self.updateAndFlashElement(elementToUpdate, true, "Error joining group.", "action-join-group-error")
                    }
                    else {
                        self.updateAndFlashElement(elementToUpdate, true, "You are now a member!", "action-join-group-success")
                    }
                },
                onFailure: function(transport){
                    self.updateAndFlashElement(elementToUpdate, true, "Error joining group.", "action-join-group-error")
                }
            })
        },
        populateCommunityTab: function(){
            var self = this;
            communityContainer.update(loadingCommunityActivityIndicatorMarkup);
            pagingControl.update("");
            var buffer = new gg.StringBuffer();
            var ba = buffer.append.bind(buffer);
            new Ajax.Request(gg.ApiUrl.GetGroups, {
                onSuccess: function(response){
                    var apiResponse = response.responseText.evalJSON(true);
                    if (apiResponse.status === 0) {
                        var groups = apiResponse.groups;
                        ba('<div id="groups-list">');
                        if (groups) {
                            for (var i = 0, limit = groups.length; i < limit; ++i) {
                                var currentGroup = groups[i];
                                ba(self.createGroupEntry(currentGroup))
                            }
                        }
                        ba("</div>");
                        var viewGroupsToggle = new Element("div", {
                            "class": "accordion_toggle"
                        }).update("View Groups");
                        var viewGroupsContent = new Element("div", {
                            id: "view-groups-content",
                            "class": "accordion_content"
                        });
                        var createGroupToggle = new Element("div", {
                            "class": "accordion_toggle"
                        }).update("Create Group");
                        var createGroupContent = new Element("div", {
                            id: "create-group-content",
                            "class": "accordion_content "
                        });
                        communityContainer.update(viewGroupsToggle).insert({
                            bottom: viewGroupsContent
                        }).insert({
                            bottom: createGroupToggle
                        }).insert({
                            bottom: createGroupContent
                        });
                        viewGroupsContent.update(buffer);
                        new accordion("groups-list", groupsAccordionOptions);
                        var groupsList = $("groups-list");
                        groupsList.stopObserving("geograffiti:sectionExpanded");
                        groupsList.observe("geograffiti:sectionExpanded", function(e){
                            e.stop();
                            gg.log("section expanded!!!--->%o", e.memo);
                            var groupId = e.memo.section.identify().gsub("group-content-", "");
                            new Ajax.Request(gg.ApiUrl.GetGroupInfo, {
                                parameters: $H({
                                    gid: groupId
                                }),
                                onSuccess: function(transport){
                                    var apiResponse = transport.responseText.evalJSON(true);
                                    if (apiResponse && apiResponse.status === 0) {
                                        gg.log("Get Group Info response is %o", apiResponse);
                                        var groupContentDiv = $(String.format("group-content-$0", groupId));
                                        groupContentDiv.innerHTML = self.generateGroupInfoContent(apiResponse.groupInfo)
                                    }
                                    else {
                                        gg.error("ERROR %o", transport)
                                    }
                                },
                                onFailure: function(transport){
                                    gg.error("ERROR %o", transport)
                                }
                            })
                        });
                        viewGroupsContent.stopObserving("click");
                        viewGroupsContent.observe("click", function(e){
                            e.stop();
                            var source = e.element();
                            var url = source.getAttribute("href");
                            if (url != null) {
                                if (source.hasClassName("group-action-join")) {
                                    gg.log("The URL is %s", url);
                                    if (!gg.userLoggedIn()) {
                                        self.createNeedLoginTip(source, {
                                            message: "You need to be logged in to join a group.",
                                            onLogin: function(){
                                                self.sendJoinGroupRequest(url, source)
                                            },
                                            onNoLogin: function(){
                                                gg.info("Did not login!!")
                                            }
                                        })
                                    }
                                    else {
                                        self.sendJoinGroupRequest(url, source)
                                    }
                                }
                                else {
                                    if (source.hasClassName("group-action-view-voicemarks")) {
                                        var id = source.identify().gsub("group-action-view-voicemarks-", "");
                                        sideBarElement.fire(gg.SideBarEvent.ViewGroupVoiceMarksLinkClicked, {
                                            id: id
                                        })
                                    }
                                }
                            }
                            else {
                                var sourceId = e.element().identify();
                                gg.log("Group Member table clicked with source=%s", sourceId);
                                if (sourceId.startsWith("group-member-username-")) {
                                    var systemUserId = sourceId.gsub("group-member-username-", "");
                                    sideBarElement.fire(gg.SideBarEvent.ViewProfileLinkClicked, {
                                        id: systemUserId
                                    })
                                }
                                else {
                                    if (sourceId.startsWith("group-member-firstlast-")) {
                                        var systemUserId = sourceId.gsub("group-member-firstlast-", "");
                                        sideBarElement.fire(gg.SideBarEvent.ViewProfileLinkClicked, {
                                            id: systemUserId
                                        })
                                    }
                                    else {
                                        gg.log("source is....%s", sourceId)
                                    }
                                }
                            }
                        });
                        gg.log("Coommunity container is %o", communityContainer);
                        var communityAccordion = new accordion(communityContainer.identify());
                        communityContainer.stopObserving("geograffiti:sectionExpanded");
                        communityContainer.observe("geograffiti:sectionExpanded", function(e){
                            gg.log("Hello...search results container expand....%o", e);
                            e.stop();
                            var sectionId = $(e.memo.section).identify();
                            var showLoginTip = false;
                            var toggle = null;
                            if (sectionId === "create-group-content" && !gg.userLoggedIn()) {
                                try {
                                    showLoginTip = true;
                                    toggle = e.memo.section.previous();
                                    gg.log("the toggle is %o", toggle);
                                    communityAccordion.activate.bind(communityAccordion).defer(toggle);
                                    self.createNeedLoginTip(toggle, {
                                        message: "You must be logged in to create a group.",
                                        onLogin: function(){
                                            gg.info("lLLLogged in!!!!");
                                            communityAccordion.activate.bind(communityAccordion).defer(toggle)
                                        },
                                        onNoLogin: function(){
                                            gg.info("DID NOT LOGIN!")
                                        }
                                    })
                                } 
                                catch (e) {
                                    gg.error("FUCK %o", e)
                                }
                            }
                            viewGroupsContent.update(loadingLatestGroupsActivityIndicatorMarkup);
                            new Ajax.Request(gg.ApiUrl.GetGroups, {
                                onSuccess: function(response){
                                    var apiResponse = response.responseText.evalJSON(true);
                                    if (apiResponse.status === 0) {
                                        var groups = apiResponse.groups;
                                        buffer.clear();
                                        ba('<div id="groups-list">');
                                        if (groups) {
                                            for (var i = 0, limit = groups.length; i < limit; ++i) {
                                                var currentGroup = groups[i];
                                                ba(self.createGroupEntry(currentGroup))
                                            }
                                        }
                                        ba("</div>");
                                        viewGroupsContent.update(buffer);
                                        new accordion("groups-list", groupsAccordionOptions);
                                        var groupsList = $("groups-list");
                                        groupsList.stopObserving("geograffiti:sectionExpanded");
                                        groupsList.observe("geograffiti:sectionExpanded", function(e){
                                            e.stop();
                                            gg.log("Section expanded-----> %o", e.memo);
                                            var groupId = e.memo.section.identify().gsub("group-content-", "");
                                            new Ajax.Request(gg.ApiUrl.GetGroupInfo, {
                                                parameters: $H({
                                                    gid: groupId
                                                }),
                                                onSuccess: function(transport){
                                                    var apiResponse = transport.responseText.evalJSON(true);
                                                    if (apiResponse && apiResponse.status === 0) {
                                                        gg.log("Get Group Info response is %o", apiResponse);
                                                        var groupContentDiv = $(String.format("group-content-$0", groupId));
                                                        groupContentDiv.innerHTML = self.generateGroupInfoContent(apiResponse.groupInfo)
                                                    }
                                                    else {
                                                        gg.error("ERROR %o", transport)
                                                    }
                                                },
                                                onFailure: function(transport){
                                                    gg.error("ERROR %o", transport)
                                                }
                                            })
                                        })
                                    }
                                },
                                onFailure: function(response){
                                    gg.error("Error fetching groups...%o", e)
                                }
                            })
                        });
                        buffer.clear();
                        ba('<div id="create-group-control">');
                        ba('<form id="create-group-form" name="create-group-form" action="$0">', gg.ApiUrl.CreateGroup);
                        ba('<label id="group-name-label" class="create-group-input-label" for="group-name" class="block">Group Name</label>');
                        ba('<input id="group-name" name="name" type="text" class="block" />');
                        ba('<label id="group-description-label" class="create-group-input-label" for="group-description" class="block">Group Description</label>');
                        ba('<textarea id="group-description" name="description" class="block"></textarea>');
                        ba('<input id="create-group-button" name="create-group-button" value="Create" type="submit" class="block"/>');
                        ba('<div id="create-group-status-message"></div>');
                        ba("</form>");
                        ba("</div>");
                        createGroupContent.update(buffer);
                        var form = $("create-group-form");
                        form.stopObserving("submit");
                        form.observe("submit", function(e){
                            e.stop();
                            form.request({
                                onSuccess: function(transport){
                                    self.updateAndFlashElement($("create-group-status-message"), true, "Group Created!", "create-group-success")
                                },
                                onFailure: function(transport){
                                    self.updateAndFlashElement($("create-group-status-message"), true, "Error Creating Group", "create-group-failure")
                                }
                            })
                        }
.bind(form))
                    }
                    else {
                        gg.error("Error with GetGroups: %o %d %s", response, apiResponse.status, apiResponse.details)
                    }
                },
                onFailure: function(response){
                    gg.error("Error with GetGroups: %o", response)
                }
            })
        },
        updateSideBar: function(resultsOn, accountOn, communityOn, extend){
            if (resultsOn) {
                $("sidebar-tab-results").addClassName("sidebar-tab-results-active");
                searchResultsContainer.show();
                searchResultsContainer.setStyle("width:100%")
            }
            else {
                $("sidebar-tab-results").removeClassName("sidebar-tab-results-active");
                searchResultsContainer.hide()
            }
            if (accountOn) {
                $("sidebar-tab-account").addClassName("sidebar-tab-account-active");
                accountContainer.show();
                accountContainer.setStyle("width:100%")
            }
            else {
                $("sidebar-tab-account").removeClassName("sidebar-tab-account-active");
                accountContainer.hide()
            }
            if (communityOn) {
                $("sidebar-tab-community").addClassName("sidebar-tab-community-active");
                communityContainer.show();
                communityContainer.setStyle("width:100%")
            }
            else {
                $("sidebar-tab-community").removeClassName("sidebar-tab-community-active");
                communityContainer.hide()
            }
            if (extend) {
                if (!isExtended) {
                    this.extend()
                }
            }
            else {
                if (isExtended) {
                    this.collapse()
                }
            }
        },
        transitionToStateZero: function(){
            gg.log("transitioning to state 0 for tab and this=%o", this);
            currentTabState = TabState.Zero;
            this.updateSideBar(true, false, false, true)
        },
        transitionToStateOne: function(){
            gg.log("transitioning to state 1 for tab");
            currentTabState = TabState.One;
            this.updateSideBar(true, false, false, false)
        },
        transitionToStateTwo: function(){
            gg.log("transitioning to state 2 for tab");
            currentTabState = TabState.Two;
            this.updateSideBar(false, true, false, true);
            if (gg.userLoggedIn()) {
                this.populateAccountTab()
            }
            else {
                this.sendUserToLoginScreen()
            }
        },
        transitionToStateThree: function(){
            gg.log("transitioning to state 3 for tab");
            currentTabState = TabState.Three;
            this.updateSideBar(false, false, true, true);
            this.populateCommunityTab()
        },
        transitionToStateFour: function(){
            gg.log("transitioning to state 4 for tab");
            currentTabState = TabState.Four;
            this.updateSideBar(false, false, true, false)
        },
        transitionToStateFive: function(){
            gg.log("transitioning to state 5 for tab");
            currentTabState = TabState.Five;
            this.updateSideBar(false, true, false, false)
        },
        handleStateZero: function(tab){
            gg.log("handling state 0 for tab %o", tab);
            var id = tab.identify();
            if (id === "sidebar-tab-results") {
                this.transitionToStateOne()
            }
            else {
                if (id === "sidebar-tab-account") {
                    this.transitionToStateTwo()
                }
                else {
                    if (id === "sidebar-tab-community") {
                        this.transitionToStateThree()
                    }
                    else {
                        gg.warn("handleStateZero - tab clicked is %s", id)
                    }
                }
            }
        },
        handleStateOne: function(tab){
            gg.log("handling state 1 for tab %o", tab);
            var id = tab.identify();
            if (id === "sidebar-tab-results") {
                this.transitionToStateZero()
            }
            else {
                if (id === "sidebar-tab-account") {
                    this.transitionToStateTwo()
                }
                else {
                    if (id === "sidebar-tab-community") {
                        this.transitionToStateThree()
                    }
                    else {
                        gg.warn("handleStateZero - tab clicked is %s", id)
                    }
                }
            }
        },
        handleStateTwo: function(tab){
            gg.log("handling state 2 for tab %o", tab);
            var id = tab.identify();
            if (id === "sidebar-tab-results") {
                this.transitionToStateZero()
            }
            else {
                if (id === "sidebar-tab-account") {
                    this.transitionToStateFive()
                }
                else {
                    if (id === "sidebar-tab-community") {
                        this.transitionToStateThree()
                    }
                    else {
                        gg.warn("handleStateZero - tab clicked is %s", id)
                    }
                }
            }
        },
        handleStateThree: function(tab){
            gg.log("handling state 3 for tab %o", tab);
            var id = tab.identify();
            if (id === "sidebar-tab-results") {
                this.transitionToStateZero()
            }
            else {
                if (id === "sidebar-tab-account") {
                    this.transitionToStateTwo()
                }
                else {
                    if (id === "sidebar-tab-community") {
                        this.transitionToStateFour()
                    }
                    else {
                        gg.warn("handleStateZero - tab clicked is %s", id)
                    }
                }
            }
        },
        handleStateFour: function(tab){
            gg.log("handling state 4 for tab %o", tab);
            var id = tab.identify();
            if (id === "sidebar-tab-results") {
                this.transitionToStateZero()
            }
            else {
                if (id === "sidebar-tab-account") {
                    this.transitionToStateTwo()
                }
                else {
                    if (id === "sidebar-tab-community") {
                        this.transitionToStateThree()
                    }
                    else {
                        gg.warn("handleStateZero - tab clicked is %s", id)
                    }
                }
            }
        },
        handleStateFive: function(tab){
            gg.log("handling state 5 for tab %o", tab);
            var id = tab.identify();
            if (id === "sidebar-tab-results") {
                this.transitionToStateZero()
            }
            else {
                if (id === "sidebar-tab-account") {
                    this.transitionToStateTwo()
                }
                else {
                    if (id === "sidebar-tab-community") {
                        this.transitionToStateThree()
                    }
                    else {
                        gg.warn("handleStateZero - tab clicked is %s", id)
                    }
                }
            }
        },
        tabClicked: function(e){
            try {
                if (gg.debug) {
                    gg.log("Tab Clicked with %o", e)
                }
                var tab = e.element();
                switch (currentTabState) {
                    case TabState.Zero:
                        this.handleStateZero(tab);
                        break;
                    case TabState.One:
                        this.handleStateOne(tab);
                        break;
                    case TabState.Two:
                        this.handleStateTwo(tab);
                        break;
                    case TabState.Three:
                        this.handleStateThree(tab);
                        break;
                    case TabState.Four:
                        this.handleStateFour(tab);
                        break;
                    case TabState.Five:
                        this.handleStateFive(tab);
                        break;
                    default:
                        gg.warn("tabClicked - invalid current state %d ", currentTabState);
                        break
                }
            } 
            catch (e) {
                gg.error("tabClicked error - %o", e)
            }
        },
		simulateTabClicked : function(tab) {
			switch (currentTabState) {
                    case TabState.Zero:
                        this.handleStateZero(tab);
                        break;
                    case TabState.One:
                        this.handleStateOne(tab);
                        break;
                    case TabState.Two:
                        this.handleStateTwo(tab);
                        break;
                    case TabState.Three:
                        this.handleStateThree(tab);
                        break;
                    case TabState.Four:
                        this.handleStateFour(tab);
                        break;
                    case TabState.Five:
                        this.handleStateFive(tab);
                        break;
                    default:
                        gg.warn("tabClicked - invalid current state %d ", currentTabState);
                        break
                }
		},
        initialize: function(active, resize, options){
            var self = this;
            activeElement = $(active);
            elementToResize = $(resize);
            sideBarElement = $("sidebar");
            pagingControl = $("pagingcontrol");
            sideBarContent = $("sidebarcontent");
            filterBarElement = $("filterbar-container");
            contentContainer = $("content-container");
            if (typeof options !== "undefined") {
                self.applyOptions(options)
            }
            searchResultsContainer = new Element("div", {
                id: "search-results-container"
            });
            accountContainer = new Element("div", {
                id: "account-container"
            });
            communityContainer = new Element("div", {
                id: "community-container"
            });
            searchResultsContainer.setStyle("position:absolute;left:0px;top:0px;width:100%");
            accountContainer.setStyle("position:absolute;left:0px;top:0px:width:100%");
            communityContainer.setStyle("position:absolute;left:0px;top:0px:width:100%");
            contentContainer.insert(searchResultsContainer);
            contentContainer.insert(accountContainer);
            contentContainer.insert(communityContainer);
            var tabs = $("sidebar-tabs").select(".sidebar-tab");
            tabs.each(function(tab){
                tab.observe("click", self.tabClicked.bindAsEventListener(self))
            });
            Event.observe(window, "resize", function(e){
                var options = {
                    height: $("viewport").getHeight() - $("toparea").getHeight() + 55
                };
                self.applyOptions(options)
            });
            var searcher = $("searcher");
            searcher.observe(gg.SearcherEvent.GoingToSearch, self.searcherGoingToSearch.bindAsEventListener(self));
            searcher.observe(gg.SearcherEvent.SearchStarted, self.searcherSearchStarted.bindAsEventListener(self));
            searcher.observe(gg.SearcherEvent.SearchCompleted, self.searcherSearchCompleted.bindAsEventListener(self));
            searcher.observe(gg.SearcherEvent.SearchCompletedWithFailure, self.searcherSearchCompletedWithFailure.bindAsEventListener(self));
            document.observe(gg.UserEvent.UserLoggedOut, function(e){
                self.transitionToStateZero()
            });
            document.observe(gg.MapEvent.ShowMyPhonesRequested, function(e){
                sideBarElement.observe(gg.SideBarEvent.MyAccountReady, function(e){
                    gg.log("i will activate phones now!");
                    gg.log("accordion is %o", myAccountAccordion);
                    myAccountAccordion.activate.bind(myAccountAccordion).delay(1, $$("#account-container .accordion_toggle")[1])
                });
                self.transitionToStateTwo()
            })
        },
        searcherGoingToSearch: function(e){
            searchResultsContainer.innerHTML = searchingActivityIndicatorMarkup;
            this.activateContainer(ContainerType.SearchResults);
            pagingControl.innerHTML = ""
        },
        searcherSearchStarted: function(e){
        },
        searcherSearchCompleted: function(e){
        },
        searcherSearchCompletedWithFailure: function(e){
            searchResultsContainer.innerHTML = String.format('<div id="search-failure-notice"><p>Your search request is unrecognizable.  <span class="bold">HINT: Enter WHAT you are looking for in the "Search Topic" box and its LOCATION in the next box!</span></p><p>A common error we encounter involves users typing all information into one box, or inputting locations that do not exist (e.g. Entering <span class="italic">Disneyland,CA</span> into the "Location" box will result in an error.  Instead try <span class="italic">Disneyland</span> in the "Search Topic" box and <span class="italic">CA</span> in the "Location" box)</p></div>');
            pagingControl.innerHTML = ""
        },
        activateContainer: function(containerType){
            switch (containerType) {
                case ContainerType.SearchResults:
                    accountContainer.hide();
                    communityContainer.hide();
                    searchResultsContainer.show();
                    searchResultsContainer.setStyle("width:100%");
                    break;
                case ContainerType.Account:
                    searchResultsContainer.hide();
                    communityContainer.hide();
                    accountContainer.show();
                    accountContainer.setStyle("width:100%");
                    break;
                case ContainerType.Community:
                    searchResultsContainer.hide();
                    accountContainer.hide();
                    communityContainer.show();
                    communityContainer.setStyle("width:100%");
                    break
            }
        },
        extend: function(){
            var self = this;
            var newWidth = $("viewport").getWidth() - 340 + 16;
            if (gg.debug) {
                gg.log("new width is " + newWidth)
            }
            var sideBarDimensions = sideBarElement.getDimensions();
            var effects = new Array();
            effects.push(new Effect.Morph(elementToResize, {
                style: "width: " + newWidth + "px; left: " + 340 + "px;",
                sync: true
            }));
            effects.push(new Effect.Morph(sideBarElement, {
                style: "width: 356px;",
                sync: true
            }));
            effects.push(new Effect.Morph(sideBarContent, {
                style: "width: 340px;",
                sync: true
            }));
            effects.push(new Effect.Morph(activeElement, {
                style: "left: 340px;",
                sync: true
            }));
            effects.push(new Effect.Morph(filterBarElement, {
                style: "margin-left: 390px;",
                sync: true
            }));
            new Effect.Parallel(effects, {
                duration: 0.8,
                afterFinish: function(){
                    isExtended = true;
                    sideBarElement.fire(geograffiti.SideBarEvent.SideBarExtended);
                    effects.clear();
                    effects = null
                }
            })
        },
        collapse: function(){
            var self = this;
            var newWidth = $("viewport").getWidth();
            if (gg.debug) {
                gg.log("new width is " + newWidth)
            }
            var effects = new Array();
            var sideBarDimensions = sideBarElement.getDimensions();
            effects.push(new Effect.Morph(elementToResize, {
                style: "width: " + newWidth + "px; left: 0px;",
                sync: true
            }));
            effects.push(new Effect.Morph(sideBarElement, {
                style: "width: 0px;",
                sync: true
            }));
            effects.push(new Effect.Morph(sideBarContent, {
                style: "width: 0px;",
                sync: true
            }));
            effects.push(new Effect.Morph(activeElement, {
                style: "left: 0px;",
                sync: true
            }));
            effects.push(new Effect.Morph(filterBarElement, {
                style: "margin-left: 50px;",
                sync: true
            }));
            new Effect.Parallel(effects, {
                duration: 0.8,
                afterFinish: function(){
                    isExtended = false;
                    sideBarElement.fire(geograffiti.SideBarEvent.SideBarCollapsed);
                    effects.clear();
                    effects = null
                }
            })
        },
        userVoiceMarksPageClicked: function(e){
            var element = Event.element(e);
            var activeClassName = "activepage";
            var inactiveClassName = "inactivepage";
            element.toggleClassName(inactiveClassName);
            element.toggleClassName(activeClassName);
            var idValue = element.getAttribute("id");
            id = parseInt(idValue.charAt(idValue.length - 1));
            if (gg.debug) {
                gg.log("the arguments array is %o", $A(arguments))
            }
            var cursor = $A(arguments)[1];
            var that = $A(arguments)[2];
            if (id === 0 && (id !== (cursor.pages.length - 1))) {
                var next = element.next();
                if (next.hasClassName(activeClassName)) {
                    next.toggleClassName(activeClassName);
                    next.toggleClassName(inactiveClassName);
                    var obj = {
                        fx: that.userVoiceMarksPageClicked
                    };
                    obj.bfx = obj.fx.bindAsEventListener(obj, cursor, that);
                    next.observe("click", obj.bfx)
                }
            }
            else {
                if (id !== 0 && (id === (cursor.pages.length - 1))) {
                    var previous = element.previous();
                    if (previous.hasClassName(activeClassName)) {
                        previous.toggleClassName(activeClassName);
                        previous.toggleClassName(inactiveClassName);
                        var obj = {
                            fx: that.userVoiceMarksPageClicked
                        };
                        obj.bfx = obj.fx.bindAsEventListener(obj, cursor, that);
                        previous.observe("click", obj.bfx)
                    }
                }
                else {
                    var previous = element.previous();
                    var next = element.next();
                    if (previous.hasClassName(activeClassName)) {
                        previous.toggleClassName(activeClassName);
                        previous.toggleClassName(inactiveClassName);
                        var obj = {
                            fx: that.userVoiceMarksPageClicked
                        };
                        obj.bfx = obj.fx.bindAsEventListener(obj, cursor, that);
                        previous.observe("click", obj.bfx)
                    }
                    else {
                        if (next.hasClassName(activeClassName)) {
                            next.toggleClassName(activeClassName);
                            next.toggleClassName(inactiveClassName);
                            var obj = {
                                fx: that.userVoiceMarksPageClicked
                            };
                            obj.bfx = obj.fx.bindAsEventListener(obj, cursor, that);
                            next.observe("click", obj.bfx)
                        }
                    }
                }
            }
            element.stopObserving("click", this.bfx);
            sideBarElement.fire(gg.SideBarEvent.UserVoiceMarksSearchRequested, {
                page: cursor.pages[id]
            })
        },
        groupVoiceMarksPageClicked: function(e){
            var element = Event.element(e);
            var activeClassName = "activepage";
            var inactiveClassName = "inactivepage";
            element.toggleClassName(inactiveClassName);
            element.toggleClassName(activeClassName);
            var idValue = element.getAttribute("id");
            id = parseInt(idValue.charAt(idValue.length - 1));
            if (gg.debug) {
                gg.log("the arguments array is %o", $A(arguments))
            }
            var cursor = $A(arguments)[1];
            var that = $A(arguments)[2];
            if (id === 0 && (id !== (cursor.pages.length - 1))) {
                var next = element.next();
                if (next.hasClassName(activeClassName)) {
                    next.toggleClassName(activeClassName);
                    next.toggleClassName(inactiveClassName);
                    var obj = {
                        fx: that.groupVoiceMarksPageClicked
                    };
                    obj.bfx = obj.fx.bindAsEventListener(obj, cursor, that);
                    next.observe("click", obj.bfx)
                }
            }
            else {
                if (id !== 0 && (id === (cursor.pages.length - 1))) {
                    var previous = element.previous();
                    if (previous.hasClassName(activeClassName)) {
                        previous.toggleClassName(activeClassName);
                        previous.toggleClassName(inactiveClassName);
                        var obj = {
                            fx: that.groupVoiceMarksPageClicked
                        };
                        obj.bfx = obj.fx.bindAsEventListener(obj, cursor, that);
                        previous.observe("click", obj.bfx)
                    }
                }
                else {
                    var previous = element.previous();
                    var next = element.next();
                    if (previous.hasClassName(activeClassName)) {
                        previous.toggleClassName(activeClassName);
                        previous.toggleClassName(inactiveClassName);
                        var obj = {
                            fx: that.groupVoiceMarksPageClicked
                        };
                        obj.bfx = obj.fx.bindAsEventListener(obj, cursor, that);
                        previous.observe("click", obj.bfx)
                    }
                    else {
                        if (next.hasClassName(activeClassName)) {
                            next.toggleClassName(activeClassName);
                            next.toggleClassName(inactiveClassName);
                            var obj = {
                                fx: that.groupVoiceMarksPageClicked
                            };
                            obj.bfx = obj.fx.bindAsEventListener(obj, cursor, that);
                            next.observe("click", obj.bfx)
                        }
                    }
                }
            }
            element.stopObserving("click", this.bfx);
            sideBarElement.fire(gg.SideBarEvent.GroupVoiceMarksSearchRequested, {
                page: cursor.pages[id]
            })
        },
        pageClicked: function(e){
            if (gg.debug) {
                gg.log("page click...event %o", e)
            }
            var element = Event.element(e);
            var activeClassName = "activepage";
            var inactiveClassName = "inactivepage";
            element.toggleClassName(inactiveClassName);
            element.toggleClassName(activeClassName);
            var idValue = element.getAttribute("id");
            id = parseInt(idValue.charAt(idValue.length - 1));
            if (gg.debug) {
                gg.log("the arguments array is %o", $A(arguments))
            }
            var cursor = $A(arguments)[1];
            var that = $A(arguments)[2];
            if (id === 0 && (id !== (cursor.pages.length - 1))) {
                var next = element.next();
                if (next.hasClassName(activeClassName)) {
                    next.toggleClassName(activeClassName);
                    next.toggleClassName(inactiveClassName);
                    var obj = {
                        fx: that.pageClicked
                    };
                    obj.bfx = obj.fx.bindAsEventListener(obj, cursor, that);
                    next.observe("click", obj.bfx)
                }
            }
            else {
                if (id !== 0 && (id === (cursor.pages.length - 1))) {
                    var previous = element.previous();
                    if (previous.hasClassName(activeClassName)) {
                        previous.toggleClassName(activeClassName);
                        previous.toggleClassName(inactiveClassName);
                        var obj = {
                            fx: that.pageClicked
                        };
                        obj.bfx = obj.fx.bindAsEventListener(obj, cursor, that);
                        previous.observe("click", obj.bfx)
                    }
                }
                else {
                    var previous = element.previous();
                    var next = element.next();
                    if (previous.hasClassName(activeClassName)) {
                        previous.toggleClassName(activeClassName);
                        previous.toggleClassName(inactiveClassName);
                        var obj = {
                            fx: that.pageClicked
                        };
                        obj.bfx = obj.fx.bindAsEventListener(obj, cursor, that);
                        previous.observe("click", obj.bfx)
                    }
                    else {
                        if (next.hasClassName(activeClassName)) {
                            next.toggleClassName(activeClassName);
                            next.toggleClassName(inactiveClassName);
                            var obj = {
                                fx: that.pageClicked
                            };
                            obj.bfx = obj.fx.bindAsEventListener(obj, cursor, that);
                            next.observe("click", obj.bfx)
                        }
                    }
                }
            }
            element.stopObserving("click", this.bfx);
            sideBarElement.fire(gg.SideBarEvent.SearchRequested, {
                page: cursor.pages[id]
            })
        },
        filterPageClicked: function(e){
            if (gg.debug) {
                gg.log("FILTER page click...event %o", e)
            }
            var element = Event.element(e);
            var activeClassName = "activepage";
            var inactiveClassName = "inactivepage";
            element.toggleClassName(inactiveClassName);
            element.toggleClassName(activeClassName);
            var idValue = element.getAttribute("id");
            id = parseInt(idValue.charAt(idValue.length - 1));
            if (gg.debug) {
                gg.log("the arguments array is %o", $A(arguments))
            }
            var cursor = $A(arguments)[1];
            var that = $A(arguments)[2];
            if (id === 0 && (id !== (cursor.pages.length - 1))) {
                var next = element.next();
                if (next.hasClassName(activeClassName)) {
                    next.toggleClassName(activeClassName);
                    next.toggleClassName(inactiveClassName);
                    var obj = {
                        fx: that.filterPageClicked
                    };
                    obj.bfx = obj.fx.bindAsEventListener(obj, cursor, that);
                    next.observe("click", obj.bfx)
                }
            }
            else {
                if (id !== 0 && (id === (cursor.pages.length - 1))) {
                    var previous = element.previous();
                    if (previous.hasClassName(activeClassName)) {
                        previous.toggleClassName(activeClassName);
                        previous.toggleClassName(inactiveClassName);
                        var obj = {
                            fx: that.filterPageClicked
                        };
                        obj.bfx = obj.fx.bindAsEventListener(obj, cursor, that);
                        previous.observe("click", obj.bfx)
                    }
                }
                else {
                    var previous = element.previous();
                    var next = element.next();
                    if (previous.hasClassName(activeClassName)) {
                        previous.toggleClassName(activeClassName);
                        previous.toggleClassName(inactiveClassName);
                        var obj = {
                            fx: that.filterPageClicked
                        };
                        obj.bfx = obj.fx.bindAsEventListener(obj, cursor, that);
                        previous.observe("click", obj.bfx)
                    }
                    else {
                        if (next.hasClassName(activeClassName)) {
                            next.toggleClassName(activeClassName);
                            next.toggleClassName(inactiveClassName);
                            var obj = {
                                fx: that.filterPageClicked
                            };
                            obj.bfx = obj.fx.bindAsEventListener(obj, cursor, that);
                            next.observe("click", obj.bfx)
                        }
                    }
                }
            }
            element.stopObserving("click", this.bfx);
            if (gg.debug) {
                gg.log("filter search requested is about to be fire")
            }
            sideBarElement.fire(gg.SideBarEvent.FilterSearchRequested, {
                page: cursor.pages[id]
            });
            if (gg.debug) {
                gg.log("sent filter search requested")
            }
        },
        activateUserVoiceMarksPaging: function(cursor){
            var self = this;
            if (cursor) {
                var pages = cursor.pages;
                var buffer = new geograffiti.StringBuffer();
                for (var i = 0, limit = pages.length; i < limit; i++) {
                    var currentPage = pages[i];
                    var spanClass = "inactivepage";
                    if (i === cursor.currentPageIndex) {
                        spanClass = "activepage"
                    }
                    buffer.append(String.format('<span id="searchresultspage-$0" class="pagelabel $1">$2</span>', i, spanClass, currentPage.label))
                }
                pagingControl.innerHTML = buffer.toString();
                var inactivePages = $$("span.inactivepage");
                if (inactivePages) {
                    for (var i = 0, limit = inactivePages.length; i < limit; i++) {
                        var currentPage = inactivePages[i];
                        var obj = {
                            fx: self.userVoiceMarksPageClicked
                        };
                        obj.bfx = obj.fx.bindAsEventListener(obj, cursor, self);
                        currentPage.observe("click", obj.bfx)
                    }
                }
            }
        },
        activateGroupVoiceMarksPaging: function(cursor){
            var self = this;
            if (cursor) {
                var pages = cursor.pages;
                var buffer = new geograffiti.StringBuffer();
                for (var i = 0, limit = pages.length; i < limit; i++) {
                    var currentPage = pages[i];
                    var spanClass = "inactivepage";
                    if (i === cursor.currentPageIndex) {
                        spanClass = "activepage"
                    }
                    buffer.append(String.format('<span id="searchresultspage-$0" class="pagelabel $1">$2</span>', i, spanClass, currentPage.label))
                }
                pagingControl.innerHTML = buffer.toString();
                var inactivePages = $$("span.inactivepage");
                if (inactivePages) {
                    for (var i = 0, limit = inactivePages.length; i < limit; i++) {
                        var currentPage = inactivePages[i];
                        var obj = {
                            fx: self.groupVoiceMarksPageClicked
                        };
                        obj.bfx = obj.fx.bindAsEventListener(obj, cursor, self);
                        currentPage.observe("click", obj.bfx)
                    }
                }
            }
        },
        activatePaging: function(cursor){
            var self = this;
            if (cursor) {
                var pages = cursor.pages;
                var buffer = new geograffiti.StringBuffer();
                for (var i = 0, limit = pages.length; i < limit; i++) {
                    var currentPage = pages[i];
                    var spanClass = "inactivepage";
                    if (i === cursor.currentPageIndex) {
                        spanClass = "activepage"
                    }
                    buffer.append(String.format('<span id="searchresultspage-$0" class="pagelabel $1">$2</span>', i, spanClass, currentPage.label))
                }
                pagingControl.innerHTML = buffer.toString();
                var inactivePages = $$("span.inactivepage");
                if (inactivePages) {
                    for (var i = 0, limit = inactivePages.length; i < limit; i++) {
                        var currentPage = inactivePages[i];
                        var obj = {
                            fx: self.pageClicked
                        };
                        obj.bfx = obj.fx.bindAsEventListener(obj, cursor, self);
                        currentPage.observe("click", obj.bfx)
                    }
                }
            }
        },
        activateFilterPaging: function(cursor){
            if (gg.debug) {
                gg.log("filter paging is being activated")
            }
            var self = this;
            if (cursor) {
                var pages = cursor.pages;
                var buffer = new geograffiti.StringBuffer();
                for (var i = 0, limit = pages.length; i < limit; i++) {
                    var currentPage = pages[i];
                    var spanClass = "inactivepage";
                    if (i === cursor.currentPageIndex) {
                        spanClass = "activepage"
                    }
                    buffer.append(String.format('<span id="filterresultspage-$0" class="pagelabel $1">$2</span>', i, spanClass, currentPage.label))
                }
                pagingControl.innerHTML = buffer.toString();
                var inactivePages = $$("span.inactivepage");
                if (inactivePages) {
                    for (var i = 0, limit = inactivePages.length; i < limit; i++) {
                        var currentPage = inactivePages[i];
                        var obj = {
                            fx: self.filterPageClicked
                        };
                        obj.bfx = obj.fx.bindAsEventListener(obj, cursor, self);
                        currentPage.observe("click", obj.bfx)
                    }
                }
            }
        },
        displayUserVoiceMarksResults: function(results, query){
            this.transitionToStateZero();
            var self = this;
            searchQuery = query;
            var voiceMarks = results.voiceMarks;
            var cursor = results.cursor;
            var voiceMarkDescriptors = new Array();
            var titleId = null;
            var buffer = new geograffiti.StringBuffer();
            var voiceMarksFound = voiceMarks && voiceMarks.length > 0;
            var voiceMarksSearchResultsHeading = null;
            if (voiceMarksFound === true) {
                voiceMarksSearchResultsHeading = "Voice Marks"
            }
            else {
                voiceMarksSearchResultsHeading = "No Voice Marks Found"
            }
            buffer.append('<div id="voicemarks-results-section">');
            buffer.append('<div id="search-voicemarks-results-heading" class="search-results-heading accordion_toggle"><span>$0</span></div>', voiceMarksSearchResultsHeading);
            buffer.append('<div id="search-voicemarks-results" class="accordion_content">');
            if (voiceMarksFound === false) {
                buffer.append('<div id="no-search-results-section">No Voice Marks exist for your search.  Below are relevant places that match your search.  Be the first to Voice Mark them!</div>')
            }
            else {
                var length = voiceMarks.length;
                for (var i = 0; i < length; i++) {
                    var nakedVoiceMark = voiceMarks[i];
                    var voiceMark = Object.extend(nakedVoiceMark, geograffiti.VoiceMarkBase);
                    buffer.append(String.format('<div id="vmresult$0" class="vmresult">', voiceMark.id));
                    buffer.append('<img src="/images/transparent.png" class="vmresultimage" alt="Voice Mark Result Image" />');
                    titleId = String.format("vmtitle$0", voiceMark.id);
                    voiceMarkDescriptors.push({
                        id: voiceMark.id,
                        elementId: titleId
                    });
                    buffer.append('<a id="$0" href="http://$1/voicemarks/$2" class="vmtitle">$3</a>', titleId, gg.Environment.ServerRunningOn, voiceMark.id, voiceMark.getTitle());
                    buffer.append(String.format('<div id="vmlocationinfo$0" class="vmlocationinfo">', titleId, voiceMark.id));
                    var addressLineOne = voiceMark.addressLineOne;
                    if (addressLineOne) {
                        buffer.append(String.format('<span class="vmaddrlineone">$0</span>', addressLineOne))
                    }
                    var city = voiceMark.city;
                    if (city) {
                        buffer.append(String.format('<span class="vmcity">$0</span>', city))
                    }
                    var state = voiceMark.state;
                    if (state) {
                        buffer.append(String.format('<span class="vmstate">$0</span>', state))
                    }
                    var postalCode = voiceMark.postalCode;
                    if (postalCode) {
                        buffer.append(String.format('<span class="vmpostalcode">$0</span>', postalCode))
                    }
                    var phoneNumber = voiceMark.phoneNumber;
                    if (phoneNumber) {
                        buffer.append(String.format('<span class="vmphonenumber">$0</span>', phoneNumber))
                    }
                    buffer.append("</div>");
                    buffer.append(String.format('<div id="vmcreationsection$0" class="vmcreationsection">', voiceMark.id));
                    buffer.append(String.format('<span class="vmcreatedon">$0 by </span>', voiceMark.modifiedOn));
                    var userNameId = null;
                    if (voiceMark.isAnonymous) {
                        userNameId = String.format("vmusername-anonymous-$0", voiceMark.vid)
                    }
                    else {
                        userNameId = String.format("vmusername-$0", voiceMark.uid)
                    }
                    buffer.append(String.format('<span id="$0" class="vmusername">$1</span>', userNameId, voiceMark.userName));
                    buffer.append("</div>");
                    buffer.append(String.format('<div id="vmcategorysection$0" class="vmcategorysection">', voiceMark.id));
                    buffer.append(String.format('<span id="vmcategoryheading$0" class="vmcategoryheading">Category: </span>', voiceMark.id));
                    buffer.append(String.format('<span id="vmcategory$0" class="vmcategory">$1</span>', voiceMark.id, voiceMark.category));
                    buffer.append("</div>");
                    buffer.append('<div class="vmstarrating">');
                    var rating = voiceMark.starRating;
                    var offStars = 5 - rating;
                    var onStars = 5 - offStars;
                    for (var j = 0; j < onStars; j++) {
                        buffer.append('<img class="onstar" src="/images/star.png"/>')
                    }
                    for (var j = 0; j < offStars; j++) {
                        buffer.append('<img class="offstar" src="/images/blankstar.png"/>')
                    }
                    buffer.append("</div>");
                    buffer.append("</div>")
                }
            }
            buffer.append("</div>");
            buffer.append("</div>");
            searchResultsContainer.innerHTML = buffer.toString();
            var voiceMarksAccordion = new accordion("voicemarks-results-section");
            voiceMarksAccordion.activate($$("#voicemarks-results-section .accordion_toggle")[0]);
            var voiceMarksResultsSection = $("voicemarks-results-section");
            voiceMarksResultsSection.stopObserving("geograffiti:sectionCollapsed");
            voiceMarksResultsSection.observe("geograffiti:sectionCollapsed", function(e){
                e.stop();
                if (gg.debug) {
                    gg.log("collapsed %o", e.memo.section)
                }
                sideBarElement.fire(gg.SideBarEvent.VoiceMarksHidden)
            });
            voiceMarksResultsSection.stopObserving("geograffiti:sectionExpanded");
            voiceMarksResultsSection.observe("geograffiti:sectionExpanded", function(e){
                e.stop();
                if (gg.debug) {
                    gg.log("expanded %o", e.memo.section)
                }
                sideBarElement.fire(gg.SideBarEvent.VoiceMarksVisible)
            });
            voiceMarkDescriptors.each(function(descriptor){
                var element = $(descriptor.elementId);
                if (element) {
                    element.stopObserving("click");
                    element.observe("click", function(e){
                        e.stop();
                        if (gg.debug) {
                            gg.log("going to fire a click b/c someone clicked on VM %s for %o", descriptor.elementId, e)
                        }
                        var event = sideBarElement.fire(gg.SideBarEvent.VoiceMarkLinkClicked, {
                            id: descriptor.id
                        });
                        if (gg.debug) {
                            gg.log("I stopped e...now i'm going to see if event was stopped...%o", event.stopped)
                        }
                    });
                    element.stopObserving("mouseover");
                    element.observe("mouseover", function(e){
                        e.stop();
                        sideBarElement.fire(gg.SideBarEvent.MouseOverVoiceMarkResult, {
                            id: descriptor.id
                        })
                    });
                    if (gg.debug) {
                        gg.log("The element is %o", element)
                    }
                }
                else {
                    if (gg.debug) {
                        gg.log("Element has not been set!")
                    }
                }
            });
            try {
                $$(".vmusername").each(function(userNameContainer){
                    userNameContainer.stopObserving("click");
                    userNameContainer.observe("click", function(e){
                        e.stop();
                        var sourceElement = e.element();
                        var id = sourceElement.identify();
                        var memo = {
                            userId: null,
                            userName: null,
                            isAnonymous: null
                        };
                        if (id.startsWith("vmusername-anonymous-")) {
                            memo.userId = id.gsub("vmusername-anonymous-", "");
                            memo.userName = sourceElement.innerHTML;
                            memo.isAnonymous = true
                        }
                        else {
                            memo.userId = id.gsub("vmusername-", "");
                            memo.userName = sourceElement.innerHTML;
                            memo.isAnonymous = false
                        }
                        sideBarElement.fire(gg.SideBarEvent.ResultUserNameClicked, memo)
                    })
                })
            } 
            catch (e) {
                gg.error("ERROR %o", e)
            }
            self.activateUserVoiceMarksPaging(cursor)
        },
        displayGroupVoiceMarksResults: function(results, query){
            this.transitionToStateZero();
            var self = this;
            searchQuery = query;
            var voiceMarks = results.voiceMarks;
            var cursor = results.cursor;
            var voiceMarkDescriptors = new Array();
            var titleId = null;
            var buffer = new geograffiti.StringBuffer();
            var voiceMarksFound = voiceMarks && voiceMarks.length > 0;
            var voiceMarksSearchResultsHeading = null;
            if (voiceMarksFound === true) {
                voiceMarksSearchResultsHeading = "Voice Marks"
            }
            else {
                voiceMarksSearchResultsHeading = "No Voice Marks Found"
            }
            buffer.append('<div id="voicemarks-results-section">');
            buffer.append('<div id="search-voicemarks-results-heading" class="search-results-heading accordion_toggle"><span>$0</span></div>', voiceMarksSearchResultsHeading);
            buffer.append('<div id="search-voicemarks-results" class="accordion_content">');
            if (voiceMarksFound === false) {
                buffer.append('<div id="no-search-results-section">No Voice Marks exist for your search.  Below are relevant places that match your search. Be the first to Voice Mark them!</div>')
            }
            else {
                var length = voiceMarks.length;
                for (var i = 0; i < length; i++) {
                    var nakedVoiceMark = voiceMarks[i];
                    var voiceMark = Object.extend(nakedVoiceMark, geograffiti.VoiceMarkBase);
                    buffer.append(String.format('<div id="vmresult$0" class="vmresult">', voiceMark.id));
                    buffer.append('<img src="/images/transparent.png" class="vmresultimage" alt="Voice Mark Result Image" />');
                    titleId = String.format("vmtitle$0", voiceMark.id);
                    voiceMarkDescriptors.push({
                        id: voiceMark.id,
                        elementId: titleId
                    });
                    buffer.append('<a id="$0" href="http://$1/voicemarks/$2" class="vmtitle">$3</a>', titleId, gg.Environment.ServerRunningOn, voiceMark.id, voiceMark.getTitle());
                    buffer.append(String.format('<div id="vmlocationinfo$0" class="vmlocationinfo">', titleId, voiceMark.id));
                    var addressLineOne = voiceMark.addressLineOne;
                    if (addressLineOne) {
                        buffer.append(String.format('<span class="vmaddrlineone">$0</span>', addressLineOne))
                    }
                    var city = voiceMark.city;
                    if (city) {
                        buffer.append(String.format('<span class="vmcity">$0</span>', city))
                    }
                    var state = voiceMark.state;
                    if (state) {
                        buffer.append(String.format('<span class="vmstate">$0</span>', state))
                    }
                    var postalCode = voiceMark.postalCode;
                    if (postalCode) {
                        buffer.append(String.format('<span class="vmpostalcode">$0</span>', postalCode))
                    }
                    var phoneNumber = voiceMark.phoneNumber;
                    if (phoneNumber) {
                        buffer.append(String.format('<span class="vmphonenumber">$0</span>', phoneNumber))
                    }
                    buffer.append("</div>");
                    buffer.append(String.format('<div id="vmcreationsection$0" class="vmcreationsection">', voiceMark.id));
                    buffer.append(String.format('<span class="vmcreatedon">$0 by </span>', voiceMark.modifiedOn));
                    var userNameId = null;
                    if (voiceMark.isAnonymous) {
                        userNameId = String.format("vmusername-anonymous-$0", voiceMark.vid)
                    }
                    else {
                        userNameId = String.format("vmusername-$0", voiceMark.uid)
                    }
                    buffer.append(String.format('<span id="$0" class="vmusername">$1</span>', userNameId, voiceMark.userName));
                    buffer.append("</div>");
                    buffer.append(String.format('<div id="vmcategorysection$0" class="vmcategorysection">', voiceMark.id));
                    buffer.append(String.format('<span id="vmcategoryheading$0" class="vmcategoryheading">Category: </span>', voiceMark.id));
                    buffer.append(String.format('<span id="vmcategory$0" class="vmcategory">$1</span>', voiceMark.id, voiceMark.category));
                    buffer.append("</div>");
                    buffer.append('<div class="vmstarrating">');
                    var rating = voiceMark.starRating;
                    var offStars = 5 - rating;
                    var onStars = 5 - offStars;
                    for (var j = 0; j < onStars; j++) {
                        buffer.append('<img class="onstar" src="/images/star.png"/>')
                    }
                    for (var j = 0; j < offStars; j++) {
                        buffer.append('<img class="offstar" src="/images/blankstar.png"/>')
                    }
                    buffer.append("</div>");
                    buffer.append("</div>")
                }
            }
            buffer.append("</div>");
            buffer.append("</div>");
            searchResultsContainer.innerHTML = buffer.toString();
            var voiceMarksAccordion = new accordion("voicemarks-results-section");
            voiceMarksAccordion.activate($$("#voicemarks-results-section .accordion_toggle")[0]);
            var voiceMarksResultsSection = $("voicemarks-results-section");
            voiceMarksResultsSection.stopObserving("geograffiti:sectionCollapsed");
            voiceMarksResultsSection.observe("geograffiti:sectionCollapsed", function(e){
                e.stop();
                if (gg.debug) {
                    gg.log("collapsed %o", e.memo.section)
                }
                sideBarElement.fire(gg.SideBarEvent.VoiceMarksHidden)
            });
            voiceMarksResultsSection.stopObserving("geograffiti:sectionExpanded");
            voiceMarksResultsSection.observe("geograffiti:sectionExpanded", function(e){
                e.stop();
                if (gg.debug) {
                    gg.log("expanded %o", e.memo.section)
                }
                sideBarElement.fire(gg.SideBarEvent.VoiceMarksVisible)
            });
            voiceMarkDescriptors.each(function(descriptor){
                var element = $(descriptor.elementId);
                if (element) {
                    element.stopObserving("click");
                    element.observe("click", function(e){
                        e.stop();
                        if (gg.debug) {
                            gg.log("going to fire a click b/c someone clicked on VM %s for %o", descriptor.elementId, e)
                        }
                        var event = sideBarElement.fire(gg.SideBarEvent.VoiceMarkLinkClicked, {
                            id: descriptor.id
                        });
                        if (gg.debug) {
                            gg.log("I stopped e...now i'm going to see if event was stopped...%o", event.stopped)
                        }
                    });
                    element.stopObserving("mouseover");
                    element.observe("mouseover", function(e){
                        e.stop();
                        sideBarElement.fire(gg.SideBarEvent.MouseOverVoiceMarkResult, {
                            id: descriptor.id
                        })
                    });
                    if (gg.debug) {
                        gg.log("The element is %o", element)
                    }
                }
                else {
                    if (gg.debug) {
                        gg.log("Element has not been set!")
                    }
                }
            });
            try {
                $$(".vmusername").each(function(userNameContainer){
                    userNameContainer.stopObserving("click");
                    userNameContainer.observe("click", function(e){
                        e.stop();
                        var sourceElement = e.element();
                        var id = sourceElement.identify();
                        var memo = {
                            userId: null,
                            userName: null,
                            isAnonymous: null
                        };
                        if (id.startsWith("vmusername-anonymous-")) {
                            memo.userId = id.gsub("vmusername-anonymous-", "");
                            memo.userName = sourceElement.innerHTML;
                            memo.isAnonymous = true
                        }
                        else {
                            memo.userId = id.gsub("vmusername-", "");
                            memo.userName = sourceElement.innerHTML;
                            memo.isAnonymous = false
                        }
                        sideBarElement.fire(gg.SideBarEvent.ResultUserNameClicked, memo)
                    })
                })
            } 
            catch (e) {
                gg.error("ERROR %o", e)
            }
            self.activateGroupVoiceMarksPaging(cursor)
        },
        displayFilterResults: function(results, query){
            this.transitionToStateZero();
            var self = this;
            searchQuery = query;
            if (gg.debug) {
                gg.log("The results for your search are %o", results)
            }
            var voiceMarks = results.voiceMarks;
            var cursor = results.cursor;
            var voiceMarkDescriptors = new Array();
            var titleId = null;
            var buffer = new geograffiti.StringBuffer();
            var voiceMarksFound = voiceMarks && voiceMarks.length > 0;
            var voiceMarksSearchResultsHeading = null;
            if (voiceMarksFound === true) {
                voiceMarksSearchResultsHeading = "Voice Marks"
            }
            else {
                voiceMarksSearchResultsHeading = "No Voice Marks Found"
            }
            buffer.append('<div id="voicemarks-results-section">');
            buffer.append('<div id="search-voicemarks-results-heading" class="search-results-heading accordion_toggle"><span>$0</span></div>', voiceMarksSearchResultsHeading);
            buffer.append('<div id="search-voicemarks-results" class="accordion_content">');
            if (voiceMarksFound === false) {
                buffer.append('<div id="no-search-results-section">No Voice Marks exist for your search.  Below are relevant places that match your search.  Be the first to Voice Mark them!</div>')
            }
            else {
                var length = voiceMarks.length;
                for (var i = 0; i < length; i++) {
                    var nakedVoiceMark = voiceMarks[i];
                    var voiceMark = Object.extend(nakedVoiceMark, geograffiti.VoiceMarkBase);
                    buffer.append(String.format('<div id="vmresult$0" class="vmresult">', voiceMark.id));
                    buffer.append('<img src="$0" class="vmresultimage" alt="Voice Mark Result Image" />', !voiceMark.isBiz ? gg.Art.VoiceMarkResultIcon : gg.Art.BizMarkResultIcon);
                    titleId = String.format("vmtitle$0", voiceMark.id);
                    voiceMarkDescriptors.push({
                        id: voiceMark.id,
                        elementId: titleId
                    });
                    buffer.append('<a id="$0" href="http://$1/voicemarks/$2" class="vmtitle">$3</a>', titleId, gg.Environment.ServerRunningOn, voiceMark.id, voiceMark.getTitle());
                    buffer.append(String.format('<div id="vmlocationinfo$0" class="vmlocationinfo">', titleId, voiceMark.id));
                    var addressLineOne = voiceMark.addressLineOne;
                    if (addressLineOne) {
                        buffer.append(String.format('<span class="vmaddrlineone">$0</span>', addressLineOne))
                    }
                    var city = voiceMark.city;
                    if (city) {
                        buffer.append(String.format('<span class="vmcity">$0</span>', city))
                    }
                    var state = voiceMark.state;
                    if (state) {
                        buffer.append(String.format('<span class="vmstate">$0</span>', state))
                    }
                    var postalCode = voiceMark.postalCode;
                    if (postalCode) {
                        buffer.append(String.format('<span class="vmpostalcode">$0</span>', postalCode))
                    }
                    var phoneNumber = voiceMark.phoneNumber;
                    if (phoneNumber) {
                        buffer.append(String.format('<span class="vmphonenumber">$0</span>', phoneNumber))
                    }
                    buffer.append("</div>");
                    buffer.append(String.format('<div id="vmcreationsection$0" class="vmcreationsection">', voiceMark.id));
                    buffer.append(String.format('<span class="vmcreatedon">$0 by </span>', voiceMark.modifiedOn));
                    var userNameId = null;
                    if (voiceMark.isAnonymous) {
                        userNameId = String.format("vmusername-anonymous-$0", voiceMark.vid)
                    }
                    else {
                        userNameId = String.format("vmusername-$0", voiceMark.uid)
                    }
                    buffer.append(String.format('<span id="$0" class="vmusername">$1</span>', userNameId, voiceMark.userName));
                    buffer.append("</div>");
                    buffer.append(String.format('<div id="vmcategorysection$0" class="vmcategorysection">', voiceMark.id));
                    buffer.append(String.format('<span id="vmcategoryheading$0" class="vmcategoryheading">Category: </span>', voiceMark.id));
                    buffer.append(String.format('<span id="vmcategory$0" class="vmcategory">$1</span>', voiceMark.id, voiceMark.category));
                    buffer.append("</div>");
                    buffer.append('<div class="vmstarrating">');
                    var rating = voiceMark.starRating;
                    var offStars = 5 - rating;
                    var onStars = 5 - offStars;
                    for (var j = 0; j < onStars; j++) {
                        buffer.append('<img class="onstar" src="/images/star.png"/>')
                    }
                    for (var j = 0; j < offStars; j++) {
                        buffer.append('<img class="offstar" src="/images/blankstar.png"/>')
                    }
                    buffer.append("</div>");
                    buffer.append("</div>")
                }
            }
            buffer.append("</div>");
            buffer.append("</div>");
            searchResultsContainer.innerHTML = buffer.toString();
            var voiceMarksAccordion = new accordion("voicemarks-results-section");
            voiceMarksAccordion.activate($$("#voicemarks-results-section .accordion_toggle")[0]);
            var voiceMarksResultsSection = $("voicemarks-results-section");
            voiceMarksResultsSection.stopObserving("geograffiti:sectionCollapsed");
            voiceMarksResultsSection.observe("geograffiti:sectionCollapsed", function(e){
                e.stop();
                if (gg.debug) {
                    gg.log("collapsed %o", e.memo.section)
                }
                sideBarElement.fire(gg.SideBarEvent.VoiceMarksHidden)
            });
            voiceMarksResultsSection.stopObserving("geograffiti:sectionExpanded");
            voiceMarksResultsSection.observe("geograffiti:sectionExpanded", function(e){
                e.stop();
                if (gg.debug) {
                    gg.log("expanded %o", e.memo.section)
                }
                sideBarElement.fire(gg.SideBarEvent.VoiceMarksVisible)
            });
            voiceMarkDescriptors.each(function(descriptor){
                var element = $(descriptor.elementId);
                if (element) {
                    element.stopObserving("click");
                    element.observe("click", function(e){
                        e.stop();
                        if (gg.debug) {
                            gg.log("going to fire a click b/c someone clicked on VM %s for %o", descriptor.elementId, e)
                        }
                        var event = sideBarElement.fire(gg.SideBarEvent.VoiceMarkLinkClicked, {
                            id: descriptor.id
                        });
                        if (gg.debug) {
                            gg.log("I stopped e...now i'm going to see if event was stopped...%o", event.stopped)
                        }
                    });
                    element.stopObserving("mouseover");
                    element.observe("mouseover", function(e){
                        e.stop();
                        sideBarElement.fire(gg.SideBarEvent.MouseOverVoiceMarkResult, {
                            id: descriptor.id
                        })
                    });
                    if (gg.debug) {
                        gg.log("The element is %o", element)
                    }
                }
                else {
                    if (gg.debug) {
                        gg.log("Element has not been set!")
                    }
                }
            });
            try {
                $$(".vmusername").each(function(userNameContainer){
                    userNameContainer.stopObserving("click");
                    userNameContainer.observe("click", function(e){
                        e.stop();
                        var sourceElement = e.element();
                        var id = sourceElement.identify();
                        var memo = {
                            userId: null,
                            userName: null,
                            isAnonymous: null
                        };
                        if (id.startsWith("vmusername-anonymous-")) {
                            memo.userId = id.gsub("vmusername-anonymous-", "");
                            memo.userName = sourceElement.innerHTML;
                            memo.isAnonymous = true
                        }
                        else {
                            memo.userId = id.gsub("vmusername-", "");
                            memo.userName = sourceElement.innerHTML;
                            memo.isAnonymous = false
                        }
                        sideBarElement.fire(gg.SideBarEvent.ResultUserNameClicked, memo)
                    })
                })
            } 
            catch (e) {
                gg.error("ERROR %o", e)
            }
            self.activateFilterPaging(cursor)
        },
        displaySearchResults: function(results, query){
            this.transitionToStateZero();
            var self = this;
            searchQuery = query;
            if (gg.debug) {
                gg.log("The results for your search are %o", results)
            }
            var googleResults = results.googleLocalResults;
            var voiceMarksResponse = results.voiceMarksResponse;
            var voiceMarks = voiceMarksResponse.voiceMarks;
            var localResults = results.googleLocalResults;
            var cursor = voiceMarksResponse.cursor;
            var voiceMarkDescriptors = new Array();
            var googleLocalResultDescriptors = new Array();
            var titleId = null;
            var buffer = new geograffiti.StringBuffer();
			var voiceMarksFound = voiceMarks && voiceMarks.length > 0;
            var voiceMarksSearchResultsHeading = null;
            if (voiceMarksFound === true) {
                voiceMarksSearchResultsHeading = "Voice Marks"
            }
            else {
                voiceMarksSearchResultsHeading = "No Voice Marks Found"
            }
            buffer.append('<div id="voicemarks-results-section">');
            buffer.append('<div id="search-voicemarks-results-heading" class="search-results-heading accordion_toggle"><span>$0</span></div>', voiceMarksSearchResultsHeading);
            buffer.append('<div id="search-voicemarks-results" class="accordion_content">');
            if (voiceMarksFound === false) {
                buffer.append('<div id="no-search-results-section">No Voice Marks exist for your search.  Below are relevant places that match your search. Be the first to Voice Mark them!</div>')
            }
            else {
                var length = voiceMarks.length;
                for (var i = 0; i < length; i++) {
                    var nakedVoiceMark = voiceMarks[i];
                    var voiceMark = Object.extend(nakedVoiceMark, geograffiti.VoiceMarkBase);
                    buffer.append(String.format('<div id="vmresult$0" class="vmresult">', voiceMark.id));
                    buffer.append('<img src="$0" class="vmresultimage" alt="Voice Mark Result Image" />', !voiceMark.isBiz ? gg.Art.VoiceMarkResultIcon : gg.Art.BizMarkResultIcon);
                    titleId = String.format("vmtitle$0", voiceMark.id);
                    voiceMarkDescriptors.push({
                        id: voiceMark.id,
                        elementId: titleId
                    });
                    buffer.append('<a id="$0" href="http://$1/voicemarks/$2" class="vmtitle">$3</a>', titleId, gg.Environment.ServerRunningOn, voiceMark.id, voiceMark.getTitle());
                    buffer.append(String.format('<div id="vmlocationinfo$0" class="vmlocationinfo">', titleId, voiceMark.id));
                    var addressLineOne = voiceMark.addressLineOne;
                    if (addressLineOne) {
                        buffer.append(String.format('<span class="vmaddrlineone">$0</span>', addressLineOne))
                    }
                    var city = voiceMark.city;
                    if (city) {
                        buffer.append(String.format('<span class="vmcity">$0</span>', city))
                    }
                    var state = voiceMark.state;
                    if (state) {
                        buffer.append(String.format('<span class="vmstate">$0</span>', state))
                    }
                    var postalCode = voiceMark.postalCode;
                    if (postalCode) {
                        buffer.append(String.format('<span class="vmpostalcode">$0</span>', postalCode))
                    }
                    var phoneNumber = voiceMark.phoneNumber;
                    if (phoneNumber) {
                        buffer.append(String.format('<span class="vmphonenumber">$0</span>', phoneNumber))
                    }
                    buffer.append("</div>");
                    buffer.append(String.format('<div id="vmcreationsection$0" class="vmcreationsection">', voiceMark.id));
                    buffer.append(String.format('<span class="vmcreatedon">$0 by </span>', voiceMark.modifiedOn));
                    var userNameId = null;
                    if (voiceMark.isAnonymous) {
                        userNameId = String.format("vmusername-anonymous-$0", voiceMark.vid)
                    }
                    else {
                        userNameId = String.format("vmusername-$0", voiceMark.uid)
                    }
                    buffer.append(String.format('<span id="$0" class="vmusername">$1</span>', userNameId, voiceMark.userName));
                    buffer.append("</div>");
                    buffer.append(String.format('<div id="vmcategorysection$0" class="vmcategorysection">', voiceMark.id));
                    buffer.append(String.format('<span id="vmcategoryheading$0" class="vmcategoryheading">Category: </span>', voiceMark.id));
                    buffer.append(String.format('<span id="vmcategory$0" class="vmcategory">$1</span>', voiceMark.id, voiceMark.category));
                    buffer.append("</div>");
                    buffer.append('<div class="vmstarrating">');
                    var rating = voiceMark.starRating;
                    var offStars = 5 - rating;
                    var onStars = 5 - offStars;
                    for (var j = 0; j < onStars; j++) {
                        buffer.append('<img class="onstar" src="/images/star.png"/>')
                    }
                    for (var j = 0; j < offStars; j++) {
                        buffer.append('<img class="offstar" src="/images/blankstar.png"/>')
                    }
                    buffer.append("</div>");
                    buffer.append("</div>")
                }
            }
            buffer.append("</div>");
            buffer.append("</div>");
            buffer.append('<div id="google-local-results-section">');
            buffer.append('<div id="search-google-local-results-heading" class="search-results-heading accordion_toggle google-local-results-toggle"><span>Places that need your Voice Mark</span></div>');
            buffer.append('<div id="search-google-local-results" class="accordion_content">');
            if (googleResults) {
                for (var i = 0, limit = localResults.length; i < limit; ++i) {
                    var result = localResults[i];
                    var elementId = null;
                    if (result.GsearchResultClass === "GlocalSearch") {
                        elementId = String.format("glocalresult$0", i);
                        buffer.append('<div id="$0" class="glocalresult">', elementId);
                        googleLocalResultDescriptors.push({
                            id: i,
                            elementId: elementId
                        });
                        buffer.append('<img src="/images/transparent.png" class="glocalimage glocalimage$0" alt="Google Local Result Image $1" />', i, i);
                        buffer.append('<a id="glocallink$0" class="glocallink" href="$1">$2</a> - ', i, result.url, result.titleNoFormatting);
            				buffer.append('<div class="glocaladdressinfo">$0</div>', result.streetAddress);
										buffer.append('<div class="glocaladdressinfo">$0 $1</div>', result.city, result.region);
                        //buffer.append("$0 $1 $2", result.streetAddress, result.city, result.region);
                        var phoneNumbers = result.phoneNumbers;
                        if (phoneNumbers) {
                            var phoneNumber = null;
                            for (var j = 0, innerLimit = phoneNumbers.length; j < innerLimit; ++j) {
                                phoneNumber = phoneNumbers[j];
                                if (phoneNumber.type === "" || phoneNumber.type === "main") {
                                    buffer.append('<div class="glocaladdressinfo">$0</div>', phoneNumber.number);
                                    break
                                }
                            }
                        }
										buffer.append('<img class="glocalcreatevmbutton" src="/images/create-voicemark-button-120x23.png" />');
                        buffer.append("</div>")
                    }
                }
            }
            buffer.append("</div>");
            buffer.append("</div>");
            
            searchResultsContainer.update(buffer);
            var voiceMarksAccordion = new accordion("voicemarks-results-section");
            var googleLocalResultsAccordion = new accordion("google-local-results-section");
            var collapseInput = $("collapseVoiceMarks");
	    var collapseValue = $F(collapseInput);
	    if (String.isNullOrEmpty(collapseValue) || collapseValue === "false") {
            	voiceMarksAccordion.activate($$("#voicemarks-results-section .accordion_toggle")[0]);
	    }
	    else {
	        collapseInput.writeAttribute("value", null);
	    }
			googleLocalResultsAccordion.activate($$("#google-local-results-section .accordion_toggle")[0])
			
            if (gg.debug) {
                gg.log("%o %o", voiceMarksAccordion, googleLocalResultsAccordion)
            }
            var voiceMarksResultsSection = $("voicemarks-results-section");
            voiceMarksResultsSection.stopObserving("geograffiti:sectionCollapsed");
            voiceMarksResultsSection.observe("geograffiti:sectionCollapsed", function(e){
                e.stop();
                if (gg.debug) {
                    gg.log("collapsed %o", e.memo.section)
                }
                sideBarElement.fire(gg.SideBarEvent.VoiceMarksHidden)
            });
            voiceMarksResultsSection.stopObserving("geograffiti:sectionExpanded");
            voiceMarksResultsSection.observe("geograffiti:sectionExpanded", function(e){
                e.stop();
                if (gg.debug) {
                    gg.log("expanded %o", e.memo.section)
                }
                sideBarElement.fire(gg.SideBarEvent.VoiceMarksVisible)
            });
            var googleLocalResultsSection = $("google-local-results-section");
            googleLocalResultsSection.stopObserving("geograffiti:sectionCollapsed");
            googleLocalResultsSection.observe("geograffiti:sectionCollapsed", function(e){
                e.stop();
                if (gg.debug) {
                    gg.log("collapsed %o", e.memo.section)
                }
                sideBarElement.fire(gg.SideBarEvent.GoogleLocalResultsHidden)
            });
            googleLocalResultsSection.stopObserving("geograffiti:sectionExpanded");
            googleLocalResultsSection.observe("geograffiti:sectionExpanded", function(e){
                e.stop();
                if (gg.debug) {
                    gg.log("expanded %o", e.memo.section)
                }
                sideBarElement.fire(gg.SideBarEvent.GoogleLocalResultsVisible)
            });
            googleLocalResultDescriptors.each(function(descriptor){
                var element = $(descriptor.elementId);
                if (element) {
                    element.stopObserving("click");
                    element.observe("click", function(e){
                        e.stop();
                        if (gg.debug) {
                            gg.log("going to fire a click b/c someone clicked on GOOG %s for %o", descriptor.elementId, e)
                        }
                        var event = sideBarElement.fire(gg.SideBarEvent.GoogleLocalResultLinkClicked, {
                            id: descriptor.id
                        });
                        if (gg.debug) {
                            gg.log("I stopped e...now i'm going to see if event was stopped...%o", event.stopped)
                        }
                    });
                    element.stopObserving("mouseover");
                    element.observe("mouseover", function(e){
                        e.stop();
                        sideBarElement.fire(gg.SideBarEvent.MouseOverGoogleLocalResult, {
                            id: descriptor.id
                        })
                    });
                    if (gg.debug) {
                        gg.log("The element is %o", element)
                    }
                }
                else {
                    if (gg.debug) {
                        gg.log("Element has not been set!")
                    }
                }
            });
            voiceMarkDescriptors.each(function(descriptor){
                var element = $(descriptor.elementId);
                if (element) {
                    element.stopObserving("click");
                    element.observe("click", function(e){
                        e.stop();
                        if (gg.debug) {
                            gg.log("going to fire a click b/c someone clicked on VM %s for %o", descriptor.elementId, e)
                        }
                        var event = sideBarElement.fire(gg.SideBarEvent.VoiceMarkLinkClicked, {
                            id: descriptor.id
                        });
                        if (gg.debug) {
                            gg.log("I stopped e...now i'm going to see if event was stopped...%o", event.stopped)
                        }
                    });
                    element.stopObserving("mouseover");
                    element.observe("mouseover", function(e){
                        sideBarElement.fire(gg.SideBarEvent.MouseOverVoiceMarkResult, {
                            id: descriptor.id
                        })
                    });
                    if (gg.debug) {
                        gg.log("The element is %o", element)
                    }
                }
                else {
                    if (gg.debug) {
                        gg.log("Element has not been set!")
                    }
                }
            });
            try {
                $$(".vmusername").each(function(userNameContainer){
                    userNameContainer.stopObserving("click");
                    userNameContainer.observe("click", function(e){
                        e.stop();
                        var sourceElement = e.element();
                        var id = sourceElement.identify();
                        var memo = {
                            userId: null,
                            userName: null,
                            isAnonymous: null
                        };
                        if (id.startsWith("vmusername-anonymous-")) {
                            memo.userId = id.gsub("vmusername-anonymous-", "");
                            memo.userName = sourceElement.textContent;
                            memo.isAnonymous = true
                        }
                        else {
                            memo.userId = id.gsub("vmusername-", "");
                            memo.userName = sourceElement.textContent;
                            memo.isAnonymous = false
                        }
                        sideBarElement.fire(gg.SideBarEvent.ResultUserNameClicked, memo)
                    })
                })
            } 
            catch (e) {
                gg.error("ERROR %o", e)
            }
            self.activatePaging(cursor)
        }
    }
}();
geograffiti.SideBar.load();

