﻿/*global window $ console google escape */
var Linfo;

(function initfbx() {
    if (!window.console || !console.firebug) {
        var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

        window.console = {};
        var empty = function() { };

        for (var i = 0; i < names.length; ++i) {
            window.console[names[i]] = empty;
        }
    }
} ());

Linfo = {
    emptyFn: function() { },
    boolFn: function(b) { return function() { return b; }; },
    stringFn: function(s) { return function() { return s; }; },

    isThing: function(d) {
        return d.__type == "Linfo.Data.FavoriteThing" || d.__type == "Linfo.Data.FavoriteHybridThing";
    },
    
    escapeName: function(n) {
        return n.toLowerCase()
            .replace(/[^a-z0-9]+/ig, '-')
            .replace(/^-+|-+$/g, '');
    },

    setLocationCookie: function(loc) {
        $.cookie("linfo_location", $.toJSON({
            ZipCode: loc.ZipCode,
            Latitude: loc.Lat,
            Longitude: loc.Lng,
            City: loc.Location
        }), { path: '/', expires: 30 });
    },

    A: function(spec) {

        spec = $.extend({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            cache: false,
            dataType: "json",
            success: spec.success || function() { },
            error: spec.error || function() { }
        }, spec);

        var blockf = function() { };
        var unblockf = function() { };

        if (typeof (spec.maskEl) !== 'undefined') {
            blockf = function() {
                $(spec.maskEl).block({
                    css: { border: 'none', backgroundColor: 'transparent' },
                    overlayCSS: { backgroundColor: '#FFFFFF' },
                    message: '<img src="/static/images/icon-wait-30x30.png" class="wait" />'
                });

                /* Item Auto-saved message
                $(spec.maskEl).block({
                css: { border: 'none', backgroundColor: 'transparent' },
                overlayCSS: { backgroundColor: '#FFFFFF' },
                message: '<span class="auto-save">Saved</span>'
                });
                */
            };
            unblockf = function() { $(spec.maskEl).unblock(); };
        }

        var olds = spec.success;
        var olde = spec.error;
        spec.success = function(d) { unblockf(); olds(d); };
        spec.error = function(d) { unblockf(); olde(d); };

        blockf();
        $.ajax(spec);
    }
};

Linfo.Templates = {
    
    LOCATION_SEARCH_AUTO_COMPLETE: $.template([
        '<a href="#">',
            '<span class="name">${Name}</span>',
            '<span class="details">${Address}</span>',
        '</a>'
        
    ].join('')),
    
    EMPTY_LOCATION_SEARCH_AUTO_COMPLETE: $.template([
        'No results found.'
    ].join('')),
    
    FRIEND_SEARCH_AUTO_COMPLETE: $.template([
        '<a href="#">',
            '<img src="${pic_square}" title="${first_name} ${last_name}" />',
            '<span class="user-name">${first_name} ${last_name}</span>',
        '</a>'
    ].join('')),

    FAVORITE_PLACE_FILLED_LIST_ITEM: $.template([
        '<a class="item" href="#">',
            '<span class="photo"><img class="thumb" src="${DefaultImageUri}" /></span>',
            '<span class="title">${Name}</span>',
            '<span class="number">${Number}</span>',
            '<span class="controls">',
                '<span class="edit-photo" title="Add/Edit Photo"></span>',
                '<span class="edit-note" title="Add/Edit Comment"></span>',
                '<span class="remove" title="Remove from list" number="${Number}" UsersLinfoId="${UsersLinfoId}"></span>',
            '</span>',
        '</a>'
    ].join('')),

    FAVORITE_PLACE_EMPTY_LIST_ITEM: $.template([
        '<a class="item" href="#">',
            '<span class="number">${index}</span>',
            '<em>Empty</em>',
        '</a>'
    ].join('')),

    ADDED_PLACE_LIST_ITEM: $.template([
        '<a href="#" title="${Name}"><img src="${DefaultImageUri}" /></a>'
    ].join('')),

    FAVORITE_THING_FILLED_LIST_ITEM: $.template([
        '<a href="#">',
            '<span class="count">${Number}</span>',
            '<span class="photo"><img alt="" src="${DefaultImageUri}"/></span>',
            '<span class="name">${Name}</span>',
            '<span class="controls">',
                '<span class="edit" title="Add/Edit Photo"></span>',
                '<span class="remove" title="Remove from list" number="${Number}" UsersLinfoId="${UsersLinfoId}"></span>',
            '</span>',
        '</a>'
    ].join('')),

    FAVORITE_THING_EMPTY_LIST_ITEM: $.template(
        '<a href="#">',
            '<span class="count">${Number}</span>',
            '<em>Empty</em>',
        '</a>'),

    SUGGESTION_LIST_ITEM: $.template([
        '<li class="row" linfoid="${LinfoId}"><a href="#">',
            '<span class="photo"><img class="suggestedImage" src="${DefaultImageUri}"/></span>',
            '<span class="name">${DisplayName}</span>',
            '<span class="btn-add">+Add</span>',
        '</a></li>'
    ].join('')),

    FAVORITE_PEOPLE_ITEM: $.template([
        '<li class="friend" uid="${uid}"><a href="#${uid}">',
            '<span class="photo"><img src="${pic}" title="${name}" alt="${name}" /></span>',
            '<span class="name">${name}</span>',
            '<span class="status"></span>',
            '<span class="controls"><span class="add" userid="${uid}"></span></span>',
        '</a></li>'
    ].join('')),

    BUSINESS_LISTING_EMPTY_ITEM: $.template([
        '<b>New Business Listing Name</b><br />',
        '<a href="#" id="addInfo">Click to add info</a>'
    ].join('')),

    BUSINESS_LISTING_FILLED_ITEM: $.template([
        '<h5>${businessName}</h5>',
        '<p class="info">',
            '<span class="street">${businessAddress}</span>',
            '<span class="city-zip">${businessCity} ${businessZip}</span>',
            '<span class="phone">${businessPhone}</span>',
        '</p>'
    ].join('')),

    FAVORITE_PEOPLE_SIDE_ITEM: $.template([
            '<a href="#" class="item">',
                '<span class="count">${number}</span>',
                '<span class="photo"><img src="${pic_square}" alt="" /></span>',
                '<span class="name">${name}</span>',
                '<span class="remove" title="Remove from list"></span>',
            '</a>'   
    ].join('')),
    FAVORITE_PEOPLE_SIDE_ITEM_SQUARE: $.template([
            '<a href="#">',
                '<span class="count">${number}</span>',
                '<span class="photo"><img src="${pic_square}" title="${name}" alt="${name}" /></span>',
                '<span class="name">${name}</span>',
                '<span class="controls"><span class="remove" userid="${uid}"></span></span>',
            '</a>'
        ].join('')),
    FAVORITE_PEOPLE_EMPTY_SIDE_ITEM: $.template([        
            '<a href="#" class="item">',
                '<span class="count">${number}</span>',
                '<em>Empty</em>',
            '</a>'       
    ].join('')),
    FAVORITE_PEOPLE_EMPTY_SIDE_ITEM_SQUARE: $.template([
            '<a class="item" href="#">',
                '<span class="count">${number}</span>',
            '</a>'
    ].join('')),
    USERPROFILE_DEFAULT_ITEM: $.template([
        '<li>',
            '<img src="${DefaultImageUri}" alt="${Name}" />',
            '<span class="count">${Number}</span>',
        '</li>'
    ].join('')),

    USERPROFILE_PLACE_ITEM: $.template([
        '<li><a href="/place/${Name}/${LinfoId}">',
            '<img src="${DefaultImageUri}" alt="${Name}" /><span class="count">${Number}</span>',
        '</a></li>'
    ].join('')),

    USERPROFILE_USER_ITEM: $.template([
        '<li><a href="/user/${Name}/${UserId}">',
            '<span class="photo"><fb:profile-pic linked="false" uid="${FacebookId}"></fb:profile-pic></span>',
            '<span class="count">${Number}</span>',
        '</a></li>'
    ].join('')),

    GENERIC_FAVORITE_FILLED_LIST_ITEM: $.template([
        '<a href="#" class="filled">',
        	'<span class="count">${Number}</span>',
            '<span class="photo">',
                '<img src="${DefaultImageUri}" alt="" height="46" width="46" />',
                '<span class="edit-photo" title="Change Photo"></span>',
            '</span>',
            '<span class="name">${Name}</span>',
            '<span class="controls">',
                '<span class="edit-note" title="Change Note"></span>',
                '<span class="remove" title="Remove" number="${Number}" id="${UsersLinfoId}" UsersLinfoId="${UsersLinfoId}">&nbsp;</span>',
            '</span>',
         '</a>'
    ].join('')),

    GENERIC_FAVORITE_FRIEND_FILLED_LIST_ITEM: $.template([
        '<a href="#" class="filled">',
        	'<span class="count">${number}</span>',
            '<span class="photo"><img src="${pic_square}" alt="" height="50" width="50" /></span>',
            '<span class="name">${name}</span>',
            '<span class="controls">',                
                '<span class="remove" title="Remove" number="${number}" id="fb-${uid}" UsersLinfoId="${uid}">&nbsp;</span>',
            '</span>',
         '</a>'
    ].join('')),
    GENERIC_FAVORITE_EMPTY_LIST_ITEM: $.template([
        '<li class="item"><div class="empty">',
            '<span class="count">${Number}</span><em>Empty</em>',
        '</div></li>'
    ].join('')),
    
    GENERIC_LIST_EMPTY: $.template([
        '<div class="popup-list"><div class="content">',
            '<ul class="items"></ul>',
        '</div></div>'
    ].join('')),
        
    GENERIC_LIST_ALL_HEADER: $.template([
        '<a href="#" class="btn-close" onclick="tb_remove(); return false;">Close</a>',
        '<ul class="head">',
            '<li class="avatar">',
                '<a href="/user/${UserName}/${UserId}"><fb:profile-pic linked="false" uid="${FacebookId}" size="s"></fb:profile-pic></a>',
            '</li>',
            '<li class="heading"><h3>',
                '<span class="user"><a href="/user/${UserName}/${UserId}">${UserName}</a> created</span>',
                '<span class="title">${Title}</span>',
                '<span class="details">&nbsp;<em>on</em>&nbsp;<span class="date">${Date}</span>',
                '&nbsp;<em>@</em>&nbsp;<span class="time">${Time}</span></span>',
            '</h3></li>',
        '</ul><!-- /head -->'
    ].join('')),
    
    GENERIC_FAVORITE_PLACE_LIST_ALL: $.template([        
        '<li class="item">',
            '<span class="count">${Number}</span>',
            '<a class="photo" href="/place/${UrlEncodedName}/${LinfoId}"><img src="${DefaultImageUri}" alt="" /></a>',
            '<div class="description">',
                '<h5 class="title"><a href="/place/${UrlEncodedName}/${LinfoId}">${Name}</a></h5>',
                '<p class="details">',
                    '<span>${Address}</span>',
                    '<span>${City}, ${State} ${Zip}</span>',
                '</p>',
            '</div>',
        '</li>'
    ].join('')),

    GENERIC_FAVORITE_THING_LIST_ALL: $.template([
        '<li class="item thing">',
            '<span class="count">${Number}</span>',
            '<span class="photo"><img src="${DefaultImageUri}" alt="" /></span>',
            '<div class="description">',
                '<h5 class="title">${Name}</h5>',
            '</div>',
        '</li>'
    ].join('')),
                                                        
    GENERIC_FAVORITE_FRIENDS_LIST_ALL: $.template([
        '<li class="item person">',
            '<span class="count">${Number}</span>',
            '<a class="photo" href="/user/${Name}/${Id}"><fb:profile-pic linked="false" uid="${FacebookId}"></fb:profile-pic></a>',
            '<div class="description">',
                '<h5 class="title"><a href="/user/${Name}/${Id}">${Name} ${LastName}</a></h5>',
            '</div>',
        '</li>'
        
    ].join('')),
    
    POPUP_ADD_EDIT_NOTE: $.template([
        '<div class="description"><h5>My Note:</h5>',
            '<div class="note">',
                '<p class="status">You have not added a comment yet.</p>',
                '<textarea cols="20" rows="2" disabled id="note-textarea">${Comment}</textarea>',
            '</div><ul class="controls">',
                '<li class="save"><a id="note-save" href="#" class="btn">Save</a></li>',
                '<li class="remove"><a id="note-remove" href="#" class="btn">Remove</a></li>',
                '<li class="edit"><a id="note-edit" href="#" class="btn">Edit</a></li>',
                '<li class="add"><a id="note-add" href="#" class="btn">Add</a></li>',
            '</ul>',
        '</div>'
    ].join(''))
    
};﻿/*global window $ Linfo console google */

Linfo.Selectors = {
    FavoritePlaces: {
        SUGGESTION_ITEM_CONTAINER: '#suggestions .items',
        SUGGESTION_ITEM: '#suggestions .items .row',
        INPUT_BOX: '#textbox-add-item',
        FIRST_EMPTY_ITEM: '#added-items > li.empty',
        FILLED_ITEM: '#added-items li.filled',
        DELETE_ITEM_LINK: '#added-items li .btn-remove',
        functionName: function (e) {
            return this.SUGGESTION_ITEM + e;
        }

    },

    FavoriteThings: {
        FIRST_EMPTY_ITEM: '#added-items > li.empty',
        FILLED_ITEM: '#added-items li.filled',
        SORTABLE_LIST: '#added-items',
        INPUT_BOX: '#textbox-add-item',
        DELETE_ITEM_LINK: '#added-items li .btn-remove'
    }
};﻿/*global window $ Linfo console google */

Linfo.LinfoAjaxList = $.klass({
    initialize: function(config) {
        $.extend(this, $.extend({
            name: "",
            getListName: function() { return ""; },
            LIST_SERVICE_URL_BASE: '/services/ListService.asmx/',
            ITEM_SELECTOR: 'ul.items li.filled',
            maskEl: undefined,
            path: ""
        }, config));
    },


    getServiceUrlAbsolute: function(s) {
        return this.LIST_SERVICE_URL_BASE + s;
    },

    getServiceUrl: function(op) {
        return this.serviceUrl || this.getServiceUrlAbsolute('Get' + op + 'List');
    },

    getListPath: function() {
        return this.path || ('/lists/' + this.name);
    },

    onListLoad: function(d) {

    },
    onListLoadError: function(d) { },

    listHasDupes: function() {
        var a = [];
        var listItems = $.pluck(this.getListItems(), 'ItemId');

        var dedupe = $.map(listItems, function checkDupe(v) {
            if ($.inArray(v, a) === -1) {
                a.push(v); return v;
            }
        });

        return dedupe.length !== listItems.length;
    },

    reorderList: function() {
        var self = this;
        $(this.ITEM_SELECTOR).each(function(i, v) {
            //console.log(i, v);
            var idx = i + 1;
            if ($(v).is(".empty")) {
                $(v).html(self.EMPTY_ITEM_TEMPLATE.apply({ index: idx }));
            }
            else {
                v.selectedData.Number = idx;
                v.selectedData.number = idx;
                //need to override the template for the case where you ahve two controllers attached to the same selectors                
                if (self.path.indexOf("/twenty") > 0 || typeof (v.selectedData.faceBookUserId) === "undefined") {

                    $(v).html(self.FILLED_ITEM_TEMPLATE.apply(v.selectedData));
                }
                else {

                    $(v).html(Linfo.Templates.GENERIC_FAVORITE_FRIEND_FILLED_LIST_ITEM.apply(v.selectedData));
                }
            }
        });
    },

    getListItems: function() {
        return $.map($(this.ITEM_SELECTOR + '.filled'), function(item, idx) {
            return { ItemId: item.selectedData.UsersLinfoId, ItemOrder: idx };
        });
    },

    loadListByPath: function(type, path) {
        this.type = type.split('.')[2];
        this.path = path;

        this.loadList();
    },

    loadList: function() {
        var self = this;
        if (this.creatingNew) { return; }
        var path = self.path;

        Linfo.A({
            url: this.getServiceUrl(this.type),
            data: this.getParameterData(),
            cache: false,
            maskEl: this.maskEl,
            success: function(d) {
                self.onListLoad(d, path, self.type);
            },
            error: function(d) {
                self.onListLoadError(d);
            }
        });
    },
    getParameterData: function() {
        return $.toJSON({ path: this.getListPath() });
    },

    saveList: function() {
        var self = this;
        console.log(this.getListName(), 'list name');
        var data = {
            path: this.getListPath(),
            listItems: self.getListItems()
        };        
        var url = self.getServiceUrlAbsolute('SaveListWithName');
        $.extend(data, { name: this.getListName() });

        $.ajax({
            type: "POST",
            url: url,
            data: $.toJSON(data),
            contentType: "application/json; charset=utf-8",
            cache: false,
            dataType: "json",
            success: function(msg) { self.HandleSaveListSuccess(msg); },
            error: function(msg) { }
        });
    }
});﻿/*global window $ Linfo console google */

Linfo.FriendSearchAutoComplete = $.klass({
    initialize: function(inputElement, data, completerConfig) {

        this.RESULT_TEMPLATE = Linfo.Templates.FRIEND_SEARCH_AUTO_COMPLETE;
        var self = this;

        $(inputElement).autocomplete(data.user, {
            matchSubset: 1,
            matchContains: 1,
            scroll: false,
            resultsClass: "ac-find-friends",
            delay: 25,
            cacheLength: 1,
            formatMatch: function(o) { return o.name; },
            formatItem: completerConfig.formatItem || function(o) { return self.formatItem(o); }
        }).bind("result", completerConfig.handleResult || this.handleResult);
    },
    handleResult: function(e, selectedData) {
        console.log(arguments);
    },
    formatItem: function(data) {

        if (typeof (data.last_name) == "undefined") {
            return "No results found"; 
        }
        else {

            return this.RESULT_TEMPLATE.apply(data);
        }
    }
});
﻿/*global $ Linfo console */

Linfo.LinfoCityAutoComplete = $.klass({
    initialize: function(inputElement, completerConfig) {
        this.URL_BASE = '/services/SearchService.asmx/LinfoAutoCompleter';
        this.RESULT_TEMPLATE = $.template("${Location}");
        this.lastSavedLocation = "Santa Monica, CA";
        $.extend(this, completerConfig);
        var self = this;

        var resultHandler = completerConfig.handleResult || this.handleResult;
        var handler = function(i, d, v) {
            self.lastSavedLocation = d.Location;
            return resultHandler(i, d, v);

        };
        this.acEl = $(inputElement).autocomplete(this.URL_BASE, {
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            minChars: 3,
            matchSubset: true,
            dataType: 'json',
            scroll: false,
            delay: 100,
            mustMatch: true,
            multiple: false,
            multipleSeparator: "---",
            cacheLength: 1000,
            parse: completerConfig.parse || function(o) { return self.parseResult(o); },
            formatItem: completerConfig.formatItem || function(data) { return self.formatItem(data); },
            clearOnBlur: false
        }).bind("result", handler);

        //set on blur for the where input box.. if the city is not found, reset to default location.
        $(inputElement).blur(function() {
            $(self.acEl).search(function(searchResult) {
                if (typeof (searchResult) === "undefined") {
                    $(inputElement).val(self.lastSavedLocation);
                }
                else {
                    $(self.acEl).trigger("result", [searchResult.data, searchResult.value]);
                    $("#textbox-add-item").focus();
                }
            });
        });

    },
    handleCityNotFound: function(data) {

    },
    formatItem: function(data) {
        if (typeof (data.Location) != "undefined") {
            return this.RESULT_TEMPLATE.apply(data);
        }
        else {
            return "No city found.";
        }
    },

    handleResult: function(selectionInfo, selectedData, value) {
        console.log('result'); return false;
    },

    parseResult: function(o) {
        var self = this;
        //console.log(o,"parseResult");        
        //        if (o.d.length === 0) {
        //            //$("#textbox-add-item").attr("disabled", true);
        //            //console.log("no city was found disable teh what box");
        //            var newObj = {};
        //            newObj.Name = 'No city found';
        //            newObj.data = {};
        //            newObj.value = 'invalid city';
        //            newObj.result = 'invalid city';
        //            o.d[0] = newObj;

        //            return o.d;
        //        }
        ////        else {
        ////            $("#textbox-add-item").attr("disabled", false);
        ////        }


        return $.map(o.d, function(doc, idx) {
            return { data: doc, value: doc.Location, result: doc.Location };
        });
    }
});
﻿/*global window $ Linfo console google SWFUpload controller*/

/*
    events
    | - ui
    | | - list-editor
    |   | - behavior
    |     | - suggestion-click
    |     | - photo-upload
    |     | - edit-listing 
    | - list-metrics
    | | - [favoriteplaces|favoritethings|favoritepeople]
    |   | - create
    |   | - aborted
    |   | - dupes
    |   - create
    |   - aborted
    |   - count-at-unload
    |   - count-at-time
    |   | - [20,40,60,80,100] 
*/

Linfo.EventTracker = $.klass({
    TIMED_TRACKER_SEGMENTS: 5,
    TIMED_TRACKER_SEGMENT_TIME: 20000,

    track: function() {
        var u = '/events/' + Array.prototype.slice.call(arguments).join('/');
        console.log('tracking', u);
        this.pageTracker._trackPageview(u);
    },

    initialize: function(t) {
        this.pageTracker = t;
    },

    startTrackingCount: function(page) {
        var self = this;
        var f = $.curry(function(page, itr) { self.trackTimedCount(page, itr); }, page);

        $(window).everyTime(this.TIMED_TRACKER_SEGMENT_TIME, f, this.TIMED_TRACKER_SEGMENTS);

        if (controller.getFilledItemCount() === 0) {
            self.track('list-metrics', page, 'create');
            self.track('list-metrics', 'create', page);
        }

        $(window).bind("beforeunload", function(e) {
            var c = controller.getFilledItemCount();
            if (c < controller.MIN_TO_PROCEED) {
                self.track('list-metrics', page, 'aborted');
                self.track('list-metrics', 'aborted', page);
            }
            self.track('list-metrics', 'count-at-unload', page, c);
        });
    },

    trackFriendGroupShare: function() {
        this.track('ui', 'list-editor', 'behavior', 'share', 'fb-friend-group');
    },

    trackTwitter: function() {
        this.track('ui', 'list-editor', 'behavior', 'share', 'twitter');
    },

    trackEditListingClick: function() {
        this.track('ui', 'list-editor', 'behavior', 'edit-listing');
    },

    trackUploadPhoto: function() {
        this.track('ui', 'list-editor', 'behavior', 'photo-upload');
    },

    trackSuggestionClick: function(listType) {
        this.track('ui', 'list-editor', 'behavior', 'suggestion-click', listType);
    },

    trackListCreated: function(listType, dupes) {
        var hasDupes = dupes ? "dupes" : "nodupes";

        this.track('list-metrics', listType, 'created');
        this.track('list-metrics', listType, 'dupes', hasDupes);
        this.track('list-metrics', 'dupes', hasDupes);
    },

    trackTimedCount: function(page, itr) {
        console.log(this, arguments);
        var seconds = itr * (this.TIMED_TRACKER_SEGMENT_TIME / 1000);

        this.track('list-metrics', 'count-at-time', page.toLowerCase(), seconds, controller.getFilledItemCount());
    }
});﻿/*global $ Linfo FB linfo_DataStore console tb_show window*/

Linfo.Facebook = {
    streamPublishPrompt: function() {
        var perm = 'publish_stream';

        FB.Facebook.apiClient.users_hasAppPermission(perm, function(ok) {
            console.log('hasAppPerm', arguments);
            if (ok === 0) {
                FB.Connect.showPermissionDialog(perm, function() { console.log('showPermDialogResult', arguments); });
            }
        });
    },

    handleLoginOverlay: function() {
        console.log('handleloginoverlay');
        var tpl = $.template('<li><img src="${DefaultImageUri}" /><span class="count">${Number}</span></li>');

        $.each(linfo_DataStore.Places.slice(0, 5), function(i, v) {
            var sd = this.Value;

            $('#new-fb-user-overlay .top-5').append(tpl.apply($.extend(sd, { Number: i + 1 })));
        });

        //        FB.Facebook.get_sessionState().waitUntilReady(function popupPreview() {
        //            console.log('fb.ss().ready', arguments);
        $('#popup-preview').show();
        tb_show(null, '#TB_inline?height=325&width=500&inlineId=new-fb-user-overlay&modal=true');
        //        });
    },

    emailPermissionPrompt: function() {
        var perm = 'email';

        FB.Facebook.apiClient.users_hasAppPermission(perm, function(ok) {
            console.log('hasAppPerm', arguments);
            if (ok === 0) {
                FB.Connect.showPermissionDialog(perm, function() { console.log('showPermDialogResult', arguments); });
            }
        });
    },

    onConnected: function(user_id) {

        var reqCompleted = Linfo.userOpts.hasCompletedRequirements;
        var isViewing = linfo_DataStore.IsViewingUser;

        console.log('fb.onconnected', isViewing, arguments);
        if (!isViewing && reqCompleted !== true) {
            window.location = "/home/auth";
        } else if (isViewing && reqCompleted === true) {
            window.location = '/user/' + linfo_DataStore.ViewedUserName + '/' + linfo_DataStore.ViewedUserId + '/share';
        } else if (isViewing && reqCompleted !== true) {
            //request requirement completion status
            //if returned true then redirect to share page else show overlay
            Linfo.A({
                url: "/services/ListService.asmx/HasCompletedRequirements",
                data:  $.toJSON({ FaceBookId: user_id }),
                cache: false,
                success: function(d) {
                    if (d.d === true) {
                        window.location = '/user/' + linfo_DataStore.ViewedUserName + '/' + linfo_DataStore.ViewedUserId + '/share';
                    }
                    else {
                        Linfo.Facebook.handleLoginOverlay();
                    } 
                },
                error: function(d) {

                }
            });
            //Linfo.Facebook.handleLoginOverlay();
        }
    },

    onNotConnected: function() {
        console.log('fb.onNotConnected', arguments);
        if (linfo_DataStore.IsViewingUser) {
            Linfo.Facebook.handleLoginOverlay();
        }
        return false;
    },

    login: function() {
        FB.Facebook.get_sessionState().waitUntilReady(function() {
            window.location = "/home/auth";
        });
        FB.Connect.requireSession();
    }
};
﻿/*global $ Linfo console */

Linfo.FlowManager = $.klass({
    initialize: function(config) {
        this.userOpts = config.userOpts || {};

        this.profileLinkMessage = "Please finish all ‘People, places, things’ lists to gain access to your home page";
        this.peopleIncompleteMessage = "Oops, you have to complete the 'People' list first";
        this.placesIncompleteMessage = "Oops you have to complete the 'Place' list before 'Things' list";

        var tip = function(m) { return { type: 'tip', message: m }; };
        var enc = function(m) { return { type: 'incentive', message: m }; };
        var err = function(m) { return { type: 'error', message: m }; };
        
        this.progressTemplate = $.template('<p class="message"><span class="${type}">${message}</span></p>');

        this.progressCount = {
            things: 0, places: 0, people: 0
        };

        this.progressMessaging = {
            people: [
                tip('Browse through your friends and click a picture to add.'),
                tip('Type a friend’s name for suggested matches.'),
                tip('Re-click a friend’s picture to cancel selection.'),
                tip('Don’t worry.  Your lists save automatically.  '),
                tip('Sort your list by drag and drop.'),
                tip('Delete friend by clicking the minus sign.'),
                tip('Only one more to go.'),
                enc('Great List! Click NEXT to save and continue.')
            ],

            places: [
                tip('Typing in at least 3 letters will offer possible matches.'),
                tip('Add any U.S. city.'),
                tip('Add a new listing if it doesn’t come up in search.'),
                tip('Change the photo by clicking the photo icon.'),
                tip('Add a popular suggestion to your list from the right. '),
                tip('Delete a place by clicking the minus sign.'),
                tip('Sort your list by drag and drop.'),
                enc('Awesome Place List! Click NEXT to save and continue.')
            ],

            things: [
                tip('Typing in at least 3 letters will offer possible matches.'),
                tip('Add a popular suggestion to your list from the right.'),
                tip('Delete a thing by clicking on the minus sign.'),
                tip('Sort your list by drag and drop.'),
                tip('Don’t see it? Type in your thing anyway, then click Add.'),
                tip('Don’t worry.  Your lists are saved automatically.'),
                tip('Anything can be added to your list.'),
                enc('Cool Things List! Click NEXT to save and continue.')
            ]
        };

        this.tabs = [
            'people',
            'places',
            'things'
        ];

        $.extend(this, config);
        console.log('lfm init');
    },

    getProgressMessage: function(type, count) {
        return this.progressMessaging[type][count];
    },

    getFormattedProgressMessage: function(type, count) {
        return this.progressTemplate.apply(this.getProgressMessage(type, count));
    },

    emptyProgress: function() {
        var pg = $('#progress');
        $('.message', pg).remove();
        return pg;
    },

    updateProgressError: function(m) {
        this.emptyProgress()
            .prepend(this.progressTemplate.apply({ type: 'error', message: m }));
    },

    updateProgressMessaging: function(type, count) {
        if (this.progressMessaging[type].length <= count)
            return;
            
        this.emptyProgress()
            .prepend(this.getFormattedProgressMessage(type, count));
    },

    getTab: function(name) {
        return $('#nav-main .' + name + ' a');
    },

    activateTab: function(tab) {
        this.getTab(tab).addClass('active');
    },

    enableHref: function(anchor) {
        var oldurl = anchor.attr('oldurl');
        if (oldurl) {
            anchor.attr('href', oldurl);
        }
    },

    disableHref: function(anchor) {
        var oldurl = anchor.attr('href');
        anchor.attr('href', '#');
        anchor.attr('oldurl', oldurl);
    },

    handleListCompletion: function(which) {
        console.log('FlowControl::handleListCompletion', which);
        if (which === 'people') { this.reactivateTab('places'); }
        if (which === 'places') { this.reactivateTab('things'); }
        if (which === 'things') { this.enableProfileLinks(); }
    },

    deactivateTabs: function(tabs, message) {
        var self = this;

        $.each(tabs, function(i, v) {
            self.disableHref(self.getTab(v));
        });

        if (typeof message !== 'undefined') {
            $('[oldurl]').qtip({
                content: message,
                style: { name: 'dark' },
                position: { corner: { target: 'bottomMiddle', tooltip: 'topMiddle'} }
            });
        }

    },

    enableListsTab: function() {
        $('#nav-main').append(
            '<li id="create-list"><a href="#" class="list">Add New Lists</a><ul><li class="select"><strong>Select Type</strong></li><li><a href="/home/lists/hybrid/new">People</a></li><li><a href="/home/lists/places/new">Places</a></li><li><a href="/home/lists/things/new">Things</a></li></ul></li>'
        );
        $("#nav-main .list").click(function() {
            $("#create-list ul").slideToggle(200); return false;
        });
        
        $('#user-nav .nav-panel').append(
            '<a href="/user/' + Linfo.userOpts.userName + '/' + Linfo.userOpts.userId + '#lists-list">Profile</a><a href="/user/' + Linfo.userOpts.userName + '/' + Linfo.userOpts.userId + '#friend-list">Friends</a><a href="/user/' + Linfo.userOpts.userName + '/' + Linfo.userOpts.userId + '#note-list">Comments</a><a href="/user/' + Linfo.userOpts.userName + '/' + Linfo.userOpts.userId + '/share">My Favorites</a>'
        );
        $("#user-info .user-name").click(function() {
	        $("#user-info .nav-panel").slideToggle(200);
	        $("#user-info .user-name").toggleClass("active"); return false;
        });
        $('#user-nav').toggleClass('active');
        $('#nav-main li').toggleClass('enabled');
    },

    reactivateTab: function(tab) {
        var anchor = this.getTab(tab);
        var oldurl = anchor.attr('oldurl');
        if (oldurl) {
            anchor.qtip('destroy');
            anchor.attr('href', oldurl);
        }
    },

    deactivateTabsIf: function(tabs, exp, message) {
        if (exp) {
            this.deactivateTabs(tabs, message);
        }
    },

    enableProfileLinks: function() {
        var self = this;
        $('#user-info a').slice(0, 2).each(function(i, v) {
            self.enableHref($(this));
        });
        
    },
    
    

    disableProfileLinksIf: function() {
        var self = this;

        if (this.userOpts.hasCompletedRequirements !== true) {
            $('#user-info a').slice(0, 2).each(function(i, v) {
                self.disableHref($(this));
            });
        } else {
            this.enableListsTab();
        }
    },

    initPeople: function() {
        this.activateTab('people');
        this.disableProfileLinksIf();
        this.deactivateTabsIf(
            ['places', 'things'],
            !this.userOpts.hasCompletedFriends,
            this.peopleIncompleteMessage
        );
    },

    initPlaces: function() {
        this.activateTab('places');
        this.disableProfileLinksIf();
        this.deactivateTabsIf(
            ['things'],
            !this.userOpts.hasCompletedPlaces,
            this.placesIncompleteMessage
        );
    },

    initThings: function() {
        this.activateTab('things');
        this.disableProfileLinksIf();
    },

    initShare: function() {
        this.disableProfileLinksIf();
    },

    initProfile: function() {
        this.disableProfileLinksIf();
    },

    initListing: function() {
        this.disableProfileLinksIf();
    },

    initListEdit: function() {
        this.disableProfileLinksIf();
    }
});﻿/*global window $ Linfo console google SWFUpload */
Linfo.ListingPopup = $.klass({
    DEFAULT_POP_ELEMENT: '#popup-large',
    DEFAULT_ITEM_SELECTOR: 'li.filled',
    DEFAULT_POP_ID: 'popup-large',
    LINFO_ID: 0,
    CURRENT_INDEX: 0,
    TOP_OFFSET: 250,
    currentLinfoId: 0,
    ADD_NOTE_SERVICE: "/services/Listservice.asmx/AddNote",
    currentIndexId: "",
    currentSelectedData: {},
    IMAGE_UPLOAD_SERVICE: "/services/ListService.asmx/InsertLinfoImage",
    addNew: false,
    IsOwner: true,
    itemType: "linfo",
    setMenuOptions: function() { },
    getNextListElement: function() { },
    DEFAULT_SCROLLABLE_ID: '.picker-panel',
    tpl: $.template('<b>${Name}</b><br/>${Address}<br/>${City}, ${Zip}'),
    tpl_edit: $.template('<div class="photo"><img src="${DefaultImageUri}" height="100" width="100" alt="${Name}" /></div><h5><a href="/place/${UrlEncodedName}/${LinfoId}" class="name">${Name}</a></h5><p class="locality"><span class="street">${Address}</span><span class="address"><span class="city">${City} </span><span class="state">${State} </span><span class="zip"> ${Zip}</span></span><span class="phone">${Phone}</span></p>'),
    tpl_edit_thing: $.template('<div class="photo"><img src="${DefaultImageUri}" height="100" width="100" alt="${Name}" /></div><h5>${Name}</h5>'),
    emitMarkup: function() {
        var self = this;
        $('#canvas').append([
         '<div id="popup-large">',
            '<div class="container">',
                '<h4>',
                    '<a href="#" class="btn-close">Close</a>',
                    '<span class="title">Listing Info</span>',
                '</h4>',
                '<ul class="content">',
                    '<li class="details">',
                    '</li><!-- /details -->',
                    '<li class="tabbed-content">',
                        '<ul class="nav">',
                            '<li><a  href="#tab-photo" class="tab-photo">Photo</a></li>',
                            '<li><a href="#tab-note" class="tab-note">Comment</a></li>',
                            '<li><a href="#tab-listing" class="tab-listing" style="display:none">Listing</a></li>',
                        '</ul><!-- / nav -->',
                        '<ul class="tabs">',
                            '<li class="tab" id="tab-photo">',
                                '<ul>',
                                    '<li class="caption">',
                                        '<label for="photo-caption">Caption</label>',
                                        '<input type="text" class="textbox" id="photo-caption" value="Name or describe your photo" />',
                                    '</li>',
                                    '<li class="upload">',
                                        '<p id="desktopSelector">UPLOAD FROM DESKTOP</p>',
                                        '<p>Upload from desktop requires <a href="http://get.adobe.com/flashplayer/" target="_blank">Flash</a></p>',
                                        '<p>No more than 5 MB per photo. Acceptable Formats: jpg, png, gif</p>',
                                    '</li>',
                                    '<li class="browse">',
                                        '<h6><em>Or</em> Choose picture below</h6>',
                                        '<ul class="picker-panel">',
                                            '<li class="control-prev"><a class="btn-prev" href="#">Previous</a></li>',
                                            '<li class="items">',
                                            '<fieldset>',
                                                '<ul class="items">',
                                                '</ul>',
                                            '</fieldset>',
                                            '</li>',
                                            '<li class="control-next"><a class="btn-next" href="#">Next</a></li>',
                                        '</ul><!-- /picker-panel -->',
                                    '</li><!-- /browse -->',
                                '</ul>',
                            '</li><!-- /tab-photo -->',
                            '<li class="tab" id="tab-note">',
                                '<h6>My Comment:</h6>',
                                '<textarea rows="4" cols="40" id="note-textarea">You haven\'t added a comment yet.</textarea>',
                                '<div class="progress">',
                                    '<span class="count">140</span> characters remaining',
                                '</div>',
                            '</li>',
                            '<li class="tab" id="tab-listing">',
                                '<ul class="inputs">',
                                    '<li class="wide">',
                                        '<label for="businessName">Business Name</label>',
                                        '<input class="textbox" type="text" id="businessName" />',
                                    '</li>',
                                    '<li class="wide">',
                                        '<label for="businessAddress">Business Address</label>',
                                        '<input class="textbox" type="text" id="businessAddress" />',
                                    '</li>',
                                    '<li class="wide">',
                                        '<label for="businessCity">City</label>',
                                        '<input class="textbox" type="text" id="businessCity" />',
                                    '</li>',
                                    '<li class="narrow">',
                                        '<label for="businessZip">Zip</label>',
                                        '<input class="textbox" type="text" id="businessZip" />',
                                    '</li>',
                                    '<li class="narrow">',
                                        '<label for="businessCountry">Country</label>',
                                        '<select id="businessCountry">',
                                            '<option value="USA">USA</option>',
                                        '</select>',
                                    '</li>',
                                    '<li class="wide clear">',
                                        '<label for="businessPhone">Phone</label>',
                                       '<input class="textbox" type="text" id="businessPhone" />',
                                    '</li>',
                                    '<li class="wide">',
                                       '<label for="businessCategory">Category</label>',
                                        '<select id="businessCategory">',
                                            '<option value="0" selected="selected">None</option>',
                                            '<option value="100">Restaurants </option>',
                                            '<option value="200">Food</option>',
                                            '<option value="300">NightLife</option>',
                                            '<option value="400">Shopping</option>',
                                            '<option value="500">Home & Garden</option>',
                                            '<option value="600">Kids & Education</option>',
                                            '<option value="700">Community & Society</option>',
                                            '<option value="800">Health & Beauty</option>',
                                            '<option value="900">Travel</option>',
                                            '<option value="1000">Sports & Recreation</option>',
                                            '<option value="1100">Arts & Entertainment</option>',
                                            '<option value="1200">Professionals & Services</option>',
                                            '<option value="1300">Wedding & Parties</option>',
                                        '</select>',
                                    '</li>',
                                    '<li class="wide">',
                                        '<label for="businessSubCategory">SubCategory</label>',
                                        '<select id="businessSubCategory">',
                                            '<option value="0" selected="selected">None</option>',
                                        '</select>',
                                    '</li>',
                                '</ul>',
                            '</li>',
                        '</ul><!-- /tabs -->',
                    '</li><!-- /content -->',
                '</ul>',
                '<ul class="controls">',
                    '<li>',
                        '<a href="#" class="btn-save">Save</a>',
                        '<a href="#" class="btn-done">Close</a>',
                    '</li>',
                    '<li id="status-messaging"></li>',
                '</ul>',
            '</div><!-- /container -->',
        '</div><!-- /popup-large -->'].join(''));
        self.setMenuOptions();
        $('.btn-close, .btn-done').click(function(e) { $('#popup-large').hide(); return false; });
        $("#businessCategory").change(function(e) {
            self.wireUpSubCategoryData($("OPTION:selected", this).val());
        });

        //handle click paging
        var currPageScroll = 1;
        var endPageScroll = 3;
        $(self.DEFAULT_SCROLLABLE_ID).scrollable().next();
        $(".control-next").livequery("click", function(e) {
            $(self.DEFAULT_SCROLLABLE_ID).scrollable().nextPage();
            if (endPageScroll < 7) {
                endPageScroll++;
                currPageScroll++;
                $('.photo-picker .paging .count').html(currPageScroll + "-" + endPageScroll);

            }
            return false;
        });
        $(".control-prev").livequery("click", function(e) {

            $(self.DEFAULT_SCROLLABLE_ID).scrollable().prevPage();
            if (currPageScroll < 6 && currPageScroll > 1) {
                endPageScroll--;
                currPageScroll--;
                $('.photo-picker .paging .count').html(currPageScroll + "-" + endPageScroll);
            }

            return false;
        });

        if (typeof (this.disableSwfUpload) === 'undefined') {
            this.swfu = this.SWFUploadLoad();
        }
        $('#popup-large').hide();
        $('.caption').hide();
        $('a.btn-close').livequery("click", function(e) {
            $('#popup-large').hide();
            $("status-messaging").html("");
        });



        //handle note char count
        $('#note-textarea').keyup(function(i) {
            var max = 140;
            var val = $('#note-textarea').val();
            var cur = 0;
            if (val) {
                cur = val.length;
            }
            var left = max - cur;

            if (left < 0) {
                $('#note-textarea').val(val.substring(0, max));
                left = 0;
            }
            $('#tab-note .count').html(left);

        });
        $('a.btn-save').livequery("click", function(e) {
            self.saveItem();
            return false;
        });
    },

    saveItem: function() {
        var self = this;

        if ($('li#tab-note').is(':visible')) {
            console.log("note");
            self.saveNote(self.currentSelectedData.LinfoId);
        }
        if ($('li#tab-listing').is(':visible')) {
            console.log("listing");
            self.saveNewFavoriteListItem();
        }
        if ($('li#tab-photo').is(':visible')) {
            console.log("photo");
            self.gImageUpload(self.currentSelectedData.UsersLinfoId);
        }
        self.onSaveItem();
    },
    onSaveItem: function(e) {
    },
    initialize: function(config) {
        $.extend(this, config);
    },

    wireUp: function(selector) {
        var self = this;

        this.selector = selector || this.DEFAULT_ITEM_SELECTOR;
        $(this.selector).livequery("mouseover", function(e) {
            self.show(e, $(e.currentTarget)[0].selectedData);
        });

        $(this.selector).livequery("mouseout", function(e) {
            $(self.DEFAULT_POP_ELEMENT).hide();
        });
        self.showPanel('tab-photo');


    },
    applyTemplate: function(d) {
        if (Linfo.isThing(d)) { return this.tpl_edit_thing.apply(d); }
        else { return this.tpl_edit.apply(d); }
    },




    show: function(e, selectedData) {
        console.log('show this');
        var self = this;
        if (!self.IsOwner) {
            $('#note-textarea').get(0).disabled = true;
        }
        self.showDefaultPanel();
        $('#note-textarea').val(selectedData.Comment);
        self.currentIndexId = $(e.currentTarget).attr("id");
        console.log(e.pageY);
        $('#popup-large').css({ left: e.pageX, top: e.pageY - self.TOP_OFFSET, display: 'block', position: 'absolute' });

        console.log(selectedData);
        selectedData.UrlEncodedName = Linfo.escapeName(selectedData.Name);

        $('ul.content li.details').html(this.applyTemplate(selectedData));
        console.log(selectedData, 'selectedData');
        self.currentLinfoId = selectedData.LinfoId;
        //$('#popup-large .photo img').attr("src", selectedData.DefaultImageUri);        
        this.searchControl.execute(selectedData.Name);
        self.currentSelectedData = selectedData;
        return false;
    },

    showPanel: function(panelToShow, classToAdd) {
        console.log('showPanel', $(this), arguments);
        if (typeof (classToAdd) === 'undefined') {
            $("#popup-large").removeAttr("class");
        } else {
            $("#popup-large").addClass(classToAdd);
        }

        $("li.tabbed-content ul.tabs .tab").each(function(i) {
            // console.log(this);
            $(this).hide();
        });

        $("ul.nav li").each(function(i) {
            // console.log(this);
            $(this).hide();
        });
        $("ul.nav li:has(." + panelToShow + ")").show();
        $("ul.tabs li#" + panelToShow).show();
        //reset photo upload status
        $("#status-messaging").html("");
    },
    showDefaultPanel: function() {
        var self = this;
        $('a.tab-photo').livequery("click", function(e) { self.showPanel('tab-photo'); $('li.details').show(); return false; });
        $('a.tab-note').livequery("click", function(e) { self.showPanel('tab-note'); $('li.details').show(); return false; });
        $('a.tab-listing').livequery("click", function(e) { self.showPanel('tab-listing'); $('li.details').hide(); return false; });
        self.showPanel('tab-photo');
    },
    search: function(searchData) {

        this.searchControl.execute(searchData);
        return false;
    },
    saveNote: function(LinfoId) {
        var self = this;
        Linfo.A({
            url: this.ADD_NOTE_SERVICE,
            data: $.toJSON({ itemId: LinfoId, note: $("#note-textarea").val() }),
            success: function(d) {
                self.currentSelectedData.Comment = $("#note-textarea").val();
                //self.hidePop();
                $("#status-messaging").html("Your comment has been saved.");
                self.HidePopUp();
            }
        });

        return false;

    },
    HidePopUp: function() {
        console.log('hide pop up called');
        setTimeout(function() {
            var selectedEffect = 'fold';
            var options = {};
            $("#popup-large").hide(selectedEffect, options, 500)
        }, 1000);
    },
    SWFUploadLoad: function() {
        //swfupload code        
        var self = this;
        var swfu;
        var settings_object = {
            upload_url: "/home/UploadDesktopImage",
            flash_url: "/static/flash/swfupload.swf",
            button_placeholder_id: "desktopSelector",
            button_placeholder: "get_flash",
            button_width: 200,
            button_height: 20,
            button_text: "<span class='upload'>UPLOAD FROM DESKTOP</span>",
            button_text_style: ".upload {color:#00BBFF;textDecoration:underline;fontFamily:Arial,Helvetica,sans-serif;fontSize:14;}",
            file_queued_handler: function() { console.log('broken', self.currentLinfoId, swfu); self.SWFUploadExecute(swfu, self.currentLinfoId); },
            //file_queue_error_handler: function() { console.log('error handler'); },
            //file_dialog_complete_handler: function() { console.log('dialog handler'); },
            upload_start_handler: function() { },
            upload_progress_handler: function(swfu, dataUploaded, totalData) { },
            upload_success_handler: function(e, imgUrl) { $('ul.content li.details div.photo img').attr("src", imgUrl); self.SWFUpload_Sucess_Handler(e, imgUrl); },
            button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,
            button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
            file_size_limit: "5 MB"
        };
        swfu = new SWFUpload(settings_object);
        return swfu;
        //end code
    },
    SWFUpload_Sucess_Handler: function(e, imgUrl) {
        console.log("handler");
        console.log(arguments);
        var self = this;
        //var NewFilledItem = self.getItemAt(self.CurrentIndex - 1);
        //NewFilledItem.selectedData.DefaultImageUri = imgUrl;        
        $("#photo-caption").val("");
        $('#Linfo-' + self.currentSelectedData.UsersLinfoId + ' a img').attr("src", imgUrl);
        self.currentSelectedData.DefaultImageUri = imgUrl;

        $("#status-messaging").html("The photo has been saved");
        $('#linfo-' + self.currentSelectedData.UsersLinfoId).unblock();
    },

    SWFUploadExecute: function(swfu, linfoid) {
        var self = this;
        console.log(arguments, "hi pauylly");
        //swfu.settings.upload_url = "/home/UploadDesktopImage?imageCaption=" + $("#imagecaptionbox").val() + "&linfoid=" + linfoid;
        var caption = ($("#photo-caption").val() === "Name or describe your photo") ? "" : $("#photo-caption").val();

        swfu.setUploadURL("/home/UploadDesktopImage?imageCaption=" + caption + "&linfoid=" + linfoid + "&type=" + this.itemType);
        swfu.startUpload();
        $('#linfo-' + self.currentSelectedData.UsersLinfoId).block({ message: '<img src="/static/images/icon-wait-30x30.png" class="wait" />' });
        console.log('swfUplaodExcute');

    },
    saveNewFavoriteListItem: function() {
        var self = this;
        //make sure it's under 20
        console.log('linfolistingpopup savenew favoritelistitem');
        Linfo.A({
            url: "/services/listService.asmx/CreateNewFavoritePlace",

            data: $.toJSON({ businessName: $("#businessName").val(), businessAddress: $("#businessAddress").val(),
                businessCity: $("#businessCity").val(), businessCountry: $('#businessCountry').val(), businessPhone: $("#businessPhone").val(),
                businessCategory: $('#businessCategory').val(), businessSubCategory: $('#businessSubCategory').val(), businessZip: $("#businessZip").val()
            }),
            maskEl: self.getNextListElement(),
            cache: false,
            success: function(d) {
                console.log('inside save favorite listitem d', d);
                //reset all form variables                    
                $("[id^=business]").each(function() {
                    $(this).val("");
                });
                self.LINFO_ID = d.d.LinfoId;
                self.search(d.d.Name);
                self.showPanel("tab-photo", "listing");
                //self.searchControl.execute(d.d.Name);
                self.SaveFavoriteListItem(d.d);

            }
        });
        return false;
    },

    gSearchOnLoad: function(l) {
        var self = this;
        this.searchControl = new google.search.SearchControl();
        this.searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
        this.imageSearch = new google.search.ImageSearch();
        this.imageSearch.setRestriction(google.search.ImageSearch.RESTRICT_IMAGESIZE,
                        google.search.ImageSearch.IMAGESIZE_MEDIUM);
        this.imageSearch.setRestriction(google.search.Search.RESTRICT_SAFESEARCH, google.search.Search.SAFESEARCH_ON);
        this.imageSearch.setNoHtmlGeneration();
        this.searchControl.addSearcher(this.imageSearch);
        this.searchControl.setNoResultsString();

        // Tell the searcher to draw itself and tell it where to attach
        this.searchControl.draw();
        this.searchControl.setSearchCompleteCallback(null, function(e) { self.gImageSearchComplete(); });

        this.searchControl.clearAllResults();

        $("#imageUploadbtn").bind("click", function(e) {
            self.gImageUpload();
            $('#popup-large').hide();
            return false;
        });
        return true;
    },

    gImageSearchComplete: function() {
        $(".picker-panel li.items ul.items").empty();
        $.each(this.imageSearch.results, function(index, item) {
            console.log(item, 'image item');
            if (index < 9) {
                var photoHtml = "<li class='item'><label for=\"item-" + index + "\"><img src=\"" + item.url + "\"/><input type=\"radio\" name=\"picker\" id=\"item-" + index + "\"/></label></li>";
                $(".picker-panel li.items ul.items").append(photoHtml);
            }
        });

        this.sc = $('#popup-large .picker-panel li.items ul.items').scrollable();
    },

    gImageUpload: function(linfoId) {
        var self = this;
        //        console.log(linfoId, self.currentSelectedData);
        var originalUrl = $(".picker-panel ul li:has( input[checked] ) img").attr("src");
        var imageCaption = ($("#photo-caption").val() === "Name or describe your photo") ? "" : $("#photo-caption").val();
        console.log($("#photo-caption").val(), 'photo', imageCaption);
        console.log(arguments, "linfoid gimageupload");
        if (originalUrl) {
            Linfo.A({
                url: self.IMAGE_UPLOAD_SERVICE,
                data: $.toJSON({ originalurl: originalUrl, imagecaption: imageCaption, linfoid: self.currentSelectedData.LinfoId }),
                maskEl: $("li.filled .photo")[self.CURRENT_INDEX - 1], //self.maskMainEl,
                success: function(d) {

                    self.currentSelectedData.DefaultImageUri = d.d;
                    var tempIndex = self.CURRENT_INDEX - 1;
                    console.log(tempIndex, 'tempindex', d.d);

                    //temp fix                    
                    if (tempIndex == -1) {
                        $("li #Linfo-" + linfoId + " .photo img").attr("src", d.d); //set the small thumbnail in the list
                    }
                    else {
                        $("li.filled:eq(" + tempIndex + ") img").attr("src", d.d); //set the small thumbnail in the list
                    }
                    $('div.photo img').attr("src", d.d); //set the popped up thumbnail of the item
                    $("#status-messaging").html("The photo has been saved");
                    self.handleUploadSuccess(d, imageCaption);

                    self.HidePopUp();
                }
            });

        }
        return false;
        // console.log("googleUPload " + OriginalUrl, ImageCaption, LinfoId, self.userId);
    },
    handleUploadSuccess: function(imgUrl, imageCaption) {
        return false;
    },
    wireUpSubCategoryData: function(categoryId) {
        var self = this;
        switch (categoryId) {
            case "0": self.loadData('<option value="0">None</option>');
                break;
            case "100": self.loadData('<option value="101">American</option><option value="102">Barbecue</option><option value="103">Breakfast & Brunch</option><option value="104">Buffet</option><option value="105">Burger</option><option value="106">Chinese</option><option value="107">Dessert & Sweets</option><option value="108">Diner  &  Deli</option><option value="109">Ethiopian</option><option value="110">Fast Food</option><option value="111">Fine Dining</option><option value="112">French</option><option value="113">Greek & Mediterranean</option><option value="114">Indian</option><option value="115">Italian</option><option value="116">Japanese</option><option value="117">Korean</option><option value="118">Late Night</option><option value="119">Mexican</option><option value="120">Middle Eastern</option><option value="121">Morroccan</option><option value="122">Other Asian</option><option value="123">Other European</option><option value="124">Pizza</option><option value="125">Sandwiches</option><option value="126">Seafood</option><option value="127">South American</option><option value="128">Steak</option><option value="129">Sushi</option><option value="130">Tapas</option><option value="131">Thai</option><option value="132">Vegetarian  &  Vegan</option><option value="133">Vietnamese</option>');
                break;
            case "200": self.loadData('<option value="201">Bagels</option><option value="202">Bakeries</option><option value="203">Beer</option><option value="204">Butchers</option><option value="205">Cheese Shops</option><option value="206">Coffee & Tea</option><option value="207">Convenience Stores</option><option value="208">Creperies</option><option value="209">Donuts</option><option value="210">Farmers Market</option><option value="211">Fish Seafood</option><option value="212">Grocery</option><option value="213">Health Food</option><option value="214">Ice Cream & Frozen Yogurt</option><option value="215">Juice, Shakes & Smoothies</option><option value="216">Specialty Ethnic</option><option value="217">Wine</option>');
                break;
            case "300": self.loadData('<option value="301">Strip Clubs</option><option value="302">All Ages</option><option value="303">Bars</option><option value="304">Beer Selections</option><option value="305">Cigar Lounges</option><option value="306">College Bars</option><option value="307">Comedy Clubs</option><option value="308">Dance Clubs</option><option value="309">Disco</option><option value="310">Dive Bars</option><option value="311">Gay & Lesbian</option><option value="312">Happy Hour</option><option value="313">Jazz & Blues</option><option value="314">Karaoke</option><option value="315">Live Music Venues</option><option value="316">Patio & Outdoor</option><option value="317">Pool Halls</option><option value="318">Pubs</option><option value="319">Singles</option><option value="320">Sports Bars</option><option value="321">Wine Bars</option>');
                break;
            case "400": self.loadData('<option value="401">Accessories</option><option value="402">Art & Antiques</option><option value="403">Beauty Supply</option><option value="404">Books, Music & DVD</option><option value="405">Cars</option><option value="406">Clothes</option><option value="407">Eco-friendly</option><option value="408">Electronics</option><option value="409">Flowers</option><option value="410">Food & Wine</option><option value="411">Furniture</option><option value="412">Games</option><option value="413">Gifts</option><option value="414">Home & Garden</option><option value="415">Jewelry & Watches</option><option value="416">Lingerie</option><option value="417">Maternity</option><option value="418">Musical Instruments</option><option value="419">Online Shopping</option><option value="420">Optical</option><option value="421">Pets</option><option value="422">Shoes</option><option value="423">Specialty</option><option value="424">Sporting Goods</option><option value="425">Toys</option><option value="426">Vintage & Second-hand</option>');
                break;
            case "500": self.loadData('<option value="501">Rental</option><option value="502">Architect & Designer</option><option value="503">Cabinets & Carpentry</option><option value="504">Construction</option><option value="505">Electrician</option><option value="506">Gardening</option><option value="507">Heating & Cooling</option><option value="508">Home Center</option><option value="509">Home Security</option><option value="510">Housekeeping</option><option value="511">Insurance Agent</option><option value="512">Interior Design</option><option value="513">Landscape Architect</option><option value="514">Locksmith</option><option value="515">Maintenance</option><option value="516">Mortgage Broker</option><option value="517">Painting</option><option value="518">Pest Control</option><option value="519">Pets</option><option value="520">Plumbing</option><option value="521">Real Estate</option><option value="522">Roofing</option><option value="523">Self Storage & Moving</option><option value="524">Swimming Pools</option><option value="525">Windows & Doors</option>');
                break;
            case "600": self.loadData('<option value="601">Activities</option><option value="602">Childcare & Babysitting</option><option value="603">Coaching Services</option><option value="604">College</option><option value="605">K-12</option><option value="606">Kids Clothes</option><option value="607">Kids Parties</option><option value="608">Kids Sports</option><option value="609">Lamaze Class</option><option value="610">Maternity Clothes</option><option value="611">Pediatrician</option><option value="612">Playground & Park</option><option value="613">Pregnancy Services</option><option value="614">Pre-School & Nursery</option><option value="615">Private School</option><option value="616">Specialty Toys</option><option value="617">Summer Camps</option><option value="618">Tutoring Services</option>');
                break;
            case "700": self.loadData('<option value="701">Art Schools</option><option value="702">Charity</option><option value="703">Civic Organization</option><option value="704">Classes</option><option value="705">Culinary Schools</option><option value="706">Hospice & Home Care</option><option value="707">Language Schools</option><option value="708">Political Party</option><option value="709">Professional Association</option><option value="710">Religious Congregation</option><option value="711">Volunteering</option>');
                break;
            case "800": self.loadData('<option value="801">Alternative Medicine</option><option value="802">Chiropractor</option><option value="803">Clinic & Hospital</option><option value="804">Cosmetic Surgery</option><option value="805">Dentist</option><option value="806">Doctor</option><option value="807">Fitness</option><option value="808">Hair</option><option value="809">Makeup & Skin</option><option value="810">Massage Therapy</option><option value="811">Mental Health</option><option value="812">Nails</option><option value="813">OB & GYN</option><option value="814">Optometrist</option><option value="815">Personal Trainer</option><option value="816">Pharmacies</option><option value="817">Physical Therapy</option><option value="818">Pilates</option><option value="819">Spa</option><option value="820">Sports Medicine</option><option value="821">Tanning</option><option value="822">Tattoos & Piercing</option><option value="823">Yoga</option>');
                break;
            case "900": self.loadData('<option value="901">Air Travel</option><option value="902">Auto Rentals & Leasing</option><option value="903">Boat & Cruising</option><option value="904">Camping</option><option value="905">Casino</option><option value="906">Eco-Friendly</option><option value="907">Family-Friendly</option><option value="908">Gay & Lesbian Friendly</option><option value="909">Guided Tours</option><option value="910">Hotel</option><option value="911">Inn & B-&-B</option><option value="912">Pet-friendly</option><option value="913">Resort & Spa</option><option value="914">Safari</option><option value="915">Sightseeing</option><option value="916">Specialty Travel</option><option value="917">Taxi, Limosine & Shuttle</option><option value="918">Train & Rail Travel</option><option value="919">Travel Agency</option><option value="920">Travel Charter</option><option value="921">Travel Services</option><option value="922">Villa & Cabin</option><option value="923">Weekend Getaway</option>');
                break;
            case "1000": self.loadData('<option value="1001">Bird Watching</option><option value="1002">Boating & Fishing</option><option value="1003">Bowling Alley</option><option value="1004">Camping & Hunting</option><option value="1005">Dancing</option><option value="1006">Extreme Sports</option><option value="1007">Golf & Golf Courses</option><option value="1008">Hiking</option><option value="1009">Horses</option><option value="1010">Martial Arts</option><option value="1011">Nature Reserves</option><option value="1012">Parks</option><option value="1013">Race Courses & Race Tracks</option><option value="1014">Scuba Diving & Snorkeling</option><option value="1015">Skateboarding</option><option value="1016">Skating Rink</option><option value="1017">Ski & Snowboarding</option><option value="1018">Sport Equipment Rental</option><option value="1019">Stadiums, Courts & Arenas</option><option value="1020">Surf</option><option value="1021">Swimming</option><option value="1022">Tennis & Racquetball</option>');
                break;
            case "1100": self.loadData('<option value="1101">Arcades</option><option value="1102">Botanical Garden</option><option value="1103">Concert Halls</option><option value="1104">Cultural Centers</option><option value="1105">Fair & Festival</option><option value="1106">Historic Site</option><option value="1107">Landmarks</option><option value="1108">Libraries</option><option value="1109">Museums</option><option value="1110">Performing Arts</option><option value="1111">Theaters</option><option value="1112">Theme Park</option><option value="1113">Visual Arts</option><option value="1114">Winery</option><option value="1115">Zoo & Aquarium</option>');
                break;
            case "1200": self.loadData('<option value="1201">Accounting & Taxes</option><option value="1202">Automotive</option><option value="1203">Computer Services</option><option value="1204">Consulting</option><option value="1205">Couriers & Delivery Services</option><option value="1206">Dating Services</option><option value="1207">Drycleaner</option><option value="1208">Employment</option><option value="1209">Funeral</option><option value="1210">Insurance</option><option value="1211">Investments</option><option value="1212">Leasing</option><option value="1213">Legal</option><option value="1214">Marketing</option><option value="1215">Office Services</option><option value="1216">Photography</option><option value="1217">Recording & Rehearsal Studios</option><option value="1218">Research</option><option value="1219">Security</option><option value="1220">Transportation</option>');
                break;
            case "1300": self.loadData('<option value="1301">Audio & Visual Equipment</option><option value="1302">Balloons</option><option value="1303">Bartenders</option><option value="1304">Cakes & Desserts</option><option value="1305">Caterers</option><option value="1306">Decorations</option><option value="1307">Entertainment , DJs, Bands, & Musicians</option><option value="1308">Favors</option><option value="1309">Flowers</option><option value="1310">Gay & Lesbian Ceremony Resources</option><option value="1311">Invitations & Calligraphy</option><option value="1312">Lighting & Décor</option><option value="1313">Officiants & Premarital Counseling</option><option value="1314">Photography & Videography</option><option value="1315">Planners & Coordinators</option><option value="1316">Planning Resources</option><option value="1317">Reception & Ceremony Sites</option><option value="1318">Tuxedos & Mens Attire</option><option value="1319">Wedding Gowns & Bridesmaid Dresses</option>');
                break;
        }
    },
    SaveFavoriteListItem: function(data) {
        var self = this;
        self.currentSelectedData = data;
        $('ul.content li.details').show();
        $('ul.content li.details').html(self.tpl_edit.apply(data));
        self.onSaveFavoriteListItem(data);
    },
    loadData: function(data) {
        $("#businessSubCategory").html(data);
    }
});
﻿/*global $ Linfo console*/

Linfo.LocationSearchAutoComplete = $.klass({
    initialize: function(inputElement, completerConfig) {
        var self = this;
        this.URL_BASE = '/services/SearchService.asmx/AutocompleteLocation';
        this.RESULT_TEMPLATE = Linfo.Templates.LOCATION_SEARCH_AUTO_COMPLETE;
        this.EMPTY_RESULT_TEMPLATE = Linfo.Templates.EMPTY_LOCATION_SEARCH_AUTO_COMPLETE;
        this.maskAddBtn = '';
        this.disableNoResults = false;
        this.focusOnAfterSelect = function(o) { console.log('test in here'); };
        $.extend(this, completerConfig);

        $(inputElement).autocomplete(this.URL_BASE, {
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            minChars: 2,
            matchSubset: false,
            extraParams: {
                lat: function() { return self.lat; },
                lng: function() { return self.lng; }
            },
            dataType: 'json',
            scroll: false,
            multiple: false,
            delay: 200,
            clearOnBlur: false,
            cacheLength: 1,
            parse: completerConfig.parse || function(o) { return self.parseResult(o); },
            formatItem: completerConfig.formatItem || function(data) { return self.formatItem(data); },
            focusOnAfterSelect: completerConfig.focusOnAfterSelect || function(field) { return self.focusOnAfterSelect(field); },
            handleDropDownHover: function(selectedItem) { $("#textbox-add-item").val($.data(selectedItem[0], "ac_data").value); }
        }).bind("result", completerConfig.handleResult || this.handleResult);
    },

    formatItem: function(data) {
        if (typeof (data.Name) != "undefined") {
            return this.RESULT_TEMPLATE.apply(data);
        }
        else if (!this.disableNoResults) {
            //set the fav places variable to false no cities found
            return '<a id="noItemsFound">Not listed? <span id="btn-add-item">Add new listing</span></a>';
        }
    },

    handleResult: function(selectionInfo, selectedData, value) {

    },
    focusOnAfterSelect: function(field) {

    },
    parseResult: function(o) {
        var self = this;
        console.log(this.disableNoResults, 'disable results', o, $("#textbox-add-item").val());
        //if (o.d.length === 0) {
        var newObj = {};
        newObj.Name = $("#textbox-add-item").val();
        newObj.data = {};

        newObj.value = null;
        newObj.result = newObj.Name; //'<span id="noItemsFound">Not listed? <a id="btn-add-item" class="add-new-listing">Not Here?</a></span>';
        //o.d[0] = newObj;
        if (this.maskAddBtn !== '') {
            // console.log('prase result function in linfolocation search',o);                
            console.log($(self.maskAddBtn), 'mask button');
            $(self.maskAddBtn).show();
        }
        // return o.d;
        // }
        //        if (this.maskAddBtn !== '') {
        //            $(self.maskAddBtn).hide();
        //        }
        var result = $.map(o.d, function(doc, idx) {
            return { data: doc, value: doc.Name, result: doc.Name };
        });
        result.push(newObj);
        return result;
        /*
        LOCATION_SEARCH_AUTO_COMPLETE: $.template([
        '<a href="#">${Name}</a><br />',
        '<b>${Address}</b>',
        '<a href="#"><img src="/static/images/icon_add.gif" alt="add" /></a>'
        ].join('')),*/

    }
});
﻿
/*global $ window Linfo console */

Linfo.MiniLocationPopUp = $.klass({
    DEFAULT_POP_ELEMENT: '#mini-location-popup',
    DEFAULT_ITEM_SELECTOR: 'li.filled',
    DEFAULT_POP_ID: 'mini-location-popup',
    DEFAULT_POP_CLASS: 'mini-location-popup',
    ADD_NOTE_SERVICE: "/services/Listservice.asmx/AddNote",
    addNote: false,
    COMMENT_LENGTH: 100,
    emitMarkup: function() {
        $('#canvas').append([

            '<div id="', this.DEFAULT_POP_ID, '" class="', this.DEFAULT_POP_CLASS, '" style="display: none;">',
                //'<a href="#" class="btn-close">close</a>',
				'<div class="photo">',
					'<img src="/static/images/thing-place-holder-48x48.png" style="padding:1px;" />',
					//'<div class="caption"></div>',
				'</div>',
                //'<h4></h4>',
                '<div class="details"></div>',
            '</div>'

        ].join(''));
    },

    initialize: function(config) {
        $.extend(this, config);
    },

    wireUp: function(selector) {
        var self = this;

        self.emitMarkup();

        this.selector = selector || this.DEFAULT_ITEM_SELECTOR;

        $(this.selector).livequery("mouseover", function(e) {
            self.show(e, $(e.currentTarget)[0].selectedData);
        });

        $(this.selector).livequery("mouseout", function(e) {
            self.hidePop();
        });
    },
    saveNote: function(LinfoId) {
        Linfo.A({
            url: this.ADD_NOTE_SERVICE,
            data: $.toJSON({ itemId: LinfoId, note: $("#note-textarea").val() }),
            success: function(d) {
                $("#note-add").hide();
                $('#note-textarea').get(0).disabled = true;
                if ($.trim($("#note-textarea").val()).length > 0) {
                    $('p.status').hide();
                }
                else {
                    $('p.status').show();
                    $("#note-add").show();
                    $("#note-edit").hide();
                }
            }
        });

        return false;

    },
    wireUpNoHover: function(selector) {
        var self = this;

        self.emitMarkup();

        this.selector = selector || this.DEFAULT_ITEM_SELECTOR;

        $(this.selector).livequery("click", function(e) {
            self.show(e, $(e.currentTarget)[0].selectedData);
        });

        //        $(this.selector).livequery("click", function(e) {
        //            self.hidePop();
        //        });
        $('.btn-close').livequery('click', function(e) { self.hidePop(); });
    },

    hidePop: function() {
        $(this.DEFAULT_POP_ELEMENT).hide();
    },

    positionAndShow: function(tpl, selectedData, left, top) {

        $(this.DEFAULT_POP_ELEMENT + ' .photo img').attr('src', selectedData.DefaultImageUri);
        $(this.DEFAULT_POP_ELEMENT).css({ left: left, top: top, display: 'block' });
        $(this.DEFAULT_POP_ELEMENT + ' .details').html(tpl.apply(selectedData));

    },
    positionAndShowNoHover: function(tpl, selectedData, left, top) {
        var self = this;
        console.log(arguments);
        $(this.DEFAULT_POP_ELEMENT + ' .photo img').attr('src', selectedData.DefaultImageUri);
        $(this.DEFAULT_POP_ELEMENT + ' .details').html(tpl.apply(selectedData));

        if ($('#' + this.DEFAULT_POP_ID + ' .description').length > 0) {
            $('#' + this.DEFAULT_POP_ID + ' .description').replaceWith(Linfo.Templates.POPUP_ADD_EDIT_NOTE.apply(selectedData));
        }
        else {
            $('#' + this.DEFAULT_POP_ID).append(Linfo.Templates.POPUP_ADD_EDIT_NOTE.apply(selectedData));
        }

        //has a comment
        if (selectedData.Comment.length > 0) {
            $('p.status').hide();
            $('#note-textarea').val(String(selectedData.Comment).substring(0, self.COMMENT_LENGTH));
            $("#note-add").hide();
        }
        else {
            $("#note-edit").hide();
            $('p.status').show();
        }
        $("#note-save").livequery("click", function(e) { self.saveNote(selectedData.LinfoId); selectedData.Comment = $('#note-textarea').val(); return false; });
        $("#note-remove").livequery("click", function(e) { });
        $("#note-edit").livequery("click", function(e) { $('#note-textarea').get(0).disabled = false; return false; });
        $("#note-add").livequery("click", function(e) { $('#note-textarea').get(0).disabled = false; $('p.status').hide(); return false; });

        $(this.DEFAULT_POP_ELEMENT).css({ left: left, top: top, display: 'block' });
    },
    show: function(e, selectedData) {
        var self = this;
        var tgt = $(e.currentTarget)[0];
        if ($(tgt).is(this.selector)) {        
            //var tpl = $.template('<h5><a class="name" href="/place/${Name}/${LinfoId}">${Name}</a></h5><span>${Address}</span><span>${City} ${State} ${Zip}</span><span>${Phone}</span>');
            var tpl = $.template('<h5><span class="name">${Name}</span></h5><span>${Address}</span><span>${City} ${State} ${Zip}</span><span>${Phone}</span>');
            var rect = $(tgt).offset();
            if (self.addNote) {
                this.positionAndShowNoHover(tpl, selectedData, rect.left - 335, rect.top - 25);
            }
            else { this.positionAndShow(tpl, selectedData, rect.left - 335, rect.top - 25); }
        }
        
    }
});

Linfo.MiniPersonPopUp = $.klass(Linfo.MiniLocationPopUp, {
    DEFAULT_POP_ELEMENT: '#mini-person-popup',
    DEFAULT_POP_ID: 'mini-person-popup',
    DEFAULT_POP_CLASS: 'mini-location-popup left',

    show: function(e, selectedData) {
    var tgt = $(e.currentTarget)[0];    
        if ($(tgt).is(this.selector)) {
            //console.log(  );
            var tpl = $.template('<h5>${FirstName}</h5>');
            //'<fb:profile-pic linked="false" uid="${FacebookId}" size="s" />';
            var rect = $(tgt).offset();
            selectedData.DefaultImageUri = $('img', tgt).attr('src').replace("/t", "/s");

            this.positionAndShow(tpl, selectedData, rect.left + 50, rect.top - 25);
        }
    }
});

Linfo.MiniThingPopUp = $.klass(Linfo.MiniLocationPopUp, {
    DEFAULT_POP_ELEMENT: '#mini-thing-popup',
    DEFAULT_ITEM_SELECTOR: 'li[freebaseid]',
    DEFAULT_POP_ID: 'mini-thing-popup',

    onFreebaseData: function(d, e, selectedData) {
        selectedData.fbtext = d.result.body;

        this.showInternal(e, selectedData);
    },

    fetchFreebaseData: function(id, e, selectedData) {
        var self = this;

        $.ajax({
            type: "GET",
            url: 'http://www.freebase.com/api/trans/blurb/guid/' + id.replace(/-/g, ''),
            dataType: 'jsonp',
            success: function(d) { self.onFreebaseData(d, e, selectedData); }
        });
    },

    show: function(e, selectedData) {
        this.mouseIsOut = false;
        if (typeof (selectedData) !== 'undefined') {
            if (selectedData.FreebaseArticleId === null) {
                this.showInternal(e, selectedData);
            } else {
                this.fetchFreebaseData(selectedData.FreebaseArticleId, e, selectedData);
            }
        }
    },

    hidePop: function($super) {
        this.mouseIsOut = true;

        $super();
    },

    showInternal: function(e, selectedData) {
        if (this.mouseIsOut) { return; }

        var tgt = $(e.currentTarget)[0];

        if ($(tgt).is(this.selector)) {
            var tpl = $.template('<h5>${What}</h5><span>${fbtext}</span>');
            var rect = $(tgt).offset();

            this.positionAndShow(tpl, selectedData, rect.left - 335, rect.top - 25);
        }
    }
});﻿/*global $ Linfo window sList */
Linfo.Twitter = $.klass({
    initialize: function(config) {
        $.extend(this, config);       
    },


    CreateStatusUpdateButton: function(btnLocation, userId, btn, tweet)
    {
        if ($(btnLocation))
        {
            $(btn).click(function(){ 
                $.ajax({
                    type: "POST",
                    url: "/Services/TwitterService.asmx/StatusUpdate",
                    data: $.toJSON({
                        userId: userId,
                        message: $(tweet).val()
                    }),
                    contentType: "application/json; charset=utf-8",
                    cache: false,
                    dataType: "json",
                    success: function() {
                    }
                });
                $(tweet).val("");
                $('#tweet-text-area').hide();
            });

            $(tweet).keyup(function(i) {
                var max = 140;
                var val = $(tweet).val();
                var cur = 0;
                if (val) {
                    cur = val.length;
                }
                var left = max - cur;
                $('#charcount').html(left);
            });
        }
    },
    CreateTwitterAuthButton:function(btnLocation,userId,twitterAuthorizationLink)
    {
        if ($(btnLocation)) {
            
            $(btnLocation).click(function(event)
            {
                sList = window.open(twitterAuthorizationLink, "twcWindow", "width=800,height=400,left=150,top=100,scrollbar=no,resize=no");
                return false; 
            });
           
        }
    
    }  
    
    
});﻿/*global Linfo $ $super console */

Linfo.SuggestionsList = $.klass({

    initialize: function(config) {
        var self = this;
        this.ITEM_SELECTOR = Linfo.Selectors.FavoritePlaces.SUGGESTION_ITEM;
        this.DEFAULT_ITEM_TEMPLATE = Linfo.Templates.SUGGESTION_LIST_ITEM;
        this.SERVICE_URL = '/services/LocationService.asmx/GetSuggestionsByZip';
        this.maskEl = undefined;
        this.NO_SUGGESTIONS = 'ul.items';
        this.HasDefaultListTitle = true;
        this.isSuggestionBinded = false;
        $(".controls .btn-next, .controls .btn-prev").bind("click", function(e) {
            self.handleNextClick(e);
            return false;

        });

        $.extend(this, config);
    },

    getSuggestionData: function(e) {
        return $(e.currentTarget).attr("linfoid");
    },
    handleSuggestionClick: function(e) {
        this.onSuggestionSelected(this.getSuggestionData(e));
    },

    handleNextClick: function(e) {
        this.suggestionList.loadList(this.CurrentZipCode);
    },

    onSuggestionsLoaded: function(suggestions) {
        var self = this;
        console.log(suggestions,"suggestions");
        $(this.suggestionList.ITEM_CONTAINER).empty();
        if (suggestions === '') {
            $(self.NO_SUGGESTIONS).append("<li><h4>Sorry there are no suggestions for your area</h4></li>");
            $('p.controls').hide();
        }
        else {
            $('p.controls').show();
            $.each(suggestions, function(idx, currentSuggestion) {

                /*if (currentSuggestion.Value.Name.length > 17) {
                    currentSuggestion.Value.DisplayName = currentSuggestion.Value.Name.substring(0, 15) + "...";
                }
                else {*/
                    currentSuggestion.Value.DisplayName = currentSuggestion.Value.Name;
                //}

                var li = $(self.DEFAULT_ITEM_TEMPLATE.apply(currentSuggestion.Value))[0];

                $(self.suggestionList.ITEM_CONTAINER).append(li);
                li.selectedData = currentSuggestion.Value;
            });

            if (self.HasDefaultListTitle) {
                self.bindClickHandler();
                console.log('has default title');
                $("#suggestions div.content").show();
            }
        }

    },
    bindClickHandler: function() {
        var self = this;

        if (typeof (this.suggestionList) !== 'undefined' && !this.isSuggestionBinded) {
            self.isSuggestionBinded = true;
            $(this.suggestionList.ITEM_SELECTOR).livequery("click", function(e) {
                console.log('clicked inside selector bind click handler');
                self.handleSuggestionClick(e);
                return false;
            });
        }
        return false;
    },
    getParameterData: function() {
        return $.toJSON({ zipcode: this.CurrentZipCode });
    },

    onSuggestionSelected: function(linfoId) {

    },
    loadList: function(zipcode) {
        var self = this;
        self.CurrentZipCode = zipcode;
        this.suggestionList = new Linfo.LinfoAjaxList({
            type: 'suggestions',
            getParameterData: function() { return self.getParameterData(); },
            serviceUrl: self.SERVICE_URL,
            maskEl: self.maskEl,
            ITEM_SELECTOR: Linfo.Selectors.FavoritePlaces.SUGGESTION_ITEM,
            ITEM_CONTAINER: Linfo.Selectors.FavoritePlaces.SUGGESTION_ITEM_CONTAINER,
            onListLoad: function(d) { self.onSuggestionsLoaded(d.d); }
        });

        this.suggestionList.loadList();
        return false;
    }
});

Linfo.ThingsSuggestionsList = $.klass(Linfo.SuggestionsList, {
    initialize: function($super, config) {
        var c = $.extend({
            SERVICE_URL: '/services/ListService.asmx/GetThingsSuggestions'
        }, config);

        $super(c);
    },

    getParameterData: function() { return $.toJSON({}); },
    getSuggestionData: function(e) { return e.currentTarget.selectedData; },

    handleNextClick: function(e) {        
        this.suggestionList.loadList();
    }
});﻿/*global window $ Linfo console google SWFUpload */

Linfo.BaseListController = $.klass({

    autoSaveEnabled: false,
    generateListItems: false,
    creatingNew: false,
    afterRender: Linfo.emptyFn,
    afterDeRender: Linfo.emptyFn,
    onSaveListSuccess: Linfo.emptyFn,
    onListLoad: Linfo.emptyFn,
    reorderList: Linfo.emptyFn,    
    onItemAdd: Linfo.emptyFn,
    onItemDelete: Linfo.emptyFn,
    itemSelector: "li.item.filled",
    handleEditClick: Linfo.emptyFn,
    handleDeleteClick: Linfo.emptyFn,

    handleNeedsMoreItems: Linfo.emptyFn,
    handleCompletedItemRequirements: Linfo.emptyFn,
    handleAlreadyCompletedItemRequirements: Linfo.emptyFn,

    canDelete: false,
    canEdit: false,
    canSort: false,

    // deleteControlSelector, editControlSelector, sortSelector

    initialize: function(config) {
        console.log('base list controller');
        $.extend(this, config);
        this.currentList = new Linfo.LinfoAjaxList({
            path: this.path || undefined,
            creatingNew: this.creatingNew,
            type: this.LIST_TYPE,
            name: this.LIST_NAME,
            getListName: this.getListName,
            maskEl: this.maskMainEl,
            MIN_TO_PROCEED: this.MIN_TO_PROCEED,
            ITEM_SELECTOR: this.ITEM_SELECTOR,
            EMPTY_ITEM_TEMPLATE: this.EMPTY_ITEM_TEMPLATE,
            FILLED_ITEM_TEMPLATE: this.DEFAULT_ITEM_TEMPLATE
        });
    },
    logIfUndefined: function(prop) {
        if (typeof this[prop] === 'undefined') {
            console.log('BaseListController: required property missing' + prop);
        }
    },
    validateRequiredProperties: function() {
        var self = this;

        $([
         'minItemCount', 'maxItemCount', 'filledItemExpression', 'singleItemExpression',
         'emptyItemExpression', 'nextUnselectedExpression', 'filledItemTemplate',
         'emptyItemTemplate'
         ]).each(function validatePresence() {
             self.logIfUndefined(this);
         });
    },

    enableListSortIf: function(override) {
        if (!this.canSortItems() && typeof override !== 'undefined') {
            return;
        }

        $(this.sortSelector).sortable({
            cursor: 'pointer',
            update: function() { this.currentList.reorderList(); },
            cancel: this.nextUnselectedExpression
        }).disableSelection();
    },

    getNumToMin: function() { return this.minListSize - this.getFilledItemCount(); },
    getNumToMax: function() { return this.maxListSize - this.getFilledItemCount(); },

    getFilledItemCount: function() {
        return $(this.filledExpression).length;
    },
    getItemAt: function(index) {
        var itemSelectorString = this.itemSelector + ":eq(" + index + ")";
        return $(itemSelectorString)[0];
    },
    getDataAt: function(index) {
        return this.getItemAt(index).selectedData;
    },
    getUnselectedElements: function() {        
        return $(this.unselectedExpression);
    },
    getNextUnselectedElement: function() {
        return this.getUnselectedElements().get(0);
    },
    getNextListElement: function() {
        var n = this.getUnselectedElements();
        if (n.length === 0 && this.generateListItems) {
            $(Linfo.Selectors.FavoriteThings.SORTABLE_LIST).append('<li class="row empty"></li>');
            return this.getNextUnselectedElement();
        } else {
            return n[0];
        }
    },
    renderListItem: function(element, data) {
        this.internalBeforeModification(element, data, "render");        
        element.selectedData = data;
        $(element).html(
            this.getItemDisplayHtml(data)
            ).removeClass('empty').addClass('filled');

        this.internalAfterModification(element, data, "render");
    },
    getFilledItems: function() {
        return $(this.filledExpression);
    },
    isDupe: function(id, prop) {
        return $.inArray(parseInt(id, 10), $.pluck($.pluck(this.getFilledItems(), 'selectedData'), prop)) > -1;
    },

    deRenderListItem: function(element, data) {
        this.internalBeforeModification(element, data, "deRender");
        var index = element.selectedData.Number;
        element.selectedData = undefined;
        $(element).html(this.EMPTY_ITEM_TEMPLATE.apply({ index: index + 1 })).removeClass('filled').addClass('empty');

        if (this.generateListItems) {
            $(element).remove();
        }
        this.internalAfterModification(element, data, 'deRender');
        $(this.CompletedCount).html(this.getFilledItemCount());
    },
    internalBeforeModification: function(element, data, type) {
        this.handleForFilledCount(this.getFilledItemCount() + 1, this.getNumToMin(), this.getNumToMax());
    },
    internalAfterModification: function(element, data, type) {
        if (type == "deRender") {
            this.afterDeRender(element, data);
        }
        if (type == "render") {
            this.afterRender(element, data);
        }
        this.handleForFilledCount(this.getFilledItemCount(), this.getNumToMin(), this.getNumToMax());
    },
    afterDeRender: function(element, i) {
        //default function if none is given for de rendering on any page
        this.currentList.reorderList();
    },
    handleForFilledCount: function(filledCount) {
        if (filledCount < this.minListSize) {
            this.handleNeedsMoreItems();
        } else if (filledCount === this.minListSize) {
            this.handleCompletedItemRequirements();
        } else if (filledCount >= this.minListSize) {
            this.handleAlreadyCompletedItemRequirements();
        }
    },

    verifySaveRequirements: function() {
        var currentCount = this.getFilledItemCount();
        var isDone = currentCount >= this.minListSize;

        return isDone;
    },

    run: function() {
        this.validateRequiredProperties();
    },

    /* needs pluggable error handler */
    reportError: function(e) { Linfo.FlowControl.updateProgressError(e); },

    canDeleteItems: function() { return this.canDelete && typeof this.deleteControlSelector !== 'undefined'; },
    canEditItems: function() { return this.canEdit && typeof this.editControlSelector !== 'undefined'; },
    canSortItems: function() { return this.canSort && typeof this.sortSelector !== 'undefined'; },
    canSave: function() { return typeof this.saveSelector !== 'undefined'; }
});
﻿/*global window $ Linfo console google SWFUpload */
Linfo.FavoritePlacesController = $.klass(Linfo.BaseListController, {
    initialize: function($super, config) {
        var self = this;
        this.CREATE_FAVORITE_SERVICE_URL = "/services/listService.asmx/CreateFavoritePlace";
        this.DELETE_FAVORITE_SERVICE_URL = "/services/listService.asmx/DeleteFavoritePlace";
        this.LIST_NAME = 'twentyplaces';
        this.LIST_TYPE = 'FavoritePlaces';
        this.CurrentIndex = 0;
        this.DEFAULT_ITEM_TEMPLATE = Linfo.Templates.FAVORITE_PLACE_FILLED_LIST_ITEM;
        this.EMPTY_ITEM_TEMPLATE = Linfo.Templates.FAVORITE_PLACE_EMPTY_LIST_ITEM;
        //this.itemSelector = "#places-list ol li"; //actually using this
        this.unselectedExpression = ".items li.item:has(div.empty)"; //using this
        this.nextUnselectedExpression = ".items li.item:has(div.empty)";
        this.saveText = "next";
        this.autoCompleterElement = '#textbox-places';
        this.locationElement = '#textbox-city-zip';
        this.filledExpression = '#places-list ol > li.filled';
        this.currentLinfoId = 0;
        this.maskMainEl = '#content-main';
        this.generateListItems = false;
        this.creatingNew = false;
        this.getListName = function() { return ""; };
        this.DELETE_ITEM_LINK = '#places-list ol li .remove';
        this.EDIT_ITEM_LINK = '#places-list ol li .edit';
        this.CLOSEST_ELEMENT_SELECTED_DATA = "li";
        this.GET_ITEM_SELECTOR = "#places-list ol li";
        this.SORTABLE_SELECTOR = "#places-list ol";
        this.SORTABLE_LIST = "#added-items ol";
        this.ENABLE_SUGGESTION = true;
        this.NO_SUGGESTIONS = 'ul.items';
        this.addBtnId = '#btn-add-item';
        this.TEXT_WHERE_INPUT = '#textbox-city-zip';
        this.TEXT_WHAT_INPUT = '#textbox-places';
        this.POPUP_TOP_OFFSET = -120;
        this.POPUP_LEFT_OFFSET = 50;
        this.TAB_NOTE_SELECTOR = "a.tab-note";
        this.TAB_PHOTO_SELECTOR = "a.tab-photo";
        this.TAB_LISTING_SELECTOR = "a.tab-listing";
        this.RunListLoad = false;
        this.isTextWhereValid = true;
        this.HasDefaultListTitle = true;
        this.SAVE_BTN = "#continue a";
        this.CompletedCount = '#placescompletedcount';
        this.lastSavedLocation = "Santa Monica, CA";
        this.isLocationValid = true;
        $.extend(this, config);
        $super(config);

        this.suggestionList = new Linfo.SuggestionsList({
            maskEl: '#suggestions',
            NO_SUGGESTIONS: this.NO_SUGGESTIONS,
            HasDefaultListTitle: self.HasDefaultListTitle,
            onSuggestionSelected: function(linfoId) {
                console.log(arguments, "suggetion clicked");
                Linfo.Events.trackSuggestionClick('favoriteplaces');
                return self.saveFavoriteListItemLinfo(linfoId);
            }
        });

        this.currentList.onListLoad = function(d) { self.onFavoriteListLoad(d); };
        this.currentList.HandleSaveListSuccess = function(d) { self.HandleSaveListSuccess(d); };

        this.listingPop.handleUploadSuccess = function(d) {
            //            var NewFilledItem = self.getItemAt(self.CurrentIndex - 1);
            //            NewFilledItem.selectedData.DefaultImageUri = d.d;
            //            $(NewFilledItem).find("img").attr("src", d.d);
            Linfo.Events.trackUploadPhoto();
        };
        this.listingPop.SWFUpload_Sucess_Handler = function(d, imgUrl) { console.log('hit success handler 1', arguments); self.SWFUpload_Sucess_Handler(d, imgUrl); };
        this.listingPop.SWFUploadExecute = function(swfu, linfoid) { console.log("hit swf upload excute 2"); self.SWFUploadExecute(swfu, this.currentSelectedData.LinfoId); };
        this.listingPop.getNextListElement = function() { self.getNextListElement(); };
        this.listingPop.onSaveFavoriteListItem = function(data) { self.onSaveFavoriteListItem(data); };
    },
    addAfter: function() {
        //get next number
        //append empty item to html list

        var count = this.getFilledItemCount();
        $('#placescompletedcount').html(count);
        if (this.getNumToMin() > 0 || this.getNumToMax() > 0) {
            $("#bucket .items").append(Linfo.Templates.GENERIC_FAVORITE_EMPTY_LIST_ITEM.apply({ Number: count + 1 }));
            $('#bucket .items').scrollTo('max');
        }
        if (this.getNumToMin() > 0) {
            $(this.SAVE_BTN).html("Only " + this.getNumToMin() + " more to go.");
        }
        else {
            $(this.SAVE_BTN).html(this.saveText);
        }
        this.showHideSaveBtn(count);
    },
    removeAfter: function() {
        var lastCount = this.getFilledItemCount();
        var nextCount = isNaN(lastCount) ? 1 : lastCount + 1;


        $("#bucket .items .item .empty .count").html(nextCount);

        if (this.getNumToMin() > 0) {
            if ($("#bucket .items .item .empty").length === 0) {
                console.log('adding empty');
                $("#bucket .items").append(Linfo.Templates.GENERIC_FAVORITE_EMPTY_LIST_ITEM.apply({ Number: nextCount }));
                $('#bucket .items').scrollTo('max');
            }

            $('#continue a').html("Only " + this.getNumToMin() + " more to go.");
        }
        this.showHideSaveBtn(lastCount);
    },
    showHideSaveBtn: function(count) {
        if (this.getNumToMin() <= 0) {
            $('#continue a').addClass('btn-600x45').removeClass('btn-600x45-disabled');
        }
        else {
            $('#continue a').addClass('btn-600x45-disabled').removeClass('btn-600x45');
        }
        $('#continue .nav').hide();
        return false;
    },
    handleEditClick: function(e) {
        var self = this;

        var selectedData = $(e.currentTarget).closest(this.CLOSEST_ELEMENT_SELECTED_DATA)[0].selectedData;
        self.CurrentIndex = selectedData.Number;
        self.currentLinfoId = selectedData.LinfoId;
        console.log("selected", selectedData);
        this.listingPop.show(e, selectedData);
        var linfoid = selectedData.LinfoId;
        this.listingPop.LINFO_ID = self.currentLinfoId;
        this.listingPop.CURRENT_INDEX = self.CurrentIndex;


        this.listingPop.handleUploadSuccess = function(d) {
            //console.log("DDDD", d);
            //            var NewFilledItem = self.getItemAt(self.CurrentIndex - 1);
            //            NewFilledItem.selectedData.DefaultImageUri = d.d;
            //            $(NewFilledItem).find("img").attr("src", d.d);
            Linfo.Events.trackUploadPhoto();
        };

        return false;
    },
    handleRemoveClick: function(e) {
        return this.deleteFavoriteListItem(e, $(e.currentTarget).closest("li")[0].selectedData);
    },
    run: function(loadListPath) {
        var self = this;
        //default this on load.if they are starting a new list.        

        $(this.SAVE_BTN).html("You have " + this.getNumToMin() + " more to go. You are almost done.");
        this.enableListSort();
        this.wireUpAutoCompleter();
        this.wireUpCityCompleter();
        if (this.ENABLE_SUGGESTION) {
            this.suggestionList.loadList(this.ZipCode); //default the zipcode to your location            
        }

        if (typeof (loadListPath) === 'undefined') {
            this.loadList();
        } else {
            this.currentList.loadListByPath('Linfo.Data.FavoritePlace', loadListPath);
        }
        $(this.autoCompleterElement).bind("keydown keypress keyup", function() {
            if ($(self.autoCompleterElement).val() !== "") {
                $("#businessName").val($(self.autoCompleterElement).val());
            }
        });


        $(this.DELETE_ITEM_LINK).livequery("click", function(e, selectedData) { console.log('arguments', arguments); return self.handleRemoveClick(e, selectedData); });



        google.setOnLoadCallback(function(l) {
            if (self.listingPop.gSearchOnLoad(l)) {
                //edit photo -- RI
                $(".photo").livequery("click", function(e) {
                    $('li.details').show();
                    return self.handleEditClick(e);
                });


                //edit note link -- RI
                $(".edit-note").livequery("click", function(e) {
                    $('li.details').show();
                    self.handleEditClick(e);
                    self.listingPop.showPanel('tab-note');
                    return false;
                });

            }
        });


        //$("#saveListing").bind("click", function(e) { return self.saveNewFavoriteListItem(); });
        //        $(self.addBtnId).livequery("click", function(e) {
        //            return self.PopUpNewItem();
        //        });
        //        $(self.TAB_PHOTO_SELECTOR).livequery("click", function(e) { self.listingPop.showPanel('tab-photo'); $('li.details').show(); return false; });
        //        $(self.TAB_NOTE_SELECTOR).livequery("click", function(e) { self.listingPop.showPanel('tab-note'); $('li.details').show(); return false; });
        //        $(self.TAB_LISTING_SELECTOR).livequery("click", function(e) {
        //            self.listingPop.showPanel('tab-listing'); $('li.details').hide(); return false;
        //        });

        $(this.SAVE_BTN).bind("click", function(e) {
            var Count = $(self.filledExpression).length;
            self.CheckNumToGo(Count);
            console.log('clicked on save button');
            if (self.getNumToMax() <= 0) {
                console.log('save and redirect');
                //self.saveList();
                window.location = "/home/favoritethings";

            }
            return false;
        });
        $(self.addBtnId).hide();
        Linfo.FlowControl.updateProgressMessaging('places', 0);
        self.saveList();
    },
    PopUpNewItem: function() {
        var self = this;

        if (this.getNumToMax() > 0) {
            self.listingPop.showPanel('tab-listing', 'listing');
            $(self.TAB_NOTE_SELECTOR).hide();
            $(self.TAB_PHOTO_SELECTOR).hide();
            $('li.details').hide();
            self.CheckCityStateZip();
            //default the name, location of the place you are adding            
            //$("#businessName").val($(self.TEXT_WHAT_INPUT).val());
            $('#popup-large').css("display", "block");
            //$(".location-info").livequery("click", function(e) {
            $("#businessAddNew").css("display", "block");
            $("#businessAddPhoto").css("display", "none");
            //});
            //reset the div/add new listing to be nothing
            $("#photopicker .items").html("");
            self.CurrentIndex = $(self.nextUnselectedExpression + ' span')[0].innerHTML;
            var x = $(self.autoCompleterElement)[0].getBoundingClientRect().left + self.POPUP_LEFT_OFFSET;
            var y = $(self.autoCompleterElement)[0].getBoundingClientRect().top + self.POPUP_TOP_OFFSET;
            console.log("x", x, "y", y);
            $('#popup-large .info').html();
            $('#popup-large .photo img').attr("src", "/static/images/place-place-holder-48x48.png");
            $('#popup-large').css({ left: x, top: y, display: 'block', position: 'absolute' });

        }
        return false;
    },
    CheckCityStateZip: function() {
        //check textbox-city-zip to be city,state, just city, or zip
        var self = this;
        var wordArray = $(self.TEXT_WHERE_INPUT).val().split(',');

        $("#businessZip").val("");
        $("#businessCity").val("");
        //$("#businessName").val("");
        if (!isNaN(wordArray[0])) {
            $("#businessZip").val(wordArray[0]);
        }
        else if (wordArray.length > 1) {
            $("#businessCity").val(wordArray[0]);
            // $("#businessState").val(wordArray[1]);
        }
        else {
            $("#businessCity").val(wordArray[0]);
        }
    },
    CheckNumToGo: function() {

        if (this.getNumToMax() > 0) {
            $(this.SAVE_BTN).html("You have " + this.getNumToMin() + " more to go. You are almost done.");
            return true;
        }
        else {
            Linfo.FlowControl.handleListCompletion('things');
            $(this.SAVE_BTN).html(this.saveText);
            return false;
        }

        return false;
    },
    HandleSaveListSuccess: function() {
        //window.location = "/home/favoritethings";
    },

    SWFUpload_Sucess_Handler: function(e, imgUrl) {
        console.log('handler args', arguments);
        $('#popup-large').hide();
        var self = this;
        var NewFilledItem = self.getItemAt(self.CurrentIndex - 1);
        NewFilledItem.selectedData.DefaultImageUri = imgUrl;
        $(NewFilledItem).find("img").attr("src", imgUrl);
        $("li.filled:eq(" + (self.CurrentIndex - 1) + ")").unblock();
    },

    SWFUploadExecute: function(swfu, linfoid) {
        var self = this;
        //swfu.settings.upload_url = "/home/UploadDesktopImage?imageCaption=" + $("#imagecaptionbox").val() + "&linfoid=" + linfoid;
        swfu.setUploadURL("/home/UploadDesktopImage?imageCaption=" + $("#imagecaptionbox").val() + "&linfoid=" + linfoid + "&itemtype=linfo");
        swfu.startUpload();
        $("li.filled:eq(" + (self.CurrentIndex - 1) + ") .photo").block({
            css: { border: 'none', backgroundColor: 'transparent' },
            overlayCSS: { backgroundColor: '#FFFFFF' },
            message: '<img src="/static/images/icon-wait-30x30.png" class="wait" />'
        });

    },

    saveList: function() {
        var self = this;
        if (this.getNumToMax() > 0) {
            Linfo.Events.trackListCreated('favoriteplaces', this.currentList.listHasDupes());
        }

        $(window).bind("beforeunload", function(e) {
            self.currentList.saveList();
        });

    },

    loadList: function() {
        this.currentList.loadList();
    },
    getItemDisplayHtml: function(selectedData) {
        return this.DEFAULT_ITEM_TEMPLATE.apply(selectedData);
    },
    deleteFavoriteListItem: function(e, selectedData) {
        var self = this;

        Linfo.A({
            url: this.DELETE_FAVORITE_SERVICE_URL,
            data: $.toJSON({ itemId: selectedData.UsersLinfoId }),
            //maskEl: '#places-list ol li:eq(' + newIndex + ')',
            success: function(d) { self.onDeleteFavoriteListItem(e, selectedData); }
        });

        return false;
    },
    saveFavoriteListItemLinfo: function(LinfoId) {
        var self = this;
        console.log('save favorite listitem linfo');
        if (this.isDupe(LinfoId, 'LinfoId')) {
            this.reportError("Hey, you already added that one!");
            return false;
        } else {
            Linfo.FlowControl.emptyProgress();
        }
        if (this.getNumToMax() > 0) {
            Linfo.A({
                url: this.CREATE_FAVORITE_SERVICE_URL,
                data: $.toJSON({ linfoid: LinfoId }),
                maskEl: self.getNextListElement(),
                success: function(d) { self.onSaveFavoriteListItem(d.d); }
            });
        }
        else {
            $(this.SAVE_BTN).html("You have already added " + this.getFilledItemCount() + " places");
        }

        return false;
    },

    saveNewFavoriteListItem: function() {
        var self = this;

        if (this.getNumToMax() > 0) {
            Linfo.A({
                url: "/services/listService.asmx/CreateNewFavoritePlace",

                data: $.toJSON({ businessName: $("#businessName").val(), businessAddress: $("#businessAddress").val(),
                    businessCity: $("#businessCity").val(), businessCountry: $('#businessCountry').val(), businessPhone: $("#businessPhone").val(),
                    businessCategory: $('#businessCategory').val(), businessSubCategory: $('#businessSubCategory').val(), businessZip: $("#businessZip").val()
                }),
                maskEl: self.getNextListElement(),
                cache: false,
                success: function(d) {
                    $("#businessAddNew").css("display", "none");
                    $("#businessAddPhoto").css("display", "block");
                    //reset all form variables
                    $(".address").html("<h5>" + $("#businessName").val() + "</h5><p class='info'><span class='street'>" + $("#businessAddress").val() + "</span><span class='city-zip'>" + $("#businessCity").val() + " " + $("#businessZip").val() + "</span><span class='phone'>" + $("#businessPhone").val() + "</span></p>");
                    $("[id^=business]").each(function() {
                        $(this).val("");
                    });
                    self.listingPop.LINFO_ID = d.d.LinfoId;
                    self.listingPop.search(d.d.Name);
                    //self.searchControl.execute(d.d.Name);
                    self.onSaveFavoriteListItem(d.d);

                    self.listingPop.currentSelectedData = d.d;
                    self.listingPop.showPanel('tab-photo');
                    $('ul.content li.details').html(self.listingPop.tpl_edit.apply(d.d));
                    $(self.TAB_NOTE_SELECTOR).show();
                    $(self.TAB_PHOTO_SELECTOR).show();
                    $('li.details').show();
                }
            });
        }
        else
        { $(this.SAVE_BTN).html("You have already added " + this.getFilledItemCount() + " places"); }
        return false;
    },

    onDeleteFavoriteListItem: function(e, selectedData) {
        var self = this;
        this.deRenderListItem($(e.currentTarget).closest("li")[0], selectedData);
        this.removeAfter();
        return false;
    },
    afterDeRender: function(element, data) {
        this.CheckNumToGo(this.getFilledItemCount());
        this.currentList.reorderList();
    },
    onSaveFavoriteListItem: function(favoritePlace) {
        var v = this.getNextListElement();
        var itemCount = this.getFilledItemCount();
        //item hasn't rendered yet so it will be the next item added,
        favoritePlace.Number = itemCount + 1;
        this.listingPop.CURRENT_INDEX = favoritePlace.Number;
        this.renderListItem(v, favoritePlace);
        this.addAfter();

    },
    onFavoriteListLoad: function(d) {
        var self = this;
        $.each(d.d, function(index, item) {
            var listElement = self.getNextListElement();

            var listData = item.Value;

            listData.Number = index + 1;
            self.renderListItem(listElement, listData);
            self.addAfter();
        });
    },
    handleForFilledCount: function(itemCount, minCount, maxCount) {
        Linfo.FlowControl.updateProgressMessaging('places', itemCount);
    },
    handleSearchResultSelect: function(selectionInfo, selectedData, value) {
        var self = this;
        console.log('inside handle search result select', arguments);
        if (typeof (selectedData.Id) == "undefined") {
            if (value == null) {
                console.log($(this.TEXT_WHAT_INPUT).val());
            }
            self.PopUpNewItem();
            return false;
        }
        else {
            $(this.TEXT_WHAT_INPUT).val('');
            return this.saveFavoriteListItemLinfo(selectedData.Id);
        }

    },

    enableListSort: function() {
        var self = this;

        $(this.SORTABLE_SELECTOR).sortable({
            cursor: 'pointer',
            update: function() { self.currentList.reorderList(); },
            cancel: self.nextUnselectedExpression
        }).disableSelection();
    },

    wireUpAutoCompleter: function() {
        var self = this;
        self.displayingDefaultPlaceText = true;
        $(this.autoCompleterElement).click(function() {

            if (self.displayingDefaultPlaceText) {
                $(this).val('');
            }
            self.displayingDefaultPlaceText = false;
        });

        //console.log(self.addBtnId, 'self add before locationsearchautocomplete');
        this.locationCompleter = new Linfo.LocationSearchAutoComplete(this.autoCompleterElement, {
            handleResult: function(i, d, v) { self.handleSearchResultSelect(i, d, v); if ($("#popup-large").is(':visible')) { $("#businessAddress").focus(); } },
            maskAddBtn: self.addBtnId,
            focusOnAfterSelect: function(field) { if ($("#popup-large").is(':visible')) { $("#businessAddress").focus(); } }
        });

        self.locationCompleter.lat = this.lat;
        self.locationCompleter.lng = this.lng;
    },

    wireUpCityCompleter: function() {
        var self = this;
        var loadListSuccess = false;
        var oldSelectedCity = $(self.TEXT_WHERE_INPUT).val();
        this.cityLocationCompleter = new Linfo.LinfoCityAutoComplete(this.locationElement, {
            lastSavedLocation: this.lastSavedLocation,
            handleResult: function(i, d, v) {
                console.log('arguments', arguments);
                $(self.locationElement).val(d.Location);

                self.locationCompleter.lat = d.Lat;
                self.locationCompleter.lng = d.Lng;

                var lac = $(self.autoCompleterElement);

                if (lac.val().length > 0) {
                    lac.focus().flushCache().reloadSearch();
                }
                //if you haven't loaded an initial list yet or if you change the city load suggestion lists
                if (!loadListSuccess || v !== oldSelectedCity) {
                    self.suggestionList.loadList(d.ZipCode);
                    loadListSuccess = true;
                    oldSelectedCity = v;
                }
                Linfo.setLocationCookie(d);
            }
        });
    }
});
﻿/*global window $ Linfo console google */
Linfo.FavoriteThingsController = $.klass(Linfo.BaseListController, {
    initialize: function($super, config) {
        var self = this;
        this.DEFAULT_ITEM_TEMPLATE = Linfo.Templates.FAVORITE_THING_FILLED_LIST_ITEM;
        this.EMPTY_ITEM_TEMPLATE = Linfo.Templates.FAVORITE_PEOPLE_EMPTY_SIDE_ITEM;
        this.PERSON_DEFAULT_ITEM_TEMPLATE = Linfo.Templates.GENERIC_FAVORITE_FRIEND_FILLED_LIST_ITEM;
        this.CREATE_FAVORITE_SERVICE_URL = "/services/listService.asmx/CreateFavoriteThing";
        this.DELETE_FAVORITE_SERVICE_URL = "/services/listService.asmx/DeleteFavoriteThing";
        this.addBtnId = '.btn-add';
        this.LIST_NAME = 'twentythings';
        this.LIST_TYPE = 'FavoriteThings';
        this.autoCompleterElement = Linfo.Selectors.FavoriteThings.INPUT_BOX;
        this.nextUnselectedExpression = Linfo.Selectors.FavoriteThings.FIRST_EMPTY_ITEM;
        this.unselectedExpression = "#bucket .items .item:has(div.empty)";
        this.filledExpression = Linfo.Selectors.FavoriteThings.FILLED_ITEM;
        this.DELETE_ITEM_LINK = Linfo.Selectors.FavoriteThings.DELETE_ITEM_LINK;
        this.EDIT_ITEM_LINK = ".controls .edit";
        this.saveText = "Next";
        this.SELECTED_DATA_ROW = "li.row";
        this.GET_ITEM_SELECTOR = "#added-items > li";
        this.generateListItems = false;
        this.creatingNew = false;
        this.getListName = function() { return ""; };
        this.OnSaveRedirectUrl = "/home/share";
        this.SAVE_BTN = "#continue a";
        this.SORTABLE_SELECTOR = "#added-items";
        this.SORTABLE_LIST = "#added-items";
        this.ENABLE_SUGGESTION = true;
        this.RunDeletion = function(e) { return true; };
        this.RunListLoad = false;
        this.HasDefaultListTitle = true;
        this.CLOSEST_ELEMENT_SELECTED_DATA = "li";
        this.CompletedCount = '#thingscompletedcount';
        $.extend(this, config);
        console.log($super, "super");
        $super(config);
        this.suggestionList = new Linfo.ThingsSuggestionsList({
            onSuggestionSelected: function(el) {
                console.log("test");
                self.saveFavoriteThing(el);
                return false;
            },
            HasDefaultListTitle: self.HasDefaultListTitle
        });

        this.currentList = new Linfo.LinfoAjaxList({
            getListName: this.getListName,
            creatingNew: this.creatingNew,
            type: this.LIST_TYPE,
            name: this.LIST_NAME,
            path: this.path || undefined,
            EMPTY_ITEM_TEMPLATE: this.EMPTY_ITEM_TEMPLATE,
            FILLED_ITEM_TEMPLATE: this.DEFAULT_ITEM_TEMPLATE,
            ITEM_SELECTOR: this.filledExpression,

            getListItems: function() {
                return $.map($(this.ITEM_SELECTOR + '.filled'), function(item, idx) {
                    return { ItemId: item.selectedData.Id, ItemOrder: idx };
                });
            }
        });

        this.currentList.onListLoad = function(d) { self.onFavoriteListLoad(d); };
        this.currentList.HandleSaveListSuccess = function(d) { self.HandleSaveListSuccess(); };
        this.listingPop.SWFUploadExecute = function(swfu, linfoid) { self.SWFUploadExecute(swfu, linfoid); };
        this.listingPop.SWFUpload_Sucess_Handler = function(e, imgurl) { self.SWFUpload_Sucess_Handler(e, imgurl); };
    },
    addAfter: function() {
        //get next number
        //append empty item to html list

        var count = this.getFilledItemCount();
        $('#thingscompletedcount').html(count);
        if (this.getNumToMin() > 0 || this.getNumToMax() > 0) {
            $("#bucket .items").append(Linfo.Templates.GENERIC_FAVORITE_EMPTY_LIST_ITEM.apply({ Number: count + 1 }));
            $('#bucket .items').scrollTo('max');
        }
        if (this.getNumToMin() > 0) {
            $(this.SAVE_BTN).html("Only " + this.getNumToMin() + " more to go.");
        }
        else {
            $(this.SAVE_BTN).html(this.saveText);
        }
        this.showHideSaveBtn(count);
    },
    removeAfter: function() {
        var lastCount = this.getFilledItemCount();
        var nextCount = isNaN(lastCount) ? 1 : lastCount + 1;

        console.log('removeAfter', 'lastCount:', lastCount, 'nextCount:', nextCount);

        $("#bucket .items .item .empty .count").html(nextCount);

        if (this.getNumToMin() > 0) {
            if ($("#bucket .items .item .empty").length === 0) {
                console.log('adding empty');
                $("#bucket .items").append(Linfo.Templates.GENERIC_FAVORITE_EMPTY_LIST_ITEM.apply({ Number: nextCount }));
                $('#bucket .items').scrollTo('max');
            }

            $(this.SAVE_BTN).html("Only " + this.getNumToMin() + " more to go.");
        }
        this.showHideSaveBtn(lastCount);
    },
    showHideSaveBtn: function(count) {
        //console.log("count", count);
        if (this.getNumToMin() <= 0) {
            $(this.SAVE_BTN).addClass('btn-600x45').removeClass('btn-600x45-disabled');
        }
        else {
            $(this.SAVE_BTN).addClass('btn-600x45-disabled').removeClass('btn-600x45');
        }
        $('#continue .nav').hide();
        return false;
    },
    run: function(loadListPath) {
        var self = this;
        this.enableListSort();
        this.wireUpAutoCompleter();
        if (this.ENABLE_SUGGESTION) {
            this.suggestionList.loadList();

            //                $('.suggestions ul li').livequery("mouseover", function(e) {
            //                });            
        }

        $(this.addBtnId).bind("click", function(e) {

            self.saveFavoriteThing({
                name: $('#textbox-add-item').val(),
                image: null,
                type: '',
                article: null
            });

            return false;
        });
        $('#textbox-add-item').keyup(function(e) {
            //alert(e.keyCode);
            if (e.keyCode == 13 && $.trim($("#textbox-add-item").val()).length > 0) {
                self.saveFavoriteThing({
                    name: $('#textbox-add-item').val(),
                    image: null,
                    type: '',
                    article: null
                });
                $('#textbox-add-item').val();
                $("#fbs_list").hide();
            }
            return false;
        });


        if (typeof (loadListPath) === 'undefined') {
            this.loadList();
        } else {
            this.currentList.loadListByPath('Linfo.Data.FavoriteThing', loadListPath);
        }

        $(this.DELETE_ITEM_LINK).livequery("click", function(e) {

            var selectedData = $(e.currentTarget).closest(self.SELECTED_DATA_ROW)[0].selectedData;

            if (self.RunDeletion(e)) {
                if (typeof (selectedData.Number) === 'undefined') {
                    self.deleteFavoriteListItem(selectedData.Id, selectedData.number, e);
                }
                else {
                    self.deleteFavoriteListItem(selectedData.Id, selectedData.Number, e);
                }
            }

        });
        //        $(this.EDIT_ITEM_LINK).livequery("click", function(e) {

        //            //$(self.TAB_PHOTO_SELECTOR).show();
        //            $('li.details').show(); $("#businessAddPhoto").css("display", "block"); return self.handleEditClick(e);
        //        });
        $("#bucket .photo").livequery("click", function(e) {
            $('li.details').show(); $("#businessAddPhoto").css("display", "block");
            self.listingPop.showPanel('tab-photo');
            return self.handleEditClick(e);
        });
        google.setOnLoadCallback(function(l) { self.listingPop.gSearchOnLoad(l); });

        $(self.SAVE_BTN).livequery("click", function(e) {
            console.log('save button click');
            if (self.getNumToMin() > 0) {
                self.CheckNumToGo();
            }
            else {
                //self.saveList();
                window.location = "/home/share";
            }
            return false;
        });
        Linfo.FlowControl.updateProgressMessaging('things', 0);
        self.saveList();
    },
    HandleSaveListSuccess: function() {

        window.location = this.OnSaveRedirectUrl;
    },
    handleEditClick: function(e) {
        var self = this;

        var selectedData = $(e.currentTarget).closest(this.CLOSEST_ELEMENT_SELECTED_DATA)[0].selectedData;
        self.CurrentIndex = selectedData.Number || selectedData.number;
        self.currentLinfoId = selectedData.Id;
        console.log("selected", selectedData);
        this.listingPop.show(e, selectedData);
        this.listingPop.LINFO_ID = selectedData.Id;
        selectedData.LinfoId = selectedData.Id;
        this.listingPop.CURRENT_INDEX = self.CurrentIndex;
        this.listingPop.currentLinfoId = self.currentLinfoId;
        this.listingPop.handleUploadSuccess = function(d) {
            console.log('HUS', self, self.CurrentIndex);
            var NewFilledItem = self.getItemAt(self.CurrentIndex - 1);
            console.log(d.d, "defaultImageUri");
            NewFilledItem.selectedData.DefaultImageUri = d.d;
            $(NewFilledItem).find("img").attr("src", d.d);
            Linfo.Events.trackUploadPhoto();
        };

        return false;
    },
    SWFUpload_Sucess_Handler: function(e, imgUrl) {
        $('#popup-large').hide();
        var self = this;
        console.log("SWFSuccess", this);
        console.log("CI = ", self.CurrentIndex);
        var NewFilledItem = self.getItemAt(self.CurrentIndex - 1);
        NewFilledItem.selectedData.DefaultImageUri = imgUrl;
        $(NewFilledItem).find("img").attr("src", imgUrl);
        $("li.filled:eq(" + (self.CurrentIndex - 1) + ")").unblock();
    },

    CheckNumToGo: function() {

        if (this.getNumToMax() > 0) {
            $(this.SAVE_BTN).html("You have " + this.getNumToMin() + " more to go. You are almost done.");
            return true;
        }
        else {
            Linfo.FlowControl.handleListCompletion('things');
            $(this.SAVE_BTN).html(this.saveText);
            return false;
        }

        return false;
    },
    saveList: function() {
        var self = this;
        $(window).bind("beforeunload", function(e) {
            self.currentList.saveList();
        });
    },

    loadList: function() {
        this.currentList.loadList();
    },
    handleSuggestionSelect: function(e) {

    },

    getClosestItem: function(e) {

    },

    getItemDisplayHtml: function(selectedData) {

        if (typeof (selectedData.city) === "undefined") {
            return this.DEFAULT_ITEM_TEMPLATE.apply(selectedData);
        }
        else {
            return this.PERSON_DEFAULT_ITEM_TEMPLATE.apply(selectedData);
        }
    },
    SWFUploadExecute: function(swfu, linfoid) {
        var self = this;
        //swfu.settings.upload_url = "/home/UploadDesktopImage?imageCaption=" + $("#imagecaptionbox").val() + "&linfoid=" + linfoid;
        swfu.setUploadURL("/home/UploadDesktopImage?imageCaption=" + $("#imagecaptionbox").val() + "&linfoid=" + linfoid);
        swfu.startUpload();
        console.log(self.CurrentIndex, 'current index');
        $("li.filled:eq(" + (self.CurrentIndex - 1) + ") .photo").block({
            css: { border: 'none', backgroundColor: 'transparent' },
            overlayCSS: { backgroundColor: '#FFFFFF' },
            message: '<img src="/static/images/icon-wait-30x30.png" class="wait" />'
        });

    },
    deleteFavoriteListItem: function(thingId, index, e) {
        var self = this;
        //search for the span count that has this index in it and delete it        

        $.ajax({
            type: "POST",
            url: this.DELETE_FAVORITE_SERVICE_URL,
            data: $.toJSON({ itemId: thingId }),
            contentType: "application/json; charset=utf-8",
            cache: false,
            dataType: "json",
            success: function(d) { self.onDeleteFavoriteListItem(thingId, index, e); }
        });
        //derender li.. 
    },

    isSuggestion: function(e) {
        return typeof (e.What) !== 'undefined';
    },
    handleForFilledCount: function(itemCount, minCount, maxCount) {
        Linfo.FlowControl.updateProgressMessaging('things', itemCount);
    },
    saveFavoriteThing: function(thing) {
        var self = this;
        var thingData = thing;
        console.log('arguments', arguments);
        if (self.CheckNumToGo()) {
            if (typeof (thingData.Name) === "undefined")
                thingData.Name = thingData.name;
            if (this.isDupe(thingData.Name, 'Name')) {
                this.reportError("Hey, you already added that one!");
                return false;
            } else {
                Linfo.FlowControl.emptyProgress();
            }
            if (this.isSuggestion(thing)) {
                thingData = {
                    imageId: thing.FreebaseImageId,
                    typeId: thing.FreebaseType,
                    name: thing.Name,
                    articleGuid: thing.FreebaseArticleId,
                    guid: thing.FreebaseID
                };
            } else {
                thingData.imageId = thingData.image !== null ? thingData.image.id : null;
                thingData.typeId = thingData.type.length >= 2 ? thingData.type[1].id : null;
                thingData.guid = typeof (thingData.guid) !== 'undefined' ? thingData.guid.replace('#', '') : null;
                thingData.articleGuid = thingData.article !== null ? thingData.article.id.replace('/guid/', '') : null;

            }
            console.log('thingdata', thingData);
            Linfo.A({
                url: this.CREATE_FAVORITE_SERVICE_URL,
                data: $.toJSON({ what: thingData.name, type: thingData.typeId, fbArticleId: thingData.articleGuid, fbId: thingData.guid, imageId: thingData.imageId }),
                success: function(d) { self.onSaveFavoriteListItem(d.d); }
            });
        }
        else {
            $(self.SAVE_BTN).html("You have already added " + this.getFilledItemCount() + " things");
        }
    },

    isDupe: function(id, prop) {
        return $.inArray(id, $.pluck($.pluck(this.getFilledItems(), 'selectedData'), prop)) > -1;
    },
    onDeleteFavoriteListItem: function(LinfoId, index, e) {
        var self = this;
        self.deRenderListItem($(e.currentTarget).closest("li")[0], $(e.currentTarget).closest("li")[0].selectedData);

        this.removeAfter();
        return false;
    },
    onSaveFavoriteListItem: function(favoriteThing) {
        console.log(favoriteThing, 'saved fav thing');
        console.log('save favorite list item');
        favoriteThing.Number = this.getFilledItemCount() + 1;
        favoriteThing.DefaultImageUri = favoriteThing.DefaultImageUri.length === 0 ? '/static/images/thing-place-holder-48x48.png' : favoriteThing.DefaultImageUri;
        this.renderListItem(this.getNextListElement(), favoriteThing);
        $('#completedcount').html(favoriteThing.Number);
        this.addAfter();
    },
    afterDeRender: function(element, data) {
        $(this.CompletedCount).html(this.getFilledItemCount());
        this.CheckNumToGo();
        this.currentList.reorderList();
    },

    onFavoriteListLoad: function(d) {
        var self = this;

        Linfo.Events.startTrackingCount('favoritethings');

        $.each(d.d, function(index, item) {
            var listElement = self.getNextListElement();
            var listData = item.Value;
            listData.Number = index + 1;
            //console.log(index, item);
            self.renderListItem(listElement, listData);
            self.addAfter();
        });
    },

    handleSearchResultSelect: function(selectedData) {
        this.saveFavoriteThing(selectedData);
    },
    enableListSort: function() {
        var self = this;

        $(this.SORTABLE_SELECTOR).sortable({
            connectWith: self.SORTABLE_LIST,
            cursor: 'pointer',
            update: function(e, el) { console.log('in here'); self.currentList.reorderList(); },
            cancel: this.nextUnselectedExpression
        }).disableSelection();
    },

    wireUpAutoCompleter: function() {
        var self = this; console.log($(this.autoCompleterElement).freebaseSuggest(), 'wire up auto completer');
        $(this.autoCompleterElement).freebaseSuggest().bind('fb-select', function(el, data) {
            console.log('fb-select', arguments);
            self.handleSearchResultSelect(data);
        });
    }
});
﻿/*global window $ Linfo console google FB locationInfo tb_show location */

Linfo.UserProfileController = $.klass({
    initialize: function(config) {
        $.extend(this, config);

        var self = this;

        this.ITEM_TEMPLATE = Linfo.Templates.USERPROFILE_DEFAULT_ITEM;
        this.USER_TEMPLATE = Linfo.Templates.USERPROFILE_USER_ITEM;
        this.PLACE_TEMPLATE = Linfo.Templates.USERPROFILE_PLACE_ITEM;
        this.PLACE_FULL_LIST_TEMPLATE = Linfo.Templates.GENERIC_FAVORITE_PLACE_LIST_ALL;
        this.THING_FULL_LIST_TEMPLATE = Linfo.Templates.GENERIC_FAVORITE_THING_LIST_ALL;
        this.USER_FULL_LIST_TEMPLATE = Linfo.Templates.GENERIC_FAVORITE_FRIENDS_LIST_ALL;
        this.FULL_LIST_HEADER = Linfo.Templates.GENERIC_LIST_ALL_HEADER;
        this.FULL_LIST_CONTENT = '';

        this.locationElement = "#textbox-location";
        this.autoCompleterElement = "#textbox-what";

        this.POPUP_EMPTY = Linfo.Templates.GENERIC_LIST_EMPTY;
        this.THICKBOX_SELECTOR = "#popup-list";
        this.RECAP_ITEM_TEMPLATE = $.template('<em>${Name}</em>&nbsp;');
        this.RECAP_USER_ITEM_TEMPLATE = $.template('<em><a href="/user/${Name}/${UserId}">${Name}</a></em>&nbsp;');
        this.RECAP_PLACE_ITEM_TEMPLATE = $.template('<em><a href="/place/${UrlEncodedName}/${LinfoId}">${Name}</a></em>&nbsp;');
        this.RECAP_THING_TEMPLATE = $.template('<em>${Name}</em>&nbsp;');

        this.listManager = new Linfo.LinfoAjaxList({
            onListLoad: function(l, p, t) {
                self.handleListLoad(l, p, t);

            },
            ITEM_TEMPLATE: this.ITEM_TEMPLATE
        });

        self.expandAllLists($('#favorites'));
        self.expandAllLists($('#lists-list'));
        $('.btn-expand').click(function(e) { return self.handleListExpansion(e); });
        $('#profile-tab').click(function() {
            self.showPanelForAllFriends();
            $("#friend-drop-down option[value='0']")[0].selected = true;
            self.expandFirstList('#favorites');
            return self.showTab('#favorites');
        });
        $('#friends-tab').click(function() { return self.showTab('#friend-list'); });
        $('#notes-tab').click(function() { return self.showTab('#note-list'); });
        $('#lists-tab').click(function() {
            self.expandFirstList('#lists-list');
            $("li.row:has(ul.content[uid='" + $("#user").attr("uid") + "'])").show();
            $("li.row:has(ul.content[uid!='" + $("#user").attr("uid") + "'])").hide();
            return self.showTab('#lists-list');
        });

        $("li.friend a").livequery("click", function(e) {
            var faceBookId = $(this).attr("uid");
            if (typeof ($("#friend-drop-down option[value='" + faceBookId + "']")[0]) != "undefined") {
                $("#friend-drop-down option[value='" + faceBookId + "']")[0].selected = true;
                self.showTab("#favorites");
                self.showPanelForFriend(faceBookId);
            }
            return false;
        });

        $("#friend-drop-down").change(function(e) {
            var faceBookId = $(this).val();
            console.log(faceBookId);
            if (faceBookId === "0") {
                self.showPanelForAllFriends();
            }
            else {
                self.showPanelForFriend(faceBookId);
            }
        });
        $('li.all a').livequery("click", function(e) {
            var toShow = $(e.currentTarget).closest("ul.content")[0];
            self.populateListPreview(toShow);
            tb_show(null, "TB_inline?height=550&width=390&inlineId=popup-list&modal=true");
            return false;
        });

        $('.delete-list').livequery("click", function(e) {
            var toDelete = $(e.currentTarget);
            var title = toDelete.attr("linfo_listtitle");
            var path = toDelete.attr("linfo_listpath");

            console.log(toDelete);

            var ok = confirm('Are you sure you want to permanently delete "' + toDelete.attr("linfo_listtitle") + '"?');

            if (ok) {
                self.deleteList(path);
            }

            return false;
        });

        this.wireUpCityCompleter();
        this.wireUpAutoCompleter();
        //this.expandFirstList('#lists-list');

        Linfo.FlowControl.initProfile();

        // Initialize history plugin.
        // The callback is called at once by present location.hash.
        //$.history.init(self.pageload);

        // set onlick event for buttons
        //        $("a[rel='history']").click(function() {
        //            // 
        //            var hash = this.href;
        //            hash = hash.replace(/^.*#/, '');
        //            if (hash.length < 0) {
        //                hash = "lists-list";
        //            }
        //            // moves to a new page.
        //            // pageload is called at once.                     
        //            $.history.load(hash);
        //            return false;
        //            });

    },

    deleteList: function(path) {
        Linfo.A({
            url: '/services/ListService.asmx/DeleteList',
            data: $.toJSON({ path: path }),
            success: function() {
                $('#lists-list li.row[linfo_listpath=' + path + ']').remove();
            }
        });
    },

    pageload: function(hash) {
        var showTabString = "#";
        if (hash.length > 0) {
            showTabString += hash;
        }
        else { showTabString += "lists-list"; }
        $('.tab-data').hide();
        $(showTabString).show();

    },

    showPanelForFriend: function(faceBookId) {
        $('li.row:has(ul.content[uid!=' + faceBookId + '])').hide();
        $('li.row:has(ul.content[uid=' + faceBookId + '])').show();
    },
    showPanelForAllFriends: function() {
        $('li.row').show();
    },
    getListType: function(element) {
        return element.attr("linfo_listtype");
    },
    expandAllLists: function(root) {
        var self = this;
        $.each($('ul.content', root), function(e) {
            self.loadExpandedList($(this));
        });
    },
    populateListPreview: function(toShow) {
        var self = this;
        var listType = self.getListType($(toShow));
        $(self.THICKBOX_SELECTOR).html(self.POPUP_EMPTY.apply(''));

        self.setHeaderPopUpData(toShow);
        var fullListTemplate = self.getFullListTemplateForType(listType);
        //        console.log(listType, "listtype", fullListTemplate);
        $.each($(toShow)[0].selectedData, function(idx, val) {
            if (val.Value.DefaultImageUri == "") {
                val.Value.DefaultImageUri = "/static/images/place-place-holder-48x48.png";
            }
            val.Value.UrlEncodedName = encodeURIComponent(val.Value.Name);
            
            $(self.THICKBOX_SELECTOR + ' div.content ul.items').append(fullListTemplate, $.extend(val.Value, { Number: idx + 1 }));
        });
        self.refreshUserAvatars($(self.THICKBOX_SELECTOR).get(0));
    },
    expandFirstList: function(root) {

        var el = $(root + ' ul.content:first');
        if (el.attr("linfo_loaded") != "true") {
            this.listManager.loadListByPath(
                el.attr("linfo_listtype"),
                el.attr("linfo_listpath")
            );
        } else {
            this.collapseListsAndShow(el);
        }
    },

    handleListExpansion: function(e) {
        var t = $(e.currentTarget);
        var el = t.parents("ul.content");

        this.loadExpandedList(el);
        return false;
    },
    loadExpandedList: function(el) {
        var isActive = el.is('.active');

        if (isActive) {
            el.removeClass('active');
            return false;
        }

        var path = el.attr("linfo_listpath");
        var type = el.attr("linfo_listtype");
        //this.ListId = el.attr("listid");
        var detailEl = el;
        if (detailEl.attr("linfo_loaded") != 'true') {
            this.listManager.loadListByPath(type, path);
        }
        else {
            this.collapseListsAndShow(detailEl, type);
        }
    },
    refreshUserAvatars: function(domElement) {

        //        var newImages = $('fb\\:profile-pic:not( .fb_profile_pic_rendered )').map(function() {
        //            return new FB.XFBML.ProfilePic(this);
        //        });
        //        alert($('fb\\:profile-pic:not( .fb_profile_pic_rendered )').length);
        //        FB.XFBML.Host.addElements(newImages);
        //        console.log(domElement, "dom element");
        FB.XFBML.Host.parseDomElement(domElement);
        //FB.XFBML.Host.parseDomTree();     
    },

    showTab: function(tab) {
        $('.tab-data').hide();
        $(tab).show();
        return false;
    },

    collapseListsAndShow: function(toShow, listType) {
        var self = this;
        listType = self.getListType(toShow);
        //$('.active').removeClass('active');
        //$('.tabbed-content').addClass('hidden');
        $(toShow).attr("linfo_loaded", 'true').addClass('active');

        //        $(self.THICKBOX_SELECTOR).html(self.POPUP_EMPTY.apply(''));

        //        self.setHeaderPopUpData(toShow);
        //        var fullListTemplate = self.getFullListTemplateForType(listType);
        //        console.log(listType, "listtype", fullListTemplate);
        //        $.each($(toShow)[0].selectedData, function(idx, val) {
        //            $(self.THICKBOX_SELECTOR + ' div.content ul.items').append(fullListTemplate, $.extend(val.Value, { Number: idx + 1 }));
        //        });
        //        self.refreshUserAvatars($(self.THICKBOX_SELECTOR).get(0));

    },
    setHeaderPopUpData: function(toShow) {
        var self = this;
        var detailEl = $(toShow);
        var HeaderObj = {};
        //need to check to see if the src of the image has been rendered by fb.
        //        console.log(toShow,'toshow');
        HeaderObj.FacebookId = detailEl.attr("uid");
        HeaderObj.UserId = $(detailEl).closest('li.item').siblings('li.photo').children('a').attr("href").split("/")[$(detailEl).closest('li.item').siblings('li.photo').children('a').attr("href").split("/").length - 1];
        HeaderObj.UserName = $.trim((detailEl).siblings('h5.description').children('a.user-name').html());
        HeaderObj.Title = $.trim((detailEl).siblings('h5.description').children('strong').html());
        HeaderObj.Time = $.trim((detailEl).siblings('h5.description').children('strong.time-stamp').children('.time').html());
        HeaderObj.Date = $.trim((detailEl).siblings('h5.description').children('strong.time-stamp').children('.date').html());
        var tempFullHeader = self.FULL_LIST_HEADER.apply(HeaderObj);
        //        console.log(tempFullHeader, 'temp full header');
        $(self.THICKBOX_SELECTOR + ' div.popup-list').prepend(tempFullHeader);
    },

    getFullListTemplateForType: function(t) {
        var self = this;

        if (t === 'Linfo.Data.User') { return self.USER_FULL_LIST_TEMPLATE; }
        if (t === 'Linfo.Data.FavoritePlace') { return self.PLACE_FULL_LIST_TEMPLATE; }
        if (t === 'Linfo.Data.FavoriteThing') { return self.THING_FULL_LIST_TEMPLATE; }
        if (t === 'Linfo.Data.FavoriteHybridThing') { return self.THING_FULL_LIST_TEMPLATE; }
    },
    getTemplateForType: function(t) {
        var self = this;

        if (t === 'Linfo.Data.User') { self.RECAP_ITEM_TEMPLATE = self.RECAP_USER_ITEM_TEMPLATE; self.FULL_LIST_CONTENT = self.USER_FULL_LIST_TEMPLATE; return this.USER_TEMPLATE; }
        if (t === 'Linfo.Data.FavoritePlace') { self.RECAP_ITEM_TEMPLATE = self.RECAP_PLACE_ITEM_TEMPLATE; self.FULL_LIST_CONTENT = self.PLACE_FULL_LIST_TEMPLATE; return this.PLACE_TEMPLATE; }
        if (t === 'Linfo.Data.FavoriteThing') { self.RECAP_ITEM_TEMPLATE = self.RECAP_THING_TEMPLATE; self.FULL_LIST_CONTENT = self.THING_FULL_LIST_TEMPLATE; return this.ITEM_TEMPLATE; }
        if (t === 'Linfo.Data.FavoriteHybridThing') { self.RECAP_ITEM_TEMPLATE = self.RECAP_THING_TEMPLATE; self.FULL_LIST_CONTENT = self.THING_FULL_LIST_TEMPLATE; return this.ITEM_TEMPLATE; }
    },

    handleListLoad: function(l, p, t) {
        var self = this;                
        $(self.THICKBOX_SELECTOR).html(self.POPUP_EMPTY.apply(''));
        var detailEl = $('ul .content[linfo_listpath=' + p + ']');
        var content = detailEl.children('.tabbed-content');


        //save list so you can show the entire list when the user clicks see all, this will have the entire list array attached to this element.
        $(detailEl)[0].selectedData = l.d;


        var lst = l.d.slice(0, 7);
        var len = lst.length >= 7 ? 7 : lst.length;
        var listType = detailEl.attr('linfo_listtype'); //  === "Linfo.Data.User";
        var tpl = this.getTemplateForType(listType);

        //create full list            
        //        $.each(l.d, function(idx, val) {
        //            $(self.THICKBOX_SELECTOR + ' div.content ul.items').append(self.FULL_LIST_CONTENT, $.extend(val.Value, { Number: idx + 1 }));
        //        });
        var body = "";
        var top5Selector = $('.top-5', detailEl).get(0);
        $.each(lst, function(idx, i) {
        // console.log(tpl);
        if (i.Value.DefaultImageUri == "") {
            i.Value.DefaultImageUri = "/static/images/place-place-holder-48x48.png";
        }
            body += tpl.apply($.extend(i.Value, { ListName: self.listManager.Title, Number: idx + 1 }));
            //have to use innerHtml here because IE won't render the fb pics correctly
            top5Selector.innerHTML = body;
        });

        //checking for last and other items in the list, use a comma or and at the very last one.
        $.each(l.d.slice(0, len), function(idx, i) {

            $.extend(i.Value, { UrlEncodedName: i.Value.Name.replace('?', ' ').replace('&', ' ') });

            if (l.d.length > 1) {
                var prefix = (idx == len - 1) ? " and " : "";
                var suffix = (idx < len - 2) ? ", " : "";
                var text = prefix + self.RECAP_ITEM_TEMPLATE.apply(i.Value) + suffix;
                $('.recap li p', detailEl).append(text);
            }
            else {
                $('.recap li p', detailEl).append(self.RECAP_ITEM_TEMPLATE.apply(i.Value));
            }
        });


        if (listType === 'Linfo.Data.User') {
            self.refreshUserAvatars(top5Selector);
            //            console.log($(self.THICKBOX_SELECTOR));
        }

        //        console.log(detailEl);
        //if (detailEl.find('li.tabbed-content  ul.tabs li.tab ul.top-5 li').length < 7) {
        if (l.d.length <= 7) {
            detailEl.find('li.tabbed-content  ul.tabs li.tab ul.recap li.all').hide();
        }
        self.collapseListsAndShow(detailEl, listType);
    },

    handleSearchResultSelect: function(e, v) {
        if (v.Id !== '') {
            location.href = '/place/' + Linfo.escapeName(v.Name) + '/' + v.Id;
        }
    },

    wireUpAutoCompleter: function() {
        var self = this;
        self.displayingDefaultPlaceText = true;
        $('#textbox-what').click(function() {
            if (self.displayingDefaultPlaceText) {
                $(this).val('');
            }
            self.displayingDefaultPlaceText = false;
        });

        this.locationCompleter = new Linfo.LocationSearchAutoComplete(this.autoCompleterElement, {
            handleResult: function(i, d, v) { self.handleSearchResultSelect(i, d, v); },
            disableNoResults: false
        });

        self.locationCompleter.lat = locationInfo.lat;
        self.locationCompleter.lng = locationInfo.lng;
    },

    wireUpCityCompleter: function() {
        var self = this;

        this.cityLocationCompleter = new Linfo.LinfoCityAutoComplete(this.locationElement, {
            handleResult: function(i, d, v) {
                $(self.locationElement).val(d.Location);
                self.locationCompleter.lat = d.Lat;
                self.locationCompleter.lng = d.Lng;
                Linfo.setLocationCookie(d);
            }
        });
    }
});
﻿/*global $ Linfo console window */

Linfo.FavoritePeopleController = $.klass({
    initialize: function(xmlText, config) {
        var self = this;
        this.xmlText = $.xml2json(xmlText);
        this.DEFAULT_ITEM_TEMPLATE = Linfo.Templates.FAVORITE_PEOPLE_ITEM;
        this.DEFAULT_SIDE_ITEM_TEMPLATE = Linfo.Templates.FAVORITE_PEOPLE_SIDE_ITEM;
        this.DEFAULT_SIDE_ITEM_EMPTY_TEMPLATE = Linfo.Templates.FAVORITE_PEOPLE_EMPTY_SIDE_ITEM;
        this.THING_ITEM_TEMPLATE = Linfo.Templates.GENERIC_FAVORITE_FILLED_LIST_ITEM;
        this.SAVE_FAVORITE_FRIEND_LIST_URL = "/services/ListService.asmx/SaveFriendsList";
        this.LOAD_FAVORITE_FRIEND_LIST_URL = "/services/FriendsService.asmx/GetFriends";
        this.MIN_TO_PROCEED = 20;
        this.MAX_FRIEND_COUNT = 20;
        this.ItemCount = 0;
        this.selectExpression = "#friends-list ul";
        this.nextUnselectedExpression = '#content-sub #bucket .content ul.items li.empty';
        this.filledExpression = '#content-sub #bucket .content ul.items li.filled';
        this.autoCompleterElement = '#what';
        this.LIST_TYPE = "Friends";
        this.LIST_NAME = "twentyfriends";
        this.LIST_ID = 0;
        this.SAVE_BTN = "#continue .btn-next";
        this.SORTABLE_SELECTOR = "#content-sub #bucket .content ul.items";
        this.LIST_TITLE = "";
        this.DELETE_ITEM_LINK = '#content-sub #bucket .content ul.items li.filled span.remove';
        this.generateListItems = true;
        /* default implementations */
        this.showHideSaveBtn = function(count) {

            if ((this.getFilledItemCount() - this.MIN_TO_PROCEED) > 0) {
                $('#continue a.btn-next').addClass('btn-600x45').removeClass('btn-600x45-disabled');
            }
            else {
                $('#continue a.btn-next').addClass('btn-600x45-disabled').removeClass('btn-600x45');
            }
            $('#continue .nav').hide();
            return false;
        };
        this.addAfter = function() {
            var count = this.getFilledItemCount();
            $('#thingscompletedcount').html(count);
            if ((this.getFilledItemCount() - this.MIN_TO_PROCEED) >= 0 || this.getFilledItemCount() - this.MAX_FRIEND_COUNT <= 0) {
                console.log("add after");
                $("#bucket .items").append(Linfo.Templates.GENERIC_FAVORITE_EMPTY_LIST_ITEM.apply({ Number: count + 1 }));
                $('#bucket .items').scrollTo('max');
            }
            if ((this.getFilledItemCount() - this.MIN_TO_PROCEED) < 0) {
                $('#continue a.btn-600x45-disabled').html("Only " + (this.MIN_TO_PROCEED - this.getFilledItemCount()) + " more to go.");
                console.log("inside if statement");
            }
            else {
                console.log("else statement");
                $('#continue a.btn-600x45-disabled').html(this.saveText);
            }
            return this.showHideSaveBtn(count);
        };
        this.removeAfter = function() {
            var self = this;
            var count = isNaN(parseInt($(self.filledExpression + ":last span.count").html(), 10)) ? 1 :
            parseInt($(self.filledExpression + ":last span.count").html(), 10) + 1;
            $(self.nextUnselectedExpression + ":first span.count").html(count);
        };
        //this.deRenderListItem = function(number) { };
        this.SaveFavoriteThing = Linfo.emptyFn;
        this.RunDeletion = Linfo.boolFn(true);
        this.RunListLoad = true;
        this.CompletedCount = '#peoplecompletedcount';

        $.extend(this, config);

        this.currentList = new Linfo.LinfoAjaxList({
            type: this.LIST_TYPE,
            name: this.LIST_NAME,
            path: this.path || undefined,
            LIST_TITLE: self.LIST_TITLE,
            EMPTY_ITEM_TEMPLATE: this.DEFAULT_SIDE_ITEM_EMPTY_TEMPLATE,
            FILLED_ITEM_TEMPLATE: this.DEFAULT_SIDE_ITEM_TEMPLATE,
            ITEM_SELECTOR: this.filledExpression,
            maskEl: '#added-people',
            getListItems: function() {
                return $.map($(this.ITEM_SELECTOR + '.filled'), function(item, idx) {
                    return { ItemId: item.selectedData.UserId, ItemOrder: idx };
                });
            }
        });

        this.currentList.onListLoad = function(d) { self.onFavoriteListLoad(d); };
        this.currentList.HandleSaveListSuccess = function(d) { self.HandleSaveListSuccess(d.d); };
    },

    buildUidLookup: function(users) {
        this.lookup = {};
        var self = this;

        $.each(users, function(i, v) {
            self.lookup[v.uid] = v;
        });
    },

    userHasPic: function(u) {
        if (typeof (u.pic) === "object" || u.pic === "") {
            u.pic_square = u.pic = "/static/images/person-place-holder-100x100.png";
            return false;
        }
        return true;
    },

    run: function() {
        var self = this;

        //$('#friends-title').html(self.LIST_TITLE);
        //$('#textbox-name-list').val(self.LIST_TITLE);
        var data = self.xmlText;

        $("#friend-list").block({
            css: { border: 'none', backgroundColor: 'transparent' },
            overlayCSS: { backgroundColor: '#FFFFFF' },
            message: '<img src="/static/images/icon-wait-30x30.png" class="wait" />'
        });

        var UserArray = $.makeArray(data.user);

        console.log(UserArray.length);

        var renderUser = function(i, val) {
            //check here if val.imageurl is null use the no pic image            
            self.userHasPic(val);
            //if(val.current_location.city.length > 10)

            this.city = val.current_location.city || "none";
            this.state = val.current_location.state || "";

            var li = $(self.DEFAULT_ITEM_TEMPLATE.apply(this))[0];
            li.selectedData = val;
            //console.log(val, 'val is');
            li.selectedData.faceBookUserId = val.uid;
            $('#twenty ul').append(li);
            if (typeof ($("ul.items li[userid='" + val.uid + "']")[0]) != "undefined") {                
                $("#twenty ul li[uid='" + val.uid + "']").addClass("selectedFriend");
            }
        };

        UserArray.sort(function alpha(a, b) {
            var A = a.first_name.toUpperCase();
            var B = b.first_name.toUpperCase();
            if (A < B) { return -1; }
            else if (A > B) { return 1; }
            else { return 0; }
        });

        this.buildUidLookup(UserArray);

        if (UserArray.length >= self.MIN_TO_PROCEED) {
            this.loadList();

            var pageSize = 20;

            $('#list-pager').pagination(UserArray.length, {
                items_per_page: pageSize,
                callback: function handlePageClick(pg) {
                    $('#twenty ul').empty();
                    var start = pg * pageSize;
                    var end = pageSize * (pg + 1);
                    console.log("paging", start, end);
                    $.each(UserArray.slice(start, end), renderUser);
                    return false;
                }
            });

            //autocomplete
            this.wireUpAutoCompleter();

            $('#twenty ul li').livequery('click', function(e) {
                self.selectFriend(e);
            });
            $(self.DELETE_ITEM_LINK).livequery('click', function(e) {
                if (self.RunDeletion(e)) {
                    self.deleteItem(e);

                    //reorder empty item.
                    if (self.generateListItems) {
                        console.log('reorder');
                        self.currentList.reorderList();
                        self.removeAfter();
                    }
                }
                return false;
                //console.log(ct, "remove this item from the list and de highlight the name fromt he twenty ul li");
                //Need to check for 2 peopel when I add them, and also check for dupes.
            });

            $(".friend.selectedFriend a").livequery('click', function(e) {
                var uid = $(e.currentTarget).closest("li").attr("uid");

                $.each($(self.filledExpression), function(i, v) {
                    //console.log(arguments);
                    if (uid === $(v).attr('userid')) {

                        var selectedData = $(v).closest("li")[0].selectedData;

                        var item = $(v).closest("li");
                        selectedData.Number = selectedData.number;
                        self.deleteAndDeRenderItem(selectedData, item);
                        if (self.generateListItems) {
                            console.log('reorder');
                            self.currentList.reorderList();
                            self.removeAfter();
                        }
                    }
                });
                //get users id and then go to friends selected side and remove them from there using self.deleteitem code
                //then undo the selected code for the main 20 box.
                //                if (self.RunDeletion(e)) {
                //                    self.deleteItem(e);
                //                }
                return false;
                //console.log(ct, "remove this item from the list and de highlight the name from the twenty ul li");
                //Need to check for 2 people when I add them, and also check for dupes.
            });

            //            console.log('enabled list sort friends');
            self.enableListSort();

            if (self.getCurrentCount() < self.MIN_TO_PROCEED) {
                $("#top-places-link a").attr("href", "#");
                $("#top-things-link a").attr("href", "#");
                //display message that you must first finish things.
            }
            $(self.SAVE_BTN).bind("click", function(e) {

                if (self.getCurrentCount() >= self.MIN_TO_PROCEED) {
                    //self.SendInvites();                    
                    window.location = "/home/favoriteplaces";
                    return false;
                }
            });

            Linfo.FlowControl.updateProgressMessaging('people', 0);
        }
        else {

            $("#friend-list #twenty ul").append("<li><h3>Sorry you do not have enough friends to use this website. Please add more and try again later.</h3></li>");
            //alert("not enough friends");
        }
        $('#friend-list').unblock();
        $(window).bind("beforeunload", function(e) {
            if (self.RunListLoad) {
                self.saveFriendList();
            }
        });

    },
    deleteItem: function(e) {
        var self = this;
        var ct = $(e.currentTarget)[0];
        var closeLI = $(ct).closest("li")[0];
        var data = closeLI.selectedData;

        //delete testdata;
        //delete $(ct).closest("li")[0].selectedData;
        data.Number = data.number;
        self.deleteAndDeRenderItem(data, ct);
    },
    deleteAndDeRenderItem: function(data, item) {
        var self = this;
        $(item).closest("li").html(self.DEFAULT_SIDE_ITEM_EMPTY_TEMPLATE.apply(data)).removeClass('filled').addClass('empty');
        $("#twenty ul li[uid='" + data.uid + "']").removeClass("selectedFriend");
        self.CheckNumToGo(self.getCurrentCount());

        self.deRenderListItem(data.number);
    },

    deRenderListItem: function(index) {
        index = index - 1;
        var self = this;
        var Count = $(self.filledExpression).length;
        if (this.generateListItems) {
            var item = this.getItemAt(index);

            console.log("removed", $(item));
            $(item).remove();
        }
        //this.removeAfter();
        $(self.CompletedCount).html(Count);
        return false;

    },
    getItemAt: function(index) {
        var self = this;
        console.log('getItemAt index', index);
        var itemSelectorString = self.SORTABLE_SELECTOR + " li:eq(" + index + ")";
        //        console.log(itemSelectorString);
        return $(itemSelectorString)[0];
    },
    getFilledItemCount: function() {
        return this.getCurrentCount();
    },
    getCurrentCount: function() {
        return $(this.SORTABLE_SELECTOR).children("li.filled").length;
    },
    selectFriend: function(e) {
        var self = this;
        var ct = $(e.currentTarget)[0];
        var listElement = self.getNextListElement();


        ct.selectedData.number = parseInt($(self.nextUnselectedExpression + ":first span").html(), 10);
        //console.log(ct.selectedData, 'selected data');
        //check for if the list has 20 in it already
        //check to see if ct.selectedData.uid is already in the list
        var Count = self.getCurrentCount();
        if (Count < self.MAX_FRIEND_COUNT) {
            if (!$("#twenty ul li[uid='" + ct.selectedData.uid + "']").hasClass("selectedFriend")) {
                listElement = self.getNextListElement();
                self.renderListItem(listElement, ct.selectedData);
                //Count = $("#favorite-friends ul").children("li.filled").length;
            }
        }
        self.CheckNumToGo(++Count);
    },
    enableListSort: function() {
        var self = this;
        $(this.SORTABLE_SELECTOR).sortable({
            cursor: 'pointer',
            update: function() { self.currentList.reorderList(); },
            cancel: self.nextUnselectedExpression
        }).disableSelection();
    },
    SendInvites: function() {
        $.ajax({
            type: "POST",
            url: "/services/FriendsService.asmx/InviteFriends",
            data: $.toJSON({
                EmailList: $("#emailArea").val()
            }),
            contentType: "application/json; charset=utf-8",
            cache: false,
            dataType: "json",
            success: function() {
            }
        });
    },
    loadList: function() {
        var self = this;

        if (self.RunListLoad) {
            this.currentList.loadList();
        }
    },

    CheckNumToGo: function(NumSelected) {
        if (NumSelected < this.MIN_TO_PROCEED) {
            var numToGo = this.MIN_TO_PROCEED - (NumSelected);
            $(".btn-next").html("You have " + numToGo + " more to go. You are almost done.");
        }
        else if (NumSelected > this.MAX_FRIEND_COUNT) {
            $(".btn-next").html("You have " + this.MAX_FRIEND_COUNT + " friends already. Next");
        }
        else {
            Linfo.FlowControl.handleListCompletion('people');
            $(".btn-next").html("Next");
        }

        Linfo.FlowControl.updateProgressMessaging('people', NumSelected);

        return false;
    },
    onFavoriteListLoad: function(d) {
        var self = this;

        $.each(d.d, function(index, item) {
            var selectedData = {};
            item = item.Value;
            selectedData.uid = item.FacebookId;
            selectedData.first_name = item.FirstName;
            selectedData.last_name = item.LastName;
            selectedData.city = item.City;
            selectedData.state = item.State;
            selectedData.name = item.FirstName + ' ' + item.LastName;
            selectedData.number = index + 1;
            selectedData.UserId = item.UserId;
            selectedData.faceBookUserId = item.FacebookId;

            var fbUser = self.lookup[item.FacebookId];

            if (self.userHasPic(fbUser)) {
                selectedData.pic_square = fbUser.pic_square.replace("/s", "/q");
            } else {
                selectedData.pic_square = fbUser.pic_square;
            }

            var listElement = self.getNextListElement();

            self.renderListItem(listElement, selectedData);
        });
    },
    saveFriendList: function() {
        var self = this;
        var FriendList = $.map($(self.filledExpression), function(item, idx) {
            return {
                FacebookId: item.selectedData.uid,
                FirstName: item.selectedData.first_name,
                LastName: item.selectedData.last_name,
                DisplayName: item.selectedData.first_name,
                City: item.selectedData.city,
                State: item.selectedData.state,
                DefaultImageUri: item.selectedData.pic_square
            };
        });
        console.log(FriendList);
        Linfo.A({
            url: this.SAVE_FAVORITE_FRIEND_LIST_URL,
            data: $.toJSON({

                friendList: FriendList, listName: "20 Favorite People", path: "/lists/twentyfriends"
            }),
            contentType: "application/json; charset=utf-8",
            cache: false,
            maskEl: '#added-people',
            success: function(ListId) {

                //                console.log(ListId);
                //                $.each(msg.d, function(index, item) {
                //                    console.log($('li[uid="' + item.FacebookId + '"]')[0].selectedData);
                //                    $('li[uid="' + item.FacebookId + '"]')[0].selectedData.UserId = item.UserId;
                //                });
                //self.currentList.saveList();

                //give the user an option to change the list title or just go to the next page.
                //$("#continue-options").show();
                $("#edit-title a").bind("click", function(e) {
                    $("#content-main div#default-inputs").hide();
                    $("#content-main div#inputs").show();
                    $(".btn-85x35").bind("click", function(e) { self.UpdateList(); });


                    //show title change box
                });
            },
            error: function(msg) { }
        });
    },
    UpdateList: function() {
        var self = this;
        //        console.log("updatelist");
        Linfo.A({
            url: "/services/listservice.asmx/UpdateListTitle",
            data: $.toJSON({

                listid: self.LIST_ID, title: $("#textbox-name-list").val()
            }),
            contentType: "application/json; charset=utf-8",
            cache: false,
            //maskEl: '#added-people',
            success: function(msg) {
                //                console.log(msg);
                $('#friends-title').html(msg.d);
            },
            error: function(msg) { }
        });
    },
    HandleSaveListSuccess: function(response) { var self = this; self.LIST_ID = response; },
    getCurrentCount: function() {
        return $(this.filledExpression).length;
    },

    getNextListElement: function() {

        return $(this.nextUnselectedExpression)[0];
    },

    getClosestItem: function(e) {

    },
    getItemDisplayHtml: function(selectedData) {
        var self = this;
        /* TWENTY_APPEARANCE */
        if (self.LIST_TITLE !== "20 Favorite Friends" && typeof (selectedData.faceBookUserId) === "undefined") {
            //apply the things template
            return this.THING_ITEM_TEMPLATE.apply(selectedData);
        }
        else {
            //apply regular friend template
            //console.log("selectedData", selectedData);
            //console.log("regular template");
            return this.DEFAULT_SIDE_ITEM_TEMPLATE.apply(selectedData);
        }

    },
    /*getItemDisplayHtml: function(selectedData) {
    if ($("#friends-list ul > li.empty .count")[0]) {
    selectedData.Number = $("#friends-list ul > li.empty .count")[0].innerHTML;
    }
    return this.FAVORITE_PEOPLE_EMPTY_SIDE_ITEM.apply(selectedData);
    },*/
    renderListItem: function(element, data) {
        //        console.log("render list item inside fav people controller");
        var self = this;
        //console.log('args', arguments);
        data.faceBookUserId = data.uid;
        element.selectedData = data;
        $(element).html(
            this.getItemDisplayHtml(data)
            ).removeClass('empty').addClass('filled');
        $(element).attr("userid", data.uid);
        $("#twenty ul li[uid='" + data.uid + "']").addClass("selectedFriend");
        var Count = self.getCurrentCount();
        if (Count < self.MIN_TO_PROCEED) {
            $("#top-places-link a").attr("href", "#");
            $("#top-things-link a").attr("href", "#");
            //display message that you must first finish things.
        }
        else { $("#top-places-link a").attr("href", "/home/favoriteplaces"); }
        $('#peoplecompletedcount').html(Count);
        var tempData = { number: data.number };
        tempData.number = data.number + 1;
        //$("#content-sub #bucket ul.items").append(self.DEFAULT_SIDE_ITEM_EMPTY_TEMPLATE.apply(tempData));
    },
    DropDownSelect: function(e, selectedData, name) {

        var self = this;

        var listElement = self.getNextListElement();
        selectedData.number = $(self.selectExpression + " li.empty:first span").html();

        //"#friends-list ul "
        //check for if the list has 20 in it already
        //check to see if ct.selectedData.uid is already in the list
        var Count = self.getCurrentCount();

        if (Count < self.MAX_FRIEND_COUNT) {
            if (!$("#twenty ul li[uid='" + selectedData.uid + "']").hasClass("selectedFriend")) {
                listElement = self.getNextListElement();
                self.renderListItem(listElement, selectedData);
                //Count = $("#favorite-friends ul").children("li.filled").length;
                console.log("rendered listelement");
            }
        }

        self.CheckNumToGo(++Count);
    },
    wireUpAutoCompleter: function() {
        var self = this;

        this.locationCompleter = new Linfo.FriendSearchAutoComplete(self.autoCompleterElement, self.xmlText, {
            handleResult: function(event, selectedData, name) { console.log(arguments, "results"); self.DropDownSelect(event, selectedData, name); }
        });
        $(self.autoCompleterElement).click(function() { $(this).val(''); });
    }
});﻿/*global $ Linfo window google console location*/
Linfo.ShareController = $.klass({
    initialize: function(config) {
        var self = this;
        this.placesIconsSelector = '#places-list ul.items > li';
        this.thingsIconsSelector = '#things-list ul.items > li';
        this.personIconsSelector = '#people-list ul.items > li';
        this.IsOwner = false;
        $.extend(this, config);

        this.initPlacesDataStore();
        this.initThingsDataStore();
        this.initPersonDataStore();

        this.PopUp = new Linfo.ListingPopup({ IsOwner: self.IsOwner, TOP_OFFSET: 215, itemSelector: "#places-list .content .items li" });
        this.ThingMiniPop = new Linfo.MiniThingPopUp();
        //this.PersonMiniPop = new Linfo.MiniPersonPopUp();


        if (this.IsOwner) {
            //this.ThingPopUp = new Linfo.ListingPopup({ TOP_OFFSET: 215,itemSelctor:"#things-list .content .items li"  });
            //this.ThingPopUp.emitMarkup(this.thingsIconsSelector);
            google.setOnLoadCallback(function(l) {
                self.PopUp.gSearchOnLoad(l);

                //need to fix two on one page pop ups
                //self.ThingPopUp.gSearchOnLoad(l); 

            });
            this.PopUp.emitMarkup('li#places-list ul.items li');
            $('li#places-list ul.items li').livequery("click", function(e) {
                self.PopUp.show(e, $(e.currentTarget)[0].selectedData);
                $(".tab-note").show(); $(".tab-note").addClass('open');
            });
            //            $(this.thingsIconsSelector).livequery("click", function(e) {
            //                self.ThingPopUp.show(e, $(e.currentTarget)[0].selectedData);
            //                $(".tab-note").hide(); $(".tab-note").removeClass('open');
            //            });
        }
        else {
            this.MiniPopUp = new Linfo.MiniLocationPopUp({ DEFAULT_ITEM_SELECTOR: "#places-list .content ul.items li" });
            this.MiniPopUp.wireUp();
            $("li#places-list ul.items").addClass("non-owner");
            $('li#places-list ul.items li').livequery("click", function(e) {
                window.location = '/place/' + encodeURIComponent($(e.currentTarget)[0].selectedData.Name.replace(/&/g, '-')) + '/' + $(e.currentTarget)[0].selectedData.LinfoId;
            });

            $('.controls .btn-save').hide();
        }

        this.ThingMiniPop.wireUp(this.thingsIconsSelector);
        //this.PersonMiniPop.wireUp(this.personIconsSelector);

        this.prepareTwitter();

        Linfo.FlowControl.initShare();

        this.populateNewUserOverlay();
    },

    prepareTwitter: function() {
        console.log('IsOwner', this.IsOwner);

        if (!this.IsOwner) {
            $('#tweet-this').hide();
        }
        else {
            if (this.twitterAuthUrl.length !== 0) {
                $('#twc_connect,#twitter_authorization').show();
                $('#tweet-text-area,#twitter').hide();
            } else {
                $('#twc_connect,#twitter_authorization').hide();
                $('#tweet-text-area,#twitter').show();
            }
        }
        $('#tweet-this-link').click(function() {
            $('#tweet-text-area').toggle(); return false;
        });
        $('#tweet-this-button-close').click(function() {
            $('#tweet-text-area').hide(); return false;
        });

        $('#btn-share').click(function() {
            $.ajax({
                type: "POST",
                url: "/Services/TwitterService.asmx/StatusUpdate",
                data: $.toJSON({
                    message: $('#twitterMessage').val()
                }),
                contentType: "application/json; charset=utf-8",
                cache: false,
                dataType: "json",
                success: function() { }
            });
            $('#twitterMessage').val("");
            $('#tweet-text-area').hide();
        });

        $('#twitterMessage').keyup(function(i) {
            var max = 115;
            var val = $('#twitterMessage').val();
            var cur = 0;
            if (val) {
                cur = val.length;
            }
            var left = max - cur;
            $('#charcount').html(left);
            if (left <= 0) {
                $('#twitterMessage').val(val.substring(0, max));
            }

        });

        $('#tweet-auth-link').click(function() {
            console.log('twitterAuthUrl', window.controller.twitterAuthUrl);
            var sList = window.open(window.controller.twitterAuthUrl, "twcWindow", "width=800,height=400,left=150,top=100,scrollbar=no,resize=no");
            return false;
        });

        /*
        //var t = new Linfo.Twitter({});     
        //t.CreateStatusUpdateButton("twitter", Linfo.userOpts.userId, "#btn-share", "#twitterMessage");
        if (this.twitterAuthorizationLink.length > 0)
        {
        //t.CreateTwitterAuthButton('#twc_connect', Linfo.userOpts.userId, this.twitterAuthorizationLink);
        }
        else
        {
        $("#twc_connect").hide();
        }
        */
    },

    populateNewUserOverlay: function() {
        $('#TB_window').livequery('click', function() {
            location.href = '/home/login'; return false;
        });

        var tpl = $.template('<li><img src="${DefaultImageUri}" /><span class="count">${Number}</span></li>');

        $.each(this.dataStore.Places.slice(0, 5), function(i, v) {
            var sd = this.Value;

            $('#new-fb-user-overlay .top-5').append(tpl.apply($.extend(sd, { Number: i + 1 })));
        });
    },

    initPersonDataStore: function() {
        console.log('test');
        $.each(this.dataStore.People, function() {
            var data = this;
            $('li[fbook-id=' + this.Value.FacebookId + ']').each(function() {
                this.selectedData = data.Value;
            });
        });
    },

    initThingsDataStore: function() {
        $.each(this.dataStore.Things, function() {
            var data = this;
            var sel = data.Value.FreebaseID;
            if (sel !== null) {
                $('li[fb-id=' + sel + ']').each(function() {
                    this.selectedData = data.Value;
                });
            }
        });
    },

    initPlacesDataStore: function() {
        $.each(this.dataStore.Places, function() {
            var data = this;
            $('li[linfo-id=' + this.ItemId + ']').each(function() {
                this.selectedData = data.Value;
            });
        });
    }
});﻿/*global $ Linfo jQuery SWFUpload google location console GMap2 document GMapTypeControl GSmallMapControl locationInfo GEvent GClientGeocoder GLatLng GIcon G_DEFAULT_ICON GMarker GDirections*/

Linfo.PlaceListingController = $.klass({
    initialize: function(config) {
        this.ADD_NOTE_BUTTON = '#tab-notes';
        this.MAP_CONTAINER = '#map-canvas';
        this.locationElement = '#textbox-location';
        this.autoCompleterElement = '#textbox-what';
        this.ADD_NOTE_SERVICE = "/services/Listservice.asmx/AddNote";
        this.NEAR_BY_PLACES_SERVICE = "/services/SearchService.asmx/NearByPlaces";

        $.extend(this, config);

        Linfo.FlowControl.initListing();
    },

    handleSearchResultSelect: function(ac, d) {
        if (d.Id !== '') {
            location.href = '/place/id/' + d.Id;
        }
    },

    run: function() {
        var self = this;
        google.setOnLoadCallback(function(l) { self.listingPop.gSearchOnLoad(l); });
        this.wireUpCityCompleter();
        this.wireUpAutoCompleter();
        this.wireUpExpandos();
        this.getNearByPlaces();

        $('.btn-close').bind("click", function(e) { self.hideNotePanel(); return false; });
        $('.btn-share').livequery("click", function(e) {
            self.handleShareNote();
        });
        $('.btn-go').bind("click", function(e) {
            self.initDrivingDirectionMap();
            return false;
        });


        $('#AddPhoto').bind("click", function(e) {
            var data = {};
            Linfo.A({
                url: "/services/ListService.asmx/CreateFavoritePlace",
                data: $.toJSON({ linfoid: self.LINFOID }),
                success: function(d) {
                    data = d.d;
                    self.listingPop.search(data.Name);
                    console.log(data);
                    self.listingPop.show(e, data);
                }
            });
        });


        $('#add-note').keyup(function(i) {
            var max = 115;
            var val = $('#add-note').val();
            var cur = 0;
            if (val) {
                cur = val.length;
            }
            var left = max - cur;
            if (left < 0) {
                $('#add-note').val(val.substring(0, max));
                left = 0;
            }
            $('#charcount').html(left);

        });
    },
    SWFUploadLoad: function() {
        //swfupload code        
        var self = this;
        var swfu;
        var settings_object = {
            upload_url: "/home/UploadDesktopImage",
            flash_url: "/static/flash/swfupload.swf",
            button_placeholder_id: "desktopSelector",
            button_placeholder: "get_flash",
            button_width: 150, button_height: 22,
            button_text: "<span class='upload'>UPLOAD FROM DESKTOP</span>",
            button_text_style: ".upload {color:#0088FF;textDecoration:underline;fontFamily:Arial,Helvetica,sans-serif;fontSize:14;leading:20;}",
            file_queued_handler: function() { self.SWFUploadExecute(swfu, self.LINFOID); },
            //file_queue_error_handler: function() { console.log('error handler'); },
            //file_dialog_complete_handler: function() { console.log('dialog handler'); },
            upload_start_handler: function() { },
            upload_success_handler: function(e, imgUrl) { self.SWFUpload_Sucess_Handler(e, imgUrl); },
            button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,
            button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
            file_size_limit: "2 MB"
        };
        swfu = new SWFUpload(settings_object);
        return swfu;
        //end code
    },
    SWFUpload_Sucess_Handler: function(e, imgUrl) {
        var self = this;
        self.emitUploadHtml(imgUrl);
    },

    SWFUploadExecute: function(swfu, linfoid) {
        var self = this;
        var caption = ($("#imagecaptionbox").val() === "Name or describe your photo") ? "" : $("#photo-caption").val();

        //swfu.settings.upload_url = "/home/UploadDesktopImage?imageCaption=" + $("#imagecaptionbox").val() + "&linfoid=" + linfoid;
        swfu.setUploadURL("/home/UploadDesktopImage?imageCaption=" + caption + "&linfoid=" + self.LINFOID);
        swfu.startUpload();
        //$("li.filled:eq(" + (self.CurrentIndex - 1) + ")").block({ message: 'Loading <br /><img src="/static/images/icon-wait-30x30.png" class="wait" />' });

    },
    handleUploadSuccess: function(response, imageCaption) {
        var self = this;
        console.log("upload success args", arguments);
        self.emitUploadHtml(response.d, imageCaption);
    },
    emitUploadHtml: function(imgUrl, imageCaption) {
        console.log(arguments);
        var htmlString = '<li><img src="' + imgUrl + '" title="' + imageCaption + '" /></li>';
        $('.gallery').append(htmlString);
        $("#photo-caption").val('');
    },
    handleShareNote: function() {

        var self = this;
        Linfo.A({
            url: this.ADD_NOTE_SERVICE,
            data: $.toJSON({ itemId: self.LINFOID, note: $("#add-note").val() }),
            success: function(d) {
                var count;

                if ($('.btn-edit').is('.active')) {
                    $('ul.items li p:first').html($("#add-note").val());
                    if ($("#add-note").val() === '') {
                        $('ul.items li:first').hide();
                        count = $('span.title .count').html();
                        $('span.title .count').html(--count);
                        $('.btn-add').show();
                        $('.btn-edit').hide();
                        $('.btn-edit').removeClass("active");
                    }


                }
                else {
                    console.log(d.d);
                    $("#notes .items").prepend('<li><a class="avatar" href="/user/' + d.d.FirstName + '/' + d.d.UserId + '"><img src="' + $("#user-info img").attr("src") + '" alt="" /></a><h5><a href="' + d.d.UserId + '">' + d.d.FirstName + '</a> says</h5><p>' + $("#add-note").val() + '</p></li>');
                    count = $('span.title .count').html();
                    $('span.title .count').html(++count);
                    $('.btn-edit').show();
                    $('.btn-add').hide();
                    $('.btn-edit').addClass("active");
                    $('ul.items li p:first').attr("id", "comment-owner");
                }
                self.hideNotePanel();
                $("#add-note").val('');
                $('#charcount').html('');
                return false;
            }
        });

    },
    hideNotePanel: function() {
        var self = this;
        $(self.ADD_NOTE_BUTTON).hide(); $(self.ADD_NOTE_BUTTON).removeClass('open');
    },
    createMap: function() {
        var self = this;
        $(self.MAP_CONTAINER).googlemap({
            addresses: [self.LOCATION_ADDRESS]
        });
    },

    wireUpExpandos: function() {
        var self = this;
        $('#notes .btn-add').click(function() {
            var panel = $(self.ADD_NOTE_BUTTON);
            if (!panel.is('.open')) {
                panel.show(); panel.addClass('open');
                $('#add-note').focus();
            }
        });

        $('#notes .btn-edit').click(function() {
            console.log(arguments);
            var panel = $(self.ADD_NOTE_BUTTON);
            if (!panel.is('.open')) {
                $('#add-note').val(jQuery.trim($('#comment-owner').html()));
                panel.show(); panel.addClass('open');

            }
        });
        return false;
    },

    renderNearByPlaces: function(places) {
        var self = this;

        $.each(places, function eachNearByPlace() {
            //console.log(this);
            this.Id = this.Id.replace('L_', '');
            console.log('NBP:', this.Id, self.LINFOID);
            //if (this.Id == self.LINFOID) return;

            if (this.DefaultImageUri === null) { this.DefaultImageUri = '/static/images/place-place-holder-48x48.png'; }
            if (this.Address === null) { this.Address = ""; }

            this.LinkName = Linfo.escapeName(this.Name);

            var tpl = $.template(['<li class="row"><ul>',
                        	    '<li class="item-icon"><img alt="Item icon" src="${DefaultImageUri}"/></li>',
                        	    '<li class="item-info">',
                            	    '<a class="item-title" href="/place/${LinkName}/${Id}">${Name}</a>',
                                    '<span class="details">${Address}</span>',
                                '</li>',
                            '</ul></li>'].join(''));

            $('#suggestions .container .items').append(tpl, this);
        });
    },

    getNearByPlaces: function() {
        var self = this;
        Linfo.A({
            url: this.NEAR_BY_PLACES_SERVICE,
            data: $.toJSON({ lat: self.lat, lng: self.lng, idToExclude: self.LINFOID }),
            success: function(d) {
                self.renderNearByPlaces(d.d);
            }
        });
    },

    initDrivingDirectionMap: function() {
        $("#route").html("");

        var self = this;
        $("#gmapsBig").css("display", "block");
        var from = $("#fromDirections").val();
        var destination = $(".address").html();

        var directions_str = from + " to " + destination;

        var map = new GMap2(document.getElementById("route-map"));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());

        var directionsPanel = document.getElementById("route");
        var directions = new GDirections(map, directionsPanel);
        directions.load(directions_str);
        GEvent.addListener(directions, "error", function() { self.handleErrors(); });
    },
    handleErrors: function() {
        var self = this;

        //if (directions.getStatus().code != 200) {
        //If an invalid address is entered by the user
        //        console.log("Invalid address. Please try again.");
        var mapWithoutDirections = new GMap2(document.getElementById("route-map"));
        var geocoder = new GClientGeocoder();

        //console.log($(".address").html());
        geocoder.getLocations($(".address").html(), function(e) { mapWithoutDirections = self.centerMap(e, mapWithoutDirections); });
        mapWithoutDirections.addControl(new GSmallMapControl());
        //        $('#gmapsBig').googlemap({
        //            addresses: [self.LOCATION_ADDRESS]
        //        });
        //   }
        $("#route").html('<span class="error">Please check your starting address for errors.</span>');
    },
    centerMap: function(response, mapWithoutDirections) {
        var place = response.Placemark[0];
        // Retrieve the latitude and longitude
        var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
        mapWithoutDirections.setCenter(point, 13);

        // Create our "tiny" marker icon
        var blueIcon = new GIcon(G_DEFAULT_ICON);
        blueIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png";
        var markerOptions = { icon: blueIcon };
        mapWithoutDirections.addOverlay(new GMarker(point), markerOptions);
        //document.getElementById("addressMessage").innerHTML = "";
        return mapWithoutDirections;
    },

    wireUpAutoCompleter: function() {
        var self = this;
        self.displayingDefaultPlaceText = true;
        $('#textbox-what').click(function() {
            if (self.displayingDefaultPlaceText) {
                $(this).val('');
            }
            self.displayingDefaultPlaceText = false;
        });

        this.locationCompleter = new Linfo.LocationSearchAutoComplete(this.autoCompleterElement, {
            handleResult: function(i, d, v) { self.handleSearchResultSelect(i, d, v); },
            disableNoResults: false
        });

        self.locationCompleter.lat = locationInfo.lat;
        self.locationCompleter.lng = locationInfo.lng;
    },
    wireUpCityCompleter: function() {
        var self = this;

        this.cityLocationCompleter = new Linfo.LinfoCityAutoComplete(this.locationElement, {
            handleResult: function(i, d, v) {
                $(self.locationElement).val(d.Location);
                self.locationCompleter.lat = d.Lat;
                self.locationCompleter.lng = d.Lng;
                Linfo.setLocationCookie(d);
            }
        });


    }
});﻿/*global Linfo $ */
Linfo.ListEditor = $.klass(Linfo.FavoriteThingsController, {
    initialize: function($super) {
        $super({

        });
    }
});