var geograffiti = geograffiti || {};
geograffiti.log = function(message){
    if (geograffiti.debugging) {
        console.log(message, arguments)
    }
};
geograffiti.debug = function(message){
    if (geograffiti.debugging) {
        console.debug(message, arguments)
    }
};
geograffiti.info = function(message){
    if (geograffiti.debugging) {
        console.info(message, arguments)
    }
};
geograffiti.warn = function(message){
    if (geograffiti.debugging) {
        console.warn(message, arguments)
    }
};
geograffiti.error = function(message){
    if (geograffiti.debugging) {
        console.error(message, arguments)
    }
};
geograffiti.EmptyFunction = function(){
};
geograffiti.Environment = {
    ServerRunningOn: "www.geograffiti.com",
    exportSelf: function(){
    },
    initialize: function(){
        var value = $F("serverRunningOn");
        if (value && value.length > 0) {
            this.ServerRunningOn = value
        }
        this.exportSelf()
    }
};
geograffiti.initializeDebugging = function(shouldDebug){
    geograffiti.debugging = shouldDebug;
    document.observe("dom:loaded", function(e){
        if (!shouldDebug) {
        }
        else {
            if (!window.console) {
                var firebugCommands = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "trace", "group", "groupEnd", "groupCollapsed", "time", "timeEnd", "profile", "profileEnd", "count", "clear", "notifyFirebug", "getFirebugElement", "firebug"];
                window.console = {};
                var command = null;
                for (var i = 0; i < firebugCommands.length; ++i) {
                    command = firebugCommands[i];
                    console[command] = geograffiti.EmptyFunction
                }
            }
        }
    })
};
geograffiti.MapEvent = {
    FilterSelected: "geograffiti:filterSelected",
    RepeatLastSearch: "geograffiti:repeatLastSearch",
    ViewProfileLinkClicked: "geograffiti:viewProfileLinkClicked",
    TagLinkClicked: "geograffiti:tagLinkClicked",
    UserVoiceMarksSearchRequested: "geograffiti:userVoiceMarksSearchRequested",
    SearchAllWithTagRequested: "geograffiti:searchAllWithTagRequested",
    ShowMyPhonesRequested: "geograffiti:showMyPhonesRequested"
};
geograffiti.UserEvent = {
    UserLoggedIn: "geograffiti:userLoggedIn",
    UserLoggedOut: "geograffiti:userLoggedOut",
    UserDidNotLogIn: "geograffiti:userDidNotLogIn"
};
geograffiti.SearchUsersControlEvent = {
    UserSelected: "geograffiti:searchUsersControlUserSelected"
};
geograffiti.ApiUrl = {
    ContentSearch: "/gu/VoiceMarkSearch.html?function=contentsearch",
    TagSearch: "/gu/VoiceMarkSearch.html?function=pagedsearch",
    RespondToVoiceMark: "/gu/RespondToVoiceMark.html",
    GetUserInfo: "/gu/GetUserInfo.html",
    GetVoiceMarkInfo: "/gu/GetVoiceMarkInfo.html",
    CreateVoiceMark: "/gu/CreateVoiceMark.html",
    GetResponses: "/gu/GetResponses.html",
    StreamVoiceMark: "/geogstreamer/GetVoiceMark",
    FilterSearch: "/gu/VoiceMarkSearch.html?function=pagedsearch",
    AddTags: "/gu/AddTags.html",
    GetVoiceMarkCategories: "/gu/GetCategories.html?entityType=0",
    GetVoiceMarkSubCategories: "/gu/GetSubCategories.html?entityType=0",
    SetVoiceMarkCategory: "/gu/SetCategory.html",
    GetVoiceMarkCategory: "/gu/GetVoiceMarkCategory.html",
    GetVoiceMarkTags: "/gu/GetVoiceMarkTags.html",
    UserLoggedIn: "/gu/IsSessionAlive.html",
    GetAccountData: "/gu/GetAccountData.html",
    GetProfilePic: "/gu/GetProfilePic.html",
    UploadProfilePic: "/gu/UploadProfilePic.html",
    SetPreference: "/gu/SetPreference.html",
    BecomeFan: "/gu/Subscribe.html",
    GetGroups: "/gu/GetGroups.html",
    JoinGroup: "/gu/JoinGroup.html",
    LeaveGroup: "/gu/LeaveGroup.html",
    CreateGroup: "/gu/CreateGroup.html",
    GetGroupInfo: "/gu/GetGroupInfo.html",
    AddPhoneNumber: "/gu/AddPhoneNumber.html",
    DeletePhoneNumber: "/gu/DeletePhoneNumber.html",
    VerifyPhoneNumber: "/gu/SendVerificationCall.html",
    VerifyVerificationCallCode: "/gu/VerifyVerificationCallCode.html",
    SetNotificationPreferences: "/gu/SetNotificationPreferences.html",
    DeleteVoiceMark: "/gu/DeleteVoiceMark.html",
    DeleteSubscription: "/gu/DeleteSubscription.html",
    GetUserVoiceMarks: "/gu/GetUserVoiceMarks.html",
    RateVoiceMark: "/gu/RateVoiceMark.html",
    Logout: "/gu/LogOut.html",
    SearchForUser: "/gu/SearchForUser.html",
    SetPhoneCarrier: "/gu/SetPhoneCarrier.html",
    SetPhoneHandset: "/gu/SetPhoneHandset.html",
    GetGroupVoiceMarks: "/gu/GetGroupVoiceMarks.html",
    GetMySystemUserId: "/gu/GetMySystemUserId.html",
    GetMyPhoneNumber: "/gu/GetMyPhoneNumber.html",
    SendVoiceMarkToPhone: "/gu/SendVoiceMarkToPhone.html",
    HasVerifiedNumber: "/gu/HasVerifiedNumber.html",
    EnableTwitter: "/gu/UpdateTwitterPreferences.html",
    UpdateTwitterPreferences: "/gu/UpdateTwitterPreferences.html",
    GetTwitterPreferences: "/gu/GetTwitterPreferences.html",
    UploadVoiceMark: "/gu/UploadVoiceMark.html",
    
    initialize: function(){
    }
};
geograffiti.SEOFriendlyUrl = {
    ViewVoiceMark: "/voicemarks",
    ViewTag: "/tags",
    ViewUser: "/users",
    ViewAnonymousUser: "/anonymous-users",
    ViewGroupMap: "/map/group",
    initialize: function(){
    }
};
geograffiti.AudioPlayerDefaults = {
    remaining: "yes",
    initialvolume: 100,
    buffer: 2,
    width: "100%",
    bg: "0xcccccc",
    leftbg: "0xeeeeee",
    lefticon: "0x648bee",
    voltrack: "0xffffff",
    volslider: "0x648bee",
    rightbg: "0xcccccc",
    rightbghover: "0xeeeeee",
    righticon: "0x666666",
    righticonhover: "0x648bee",
    loader: "0xf2f723",
    track: "0xffffff",
    tracker: "0xeddd80",
    border: "0xcccccc",
    skip: "0xeddd0",
    text: "0x666666",
    transparentpagebg: "yes"
};

geograffiti.Art = {
    VoiceMarkResultIcon: "/images/voicemark-23x33.png",
    VoiceMarkIcon: "/images/voicemark.png",
	BizMarkResultIcon : "/images/bizmark-23x33.png",
    
    initialize: function(){
        try {
            var voiceMarkResultIcon = $F("voiceMarkResultIcon");
            // change server side to /images/voicemark-23x33.png
            //if (voiceMarkResultIcon && voiceMarkResultIcon.length > 0) {
            //	this.VoiceMarkResultIcon = voiceMarkResultIcon;
            //}
            
            var voiceMarkIcon = $F("voiceMarkIcon");
            if (voiceMarkIcon && voiceMarkIcon.length > 0) {
                this.VoiceMarkIcon = voiceMarkIcon;
            }
        } 
        catch (e) {
            gg.warn(e);
        }
    }
}

geograffiti.loadCallback = null;
geograffiti.getMySystemUserId = function(){
    var request = new Ajax.Request(gg.ApiUrl.GetMySystemUserId, {
        asynchronous: false
    });
    var response = request.transport.responseText.evalJSON(true);
    var id = null;
    if (response) {
        if (typeof response.id !== "undefined") {
            id = response.id;
        }
    }
    return id
};
geograffiti.getMyPhoneNumber = function(){
    var request = new Ajax.Request(gg.ApiUrl.GetMyPhoneNumber, {
        asynchronous: false
    });
    var response = request.transport.responseText.evalJSON(true);
    var phone = null;
    if (response) {
        if (typeof response.phone !== "undefined") {
            phone = response.phone;
        }
    }
    return phone;
};
geograffiti.userHasVerifiedNumber = function(){
    var hasVerifiedNumber = false;
    var request = new Ajax.Request(gg.ApiUrl.HasVerifiedNumber, {
        asynchronous: false
    });
    var response = request.transport.responseText.evalJSON(true);
    if (response && response.status === 0) {
        hasVerifiedNumber = true
    }
    return hasVerifiedNumber
};
geograffiti.require = function(library){
    geograffiti.libraries = geograffiti.libraries || $H();
    geograffiti.libraryIndicator = geograffiti.libraryIndicator || 0;
    geograffiti.libraries.set(library, false);
    $j.getScript(library, geograffiti.incrementIndicator)
};
geograffiti.incrementIndicator = function(){
    geograffiti.libraryIndicator++
};
geograffiti.intervalId = null;
geograffiti.loadCallbackLoop = function(){
    if (geograffiti.libraries.size() === geograffiti.libraryIndicator) {
        clearInterval(geograffiti.intervalId);
        geograffiti.libraries.each(function(pair){
            geograffiti.libraries.unset(pair.key)
        });
        geograffiti.libraryIndicator = 0;
        this.loadCallback()
    }
};
geograffiti.setOnLoadCallback = function(callback){
    var self = this;
    self.loadCallback = callback;
    geograffiti.intervalId = setInterval("geograffiti.loadCallbackLoop()", 50)
};
geograffiti.exportSelf = function(){
    window.gg = window.geograffiti
};
geograffiti.loadLibraries = function(){
};

geograffiti.sendUserToRegister = function() {
		if (!geograffiti.loginInProgress) {
        gg.log("user wants to login ... no login progress...going through");
        geograffiti.loginInProgress = true;
        var executor = null;
        document.observe("lightview:hidden", function(e){
            try {
                gg.log("lightview has hidden!!!");
                e.stop();
                gg.log("going to stop the pe...%o", executor);
                if (executor) {
                    executor.stop()
                }
                geograffiti.stopObservingLightviewEvents(document);
                new Ajax.Request(gg.ApiUrl.UserLoggedIn, {
                    onSuccess: function(response){
                        var apiResponse = response.responseText.evalJSON(true);
                        if (apiResponse) {
                            if (!apiResponse.isSessionAlive) {
                                gg.log("session not alive so firing did not login");
                                document.fire(geograffiti.UserEvent.UserDidNotLogIn)
                            }
                            else {
                                gg.log("session is good so firing logged in");
                                document.fire(geograffiti.UserEvent.UserLoggedIn)
                            }
                        }
                        else {
                            gg.log("firing did not login b/c apiResponse was null");
                            document.fire(geograffiti.UserEvent.UserDidNotLogIn)
                        }
                    },
                    onFailure: function(response){
                        gg.log("ajax call failed...firing not logged in");
                        document.fire(geograffiti.UserEvent.UserDidNotLogIn)
                    },
                    onComplete: function(response){
                        geograffiti.loginInProgress = false;
                    },
                    onException: function(requester, e){
                        geograffiti.loginInProgress = false;
                    }
                });
            } 
            catch (e) {
                geograffiti.loginInProgress = false;
            }
        });
        
        document.observe("lightview:opened", function(e){
            gg.log("observed lightview:openend");
            e.stop();
            gg.log("starting executor");
            new PeriodicalExecuter(function(pe){
                gg.log("%o", pe);
                executor = pe;
                gg.log("executor now pe");
                try {
                    new Ajax.Request(gg.ApiUrl.UserLoggedIn, {
                        onSuccess: function(response){
                            var apiResponse = response.responseText.evalJSON(true);
                            gg.log("api response was %o", apiResponse);
                            if (apiResponse && apiResponse.isSessionAlive === true) {
                                gg.log("api response coo and session alive coo");
                                pe.stop();
                                gg.log("stopped pe");
                                Lightview.hide();
                                document.fire(geograffiti.UserEvent.UserLoggedIn)
                                gg.log("fired gg.Userevent.UserLoggedIn");
                            }
                            else {
                                gg.log("api response not coo or session not alive");
                                if (gg.debug) {
                                    gg.info("session check...session invalid %o", response)
                                }
                            }
                        },
                        onFailure: function(response){
                            gg.log("failure sending ajax call.....%o", response);
                            if (gg.debug) {
                                gg.warn("Can't check if session is alive!!! %o", response)
                            }
                        },
                        onComplete: function(response){
                            geograffiti.loginInProgress = false;
                            gg.log("complete....%o", response);
                        },
                        onException: function(requester, e){
                            gg.log("exception sending ajax call %o", e);
                            geograffiti.loginInProgress = false;
                        }
                    })
                } 
                catch (e) {
                    gg.log("exception caught...%o ... ", e);
                    geograffiti.loginInProgress = false;
                    if (gg.debug) {
                        gg.info("can't get access to content...must be on FB")
                    }
                }
            }, 1)
        });
        try {
            /*
             Lightview.show({
             href:'#login-form',
             rel:'inline',
             options: {
             width: 800,
             height: 450
             }
             });
             */
            Lightview.show({
                href: "/gu/userRegister.html", 
                options: {
                    width: 430,
                    height: 410,
                    menubar: false,
                    topclose: true
                }
            });
            
            //Lightview.show({
            //	href: String.format("https://$0/gu/loggedin.html", geograffiti.Environment.ServerRunningOn),
            //		rel: "iframe",
            //	options: {
            //		width: 800,
            //			height: 450
            //	}
            //});
        
        } 
        catch (e) {
            geograffiti.loginInProgress = false;
        }
    }

}

geograffiti.startRegisterLinkListener = function() {
	//document.observe("dom:loaded", function() {
		$("register-link").observe("click", function(e) {
			e.stop();
			geograffiti.sendUserToRegister();
		});
	//});
}

geograffiti.load = function(){
    document.observe("dom:loaded", function(){
        var viewport = $("viewport");
        if (viewport) {
            $("viewport").setStyle("visibility:visible");
        }
		geograffiti.startRegisterLinkListener();
    });
    this.exportSelf();
    if (typeof google != "undefined") {
        google.load("maps", "2");
        google.setOnLoadCallback(function(){
            window.$j = jQuery;
            geograffiti.loadLibraries();
            geograffiti.geograffitiLibrariesLoaded()
        });
    }
};
geograffiti.enableLoginLink = function(){
    var link = $("logout-login-link");
    link.removeClassName("logout");
    link.addClassName("login");
    link.update("Sign In")
};
geograffiti.enableLogoutLink = function(){
    var link = $("logout-login-link");
    link.removeClassName("login");
    link.addClassName("logout");
    link.update("Sign Out")
};
geograffiti.initialize = function(){
    geograffiti.Environment.initialize();
    geograffiti.ApiUrl.initialize();
    geograffiti.SEOFriendlyUrl.initialize();
    geograffiti.Art.initialize();
    //document.observe(geograffiti.UserEvent.UserLoggedIn, geograffiti.enableLogoutLink.bindAsEventListener(this));
    //document.observe(geograffiti.UserEvent.UserLoggedOut, geograffiti.enableLoginLink.bindAsEventListener(this));
    //$("logout-login-link").observe("click", function(e){
    //    var link = e.element();
    //    e.stop();
    //    if (link && link.hasClassName("logout")) {
    //        new Ajax.Request(geograffiti.ApiUrl.Logout, {
    //            onSuccess: function(transport){
    //                gg.log("Loggged Out!");
    //                document.fire(geograffiti.UserEvent.UserLoggedOut);
    //				gg.mySystemUserId = -1;
    //            },
    //            onFailure: function(transport){
    //                gg.error("Error logging out!")
    //            }
    //        })
    //    }
    //    else {
    //        geograffiti.userWantsToLogIn()
    //    }
    //});
    //try {
    //    var userInfoForm = $("userInformationForm");
    //    if (userInfoForm) {
    //        var userIdInput = userInfoForm.systemUserId;
    //        if (userIdInput) {
    //            var userId = parseInt($F(userIdInput));
    //            if (!isNaN(userId)) {
    //                geograffiti.enableLogoutLink()
    //            }
    //        }
    //    }
    //} 
    //catch (e) {
    //    gg.warn("geograffiti initialization...logout-login link %o", e)
    //}
};
geograffiti.pageControlsClicked = function(){
    alert("Page Controls!")
};
geograffiti.accountControlsClicked = function(){
    alert("Account Controls!")
};
geograffiti.initializeNavigationControls = function(){
    /*
     var searchUsersLink = $("nav-link-search-users");
     var searchUsersControlContent = '<div class="search-users-section"><label for="search-users-searchbox" class="search-users-label">Search by User Name</label><input id="search-users-searchbox" type="text" /><div id="search-users-auto-complete-results" class="autocomplete"></div></div><div class="search-users-section"><label for="search-users-by-name-searchbox" class="search-users-label">Search by First or Last Name</label><input id="search-users-by-name-searchbox" type="text" /><div id="search-users-by-name-auto-complete-results" class="autocomplete"></div></div>';
     new Tip(searchUsersLink, searchUsersControlContent, {
     title: "Search for Users",
     style: "geograffiti",
     showOn: "click",
     hideOn: false,
     hideAfter: 2,
     closeButton: true,
     hook: {
     target: "bottomMiddle",
     tip: "topRight"
     }
     });
     searchUsersLink.observe("prototip:shown", function(e){
     $("search-users-searchbox").up(".prototip").setStyle("overflow:visible");
     new Ajax.Autocompleter("search-users-searchbox", "search-users-auto-complete-results", gg.ApiUrl.SearchForUser, {
     paramName: "value",
     minChars: 2,
     parameters: "format=html&type=username",
     afterUpdateElement: function(inputElement, selectedElement){
     var systemUserId = selectedElement.identify();
     document.fire(gg.SearchUsersControlEvent.UserSelected, {
     id: systemUserId
     })
     }
     });
     new Ajax.Autocompleter("search-users-by-name-searchbox", "search-users-by-name-auto-complete-results", gg.ApiUrl.SearchForUser, {
     paramName: "value",
     minChars: 2,
     parameters: "format=html&type=name",
     afterUpdateElement: function(inputElement, selectedElement){
     var systemUserId = selectedElement.identify();
     document.fire(gg.SearchUsersControlEvent.UserSelected, {
     id: systemUserId
     })
     }
     })
     });
     var aboutLink = $("nav-link-about");
     var aboutControlContent = '<a href="/about.html" class="nav-link-target" target="_blank">About Us</a><a href="http://www.geograffiti.com/blog" class="nav-link-target" target="_blank">Blog</a><a href="/helpandfaq.html" class="nav-link-target" target="_blank">Help &amp; FAQ</a><a href="/apps/iphone.html" class="nav-link-target" target="_blank">iPhone App</a>';
     new Tip(aboutLink, aboutControlContent, {
     style: "geograffiti-menu",
     width: "auto",
     showOn: "click",
     hideOn: {
     element: "tip",
     event: "mouseout"
     },
     border: 2,
     radius: 2,
     hook: {
     target: "bottomLeft",
     tip: "topLeft"
     }
     });
     aboutLink.observe("prototip:shown", function(e){
     var navLinks = $$(".nav-link-target");
     if (navLinks) {
     navLinks.each(function(navLink){
     navLink.stopObserving();
     var mouseOverEvent = navLink.observe("mouseover", function(e){
     navLink.addClassName("nav-link-target-active")
     });
     var mouseOutEvent = navLink.observe("mouseout", function(e){
     navLink.removeClassName("nav-link-target-active")
     })
     })
     }
     });
     var contactLink = $("nav-link-contact");
     var contactControlContent = '<a href="/contact.html" class="nav-link-target" target="_blank">Contact Us</a><a href="" id="yaplet-support-link" class="nav-link-target" target="_blank">Live Support</a>';
     new Tip(contactLink, contactControlContent, {
     style: "geograffiti-menu",
     width: "auto",
     showOn: "click",
     hideOn: {
     element: "tip",
     event: "mouseout"
     },
     border: 2,
     radius: 2,
     hook: {
     target: "bottomLeft",
     tip: "topLeft"
     }
     });
     contactLink.observe("prototip:shown", function(e){
     var navLinks = $$(".nav-link-target");
     if (navLinks) {
     navLinks.each(function(navLink){
     navLink.stopObserving();
     navLink.observe("mouseover", function(e){
     navLink.addClassName("nav-link-target-active")
     });
     navLink.observe("mouseout", function(e){
     navLink.removeClassName("nav-link-target-active")
     })
     })
     }
     var yapletSupportLink = $("yaplet-support-link");
     yapletSupportLink.observe("click", function(e){
     e.stop();
     window.open(String.format("http://embed.yaplet.com/?antiswear=1&title=GeoGraffiti-Support&yapletlogo=http://$0/images/gglogo-tiny-26x33.png&channel=http://$1/map", geograffiti.Environment.ServerRunningOn, geograffiti.Environment.ServerRunningOn), "", "width=300,height=500,resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no")
     })
     })
     */
};
geograffiti.geograffitiLibrariesLoaded = function(){
    geograffiti.initialize();
    geograffiti.initializeNavigationControls();
    geograffiti.loadMapAndSideBar();
    geograffiti.mapFilterBar = new geograffiti.FilterBar("filterbar-container")
};
geograffiti.loadMapAndSideBar = function(){
    geograffiti.initializeSideBar();
    geograffiti.initializeMap()
};
geograffiti.initializeSideBar = function(){
    var sideBarHeight = $("viewport").getHeight() - $("toparea").getHeight() + 55;
    var sideBar = $("sidebar");
    geograffiti.SideBar.initialize("sidebar-tabs", "voicemarkmap", {
        height: sideBarHeight
    });
    sideBar.observe(geograffiti.SideBarEvent.SideBarExtended, this.sideBarExtended.bindAsEventListener(this.sideBarExtended));
    sideBar.observe(geograffiti.SideBarEvent.SideBarCollapsed, this.sideBarCollapsed.bindAsEventListener(this.sideBarCollapsed))
};
geograffiti.initializeMap = function(){
    var mapHeight = $("viewport").getHeight() - $("toparea").getHeight();
    var mapWidth = $("viewport").getWidth() - $("sidebarcontent").getWidth();
    geograffiti.map.load(function(){
        geograffiti.map.initialize({
            width: mapWidth,
            height: mapHeight
        })
    })
};
geograffiti.sideBarExtended = function(e){
    geograffiti.map.resized()
};
geograffiti.sideBarCollapsed = function(e){
    geograffiti.map.resized()
};
geograffiti.userLoggedIn = function(){
    var loggedIn = false;
    var ajax = new Ajax.Request(gg.ApiUrl.UserLoggedIn, {
        asynchronous: false
    });
    var response = ajax.transport.responseText.evalJSON(true);
    if (response) {
        if (response.isSessionAlive === true) {
            loggedIn = true
        }
    }
    return loggedIn
};
geograffiti.stopObservingLightviewEvents = function(element){
    gg.log("stopObservingLightviewEvents on %o", element);
    var target = $(element);
    if (target) {
        target.stopObserving("lightview:opened");
        target.stopObserving("lightview:hidden")
    }
};

geograffiti.loginInProgress = false;

geograffiti.userWantsToLogIn2 = function(){
    document.stopObserving("lightview:opened");
    document.observe("lightview:opened", function(event){
        $("login-box").setStyle("visibility:visible;display:block;");
    });
    Lightview.show({
        href: '#login-box'
    });
}

geograffiti.sendUserToFacebookRegister = function() { 
	if (!geograffiti.loginInProgress) {
        gg.log("user wants to login ... no login progress...going through");
        geograffiti.loginInProgress = true;
        var executor = null;
        document.observe("lightview:hidden", function(e){
            try {
                gg.log("lightview has hidden!!!");
                e.stop();
                gg.log("going to stop the pe...%o", executor);
                if (executor) {
                    executor.stop()
                }
                geograffiti.stopObservingLightviewEvents(document);
                new Ajax.Request(gg.ApiUrl.UserLoggedIn, {
                    onSuccess: function(response){
                        var apiResponse = response.responseText.evalJSON(true);
                        if (apiResponse) {
                            if (!apiResponse.isSessionAlive) {
                                gg.log("session not alive so firing did not login");
                                document.fire(geograffiti.UserEvent.UserDidNotLogIn)
                            }
                            else {
                                gg.log("session is good so firing logged in");
                                document.fire(geograffiti.UserEvent.UserLoggedIn)
                            }
                        }
                        else {
                            gg.log("firing did not login b/c apiResponse was null");
                            document.fire(geograffiti.UserEvent.UserDidNotLogIn)
                        }
                    },
                    onFailure: function(response){
                        gg.log("ajax call failed...firing not logged in");
                        document.fire(geograffiti.UserEvent.UserDidNotLogIn)
                    },
                    onComplete: function(response){
                        geograffiti.loginInProgress = false;
                    },
                    onException: function(requester, e){
                        geograffiti.loginInProgress = false;
                    }
                });
            } 
            catch (e) {
                geograffiti.loginInProgress = false;
            }
        });
        
        document.observe("lightview:opened", function(e){
            gg.log("observed lightview:openend");
            e.stop();
            gg.log("starting executor");
            new PeriodicalExecuter(function(pe){
                gg.log("%o", pe);
                executor = pe;
                gg.log("executor now pe");
                try {
                    new Ajax.Request(gg.ApiUrl.UserLoggedIn, {
                        onSuccess: function(response){
                            var apiResponse = response.responseText.evalJSON(true);
                            gg.log("api response was %o", apiResponse);
                            if (apiResponse && apiResponse.isSessionAlive === true) {
                                gg.log("api response coo and session alive coo");
                                pe.stop();
                                gg.log("stopped pe");
                                Lightview.hide();
                                document.fire(geograffiti.UserEvent.UserLoggedIn)
                                gg.log("fired gg.Userevent.UserLoggedIn");
                            }
                            else {
                                gg.log("api response not coo or session not alive");
                                if (gg.debug) {
                                    gg.info("session check...session invalid %o", response)
                                }
                            }
                        },
                        onFailure: function(response){
                            gg.log("failure sending ajax call.....%o", response);
                            if (gg.debug) {
                                gg.warn("Can't check if session is alive!!! %o", response)
                            }
                        },
                        onComplete: function(response){
                            geograffiti.loginInProgress = false;
                            gg.log("complete....%o", response);
                        },
                        onException: function(requester, e){
                            gg.log("exception sending ajax call %o", e);
                            geograffiti.loginInProgress = false;
                        }
                    })
                } 
                catch (e) {
                    gg.log("exception caught...%o ... ", e);
                    geograffiti.loginInProgress = false;
                    if (gg.debug) {
                        gg.info("can't get access to content...must be on FB")
                    }
                }
            }, 1)
        });
        try {
            /*
             Lightview.show({
             href:'#login-form',
             rel:'inline',
             options: {
             width: 800,
             height: 450
             }
             });
             */
            Lightview.show({
                href: "/gu/FacebookRegister.html", 
                options: {
                    width: 430,
                    height: 410,
                    menubar: false,
                    topclose: true
                }
            });
            
            //Lightview.show({
            //	href: String.format("https://$0/gu/loggedin.html", geograffiti.Environment.ServerRunningOn),
            //		rel: "iframe",
            //	options: {
            //		width: 800,
            //			height: 450
            //	}
            //});
        
        } 
        catch (e) {
            geograffiti.loginInProgress = false;
        }
    }
}

geograffiti.facebookInitialized = function(){
    FB.Event.subscribe("auth.sessionChange", function(response){
        gg.log("Session Chage!!!....%o", response);
        if (response.status === "connected") {
            new Ajax.Request("/gu/SignInWithFacebook.html", {
                onSuccess: function(response){
                    gg.log("Sign In Response: %o", response);
                    var apiResponse = response.responseText.evalJSON(true);
                    if (apiResponse.status === 0) {
                        document.fire(geograffiti.UserEvent.UserLoggedIn);
                        if ($("lightview").visible()) {
                            Lightview.hide();
                        }
                    }
					else if (apiResponse.status === 2) {
						gg.sendUserToFacebookRegister();
					}
                },
                onFailure: function(response){
                    gg.log("Sign In Failure: %o", response);
                }
            });
        }
    });
}

geograffiti.userWantsToLogIn = function() {
	geograffiti.userWantsToLogIn2();
}

geograffiti.userWantsToLogInOld = function(){
    if (!geograffiti.loginInProgress) {
        gg.log("user wants to login ... no login progress...going through");
        geograffiti.loginInProgress = true;
        var executor = null;
        document.observe("lightview:hidden", function(e){
            try {
                gg.log("lightview has hidden!!!");
                e.stop();
                gg.log("going to stop the pe...%o", executor);
                if (executor) {
                    executor.stop()
                }
                geograffiti.stopObservingLightviewEvents(document);
                new Ajax.Request(gg.ApiUrl.UserLoggedIn, {
                    onSuccess: function(response){
                        var apiResponse = response.responseText.evalJSON(true);
                        if (apiResponse) {
                            if (!apiResponse.isSessionAlive) {
                                gg.log("session not alive so firing did not login");
                                document.fire(geograffiti.UserEvent.UserDidNotLogIn)
                            }
                            else {
                                gg.log("session is good so firing logged in");
                                document.fire(geograffiti.UserEvent.UserLoggedIn)
                            }
                        }
                        else {
                            gg.log("firing did not login b/c apiResponse was null");
                            document.fire(geograffiti.UserEvent.UserDidNotLogIn)
                        }
                    },
                    onFailure: function(response){
                        gg.log("ajax call failed...firing not logged in");
                        document.fire(geograffiti.UserEvent.UserDidNotLogIn)
                    },
                    onComplete: function(response){
                        geograffiti.loginInProgress = false;
                    },
                    onException: function(requester, e){
                        geograffiti.loginInProgress = false;
                    }
                });
            } 
            catch (e) {
                geograffiti.loginInProgress = false;
            }
        });
        
        document.observe("lightview:opened", function(e){
            gg.log("observed lightview:openend");
            e.stop();
            gg.log("starting executor");
            new PeriodicalExecuter(function(pe){
                gg.log("%o", pe);
                executor = pe;
                gg.log("executor now pe");
                try {
                    new Ajax.Request(gg.ApiUrl.UserLoggedIn, {
                        onSuccess: function(response){
                            var apiResponse = response.responseText.evalJSON(true);
                            gg.log("api response was %o", apiResponse);
                            if (apiResponse && apiResponse.isSessionAlive === true) {
                                gg.log("api response coo and session alive coo");
                                pe.stop();
                                gg.log("stopped pe");
                                Lightview.hide();
                                document.fire(geograffiti.UserEvent.UserLoggedIn)
                                gg.log("fired gg.Userevent.UserLoggedIn");
                            }
                            else {
                                gg.log("api response not coo or session not alive");
                                if (gg.debug) {
                                    gg.info("session check...session invalid %o", response)
                                }
                            }
                        },
                        onFailure: function(response){
                            gg.log("failure sending ajax call.....%o", response);
                            if (gg.debug) {
                                gg.warn("Can't check if session is alive!!! %o", response)
                            }
                        },
                        onComplete: function(response){
                            geograffiti.loginInProgress = false;
                            gg.log("complete....%o", response);
                        },
                        onException: function(requester, e){
                            gg.log("exception sending ajax call %o", e);
                            geograffiti.loginInProgress = false;
                        }
                    })
                } 
                catch (e) {
                    gg.log("exception caught...%o ... ", e);
                    geograffiti.loginInProgress = false;
                    if (gg.debug) {
                        gg.info("can't get access to content...must be on FB")
                    }
                }
            }, 1)
        });
        try {
            /*
             Lightview.show({
             href:'#login-form',
             rel:'inline',
             options: {
             width: 800,
             height: 450
             }
             });
             */
            Lightview.show({
                href: String.format("https://$0/gu/loggedin.html", gg.Environment.ServerRunningOn),
                options: {
                    width: 430,
                    height: 410,
                    menubar: false,
                    topclose: true
                }
            });
            
            //Lightview.show({
            //	href: String.format("https://$0/gu/loggedin.html", geograffiti.Environment.ServerRunningOn),
            //		rel: "iframe",
            //	options: {
            //		width: 800,
            //			height: 450
            //	}
            //});
        
        } 
        catch (e) {
            geograffiti.loginInProgress = false;
        }
    }
};
geograffiti.textOrDefault = function(text, defaultText){
    return (!String.isNullOrEmpty(text) ? text : defaultText).escapeHTML()
};

