//This is our invite global namespace
var Invite = window.Invite || {};

Invite.Facebook = {

    gatherEmailModal:null,

    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    handleLogout: function (logoutUrl) {
		//Call FB logout if it's available.  Include a closure to call our logout url.
		if (FB && FB.Connect) {
			Invite.Misc.eraseCookie("fbLoginRefresh");
			FB.Connect.logout(function() {
				Invite.HeaderNav.logout(logoutUrl);
			});
		} else {
			Invite.HeaderNav.logout(logoutUrl);
		}

    },

    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    onFBUserConnected:function (serverFBLogged) {
    	
        //alert("onFBUserConnect: serverFBLogged=" + serverFBLogged + ", Invite.Misc.readCookie: " + Invite.Misc.readCookie("fbLoginRefresh") + ", doc.cookie: " + document.cookie);
        //This is the real check that stops the reloads
        if (serverFBLogged) {
            return;
        }

        // STOP REFRESHING
        // I DON'T THIS THIS SOVLES ANYTHING BECAUSE IF EVERYTHING IS WORKING RIGHT, THEN serverFBLogged SHORTCUTS.
        // IN CASE THAT FAILS...WELL THIS MAY HELP.
        // IF we're inside an IFRAME, then we're probably loaded inside of facebook's iframe (from a share)
        // in this case, don't bother to do FB connect because it reloads forever
        // but we can't get top.location from another domain, so if this fails, try to use cookies.
        try {
        	 // cross domain is illegal
	         if (top.location.href != window.location.href) {
	            // this can be the modal though...
	
	            // this is here because ....
	            if (top.location.href.indexOf("iggli.com") == -1 && top.location.href.indexOf("localhost") == -1)
	                return;
	        }
	        
	    } catch(err) {
	    	var num = Invite.Misc.readCookie("fbLoginRefresh");
	    	//this works for firefox and ie.  For safari, we have to open up a window to set cookies.
	    	if (num) {
	    		if (num > 1) {
	    			Invite.Misc.eraseCookie("fbLoginRefresh");
	    			return;
	    		} else {
	    			//we've already refreshed once.
	    			Invite.Misc.writeCookie("fbLoginRefresh", 2, null);
	    		}
	    	} else {
	    		Invite.Misc.writeCookie("fbLoginRefresh", 1, null);
	    	}
	    	
	    }
	    // END STOP REFRESHING.

        

        // if there IS a modal on the page, but it is not UP
        // if the modal JS exists

        // only need to hit iggli back end if iggli not logged in

        var loggedInFBUserId = FB.Connect.get_loggedInUser();

        //Invite.RegisterLogin.onSuccess = Invite.Facebook.doStaticFBLogin;

        //alert("FB.Facebook is " + FB.Facebook);

        try {

            FB.Facebook.apiClient.users_getInfo(loggedInFBUserId, ['first_name,last_name,uid,proxied_email,current_location,email_hashes,music,sex,pic'], function(result, ex) {
                // results arrive via this callback
                //window.alert(result[0].sex + " "  + result[0].first_name + " " + result[0].last_name + " " + result[0].uid + " " + result[0].proxied_email + " " + result[0].current_location.city + " " + result[0].current_location.country + " " + result[0].current_location.state + " " + result[0].current_location.zip + " " +  " ");
                var city;
                var country;
                var state;
                var zip;
                if (result[0].current_location != null) {
                    city = result[0].city;
                    country = result[0].country;
                    state = result[0].state;
                    zip = result[0].zip;
                }

                new Ajax.Request('/ajax/fb-user-connected.iggli', {
                    method:'post',
                    evalJSON: "force",
                    parameters:{
                        fbUserId:result[0].uid,
                        fbFirstName:result[0].first_name,
                        fbLastName:result[0].last_name,
                        fbProxyEmail:result[0].proxied_email,
                        fbCity:city,
                        fbCountry:country,
                        fbState:state,
                        fbZip:zip,
                        fbPicURL:result[0].pic,
                        fbMusic:result[0].music},

                    onSuccess:function(transport) {
                        //alert("Invite.Facebook.onFBUserConnected() -> Ajax.Request.onSuccess() called");
                        var json = transport.responseJSON;
                        Invite.Facebook.handleNewLogin(true);

                    },
                    onError:function() {
                        //alert("oops, we hit the error case");
                    },
                    onComplete:function() {
                        //alert("on complete case");

                    } // end on complete
                }); // end AJAX request

            }); // end facebook callback

        } catch (err) {
            //alert('caught exception');
            //alert(err);
        }
    },

    //-----------------------------------------------------------------------------
    // Christian, currently unused, but this can be called from onFBUserConnected
    //  dynamically update the page when the FB user logs in
    //
    //-----------------------------------------------------------------------------
    doDynamicFBLogin: function() {
        _USERID = json.elements.iggliUserId;


        // window.location = '/invite2/inviteId/' + _INVITE.invite.id + '/fbReload/true/';

        // this is three nested effects
        new Effect.Highlight('center-column-header-right', {duration: 0.2, afterFinish: function(obj) {
            new Effect.Fade('center-column-header-right', {duration: 1.5,
                afterFinish: function(obj) {
                    new Ajax.Updater('user-auth', '/ajax2/fb-get-auth-section.iggli', {
                        method:'get',
                        onComplete: function(transport) {
                        }
                    });

                    new Effect.Appear('center-column-header-right', {duration: 1.0});
                }}); // done fade effect
        }});
    },

    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    doFBRefresh: function() {
        //alert("Invite.Facebook.doStaticFBLogin() called.");
        // split the request on ? , 0 is main action, 1 is everything else
        var requestString = (window.location + '').split('?');
        //alert(requestString);
        // get the hash section too
        var hashPipe = ((window.location + '').split('#'));
        if (!hashPipe[1]) hashPipe = ""; //so the word undefined doesn't get into the hash.
        // make a hash out of the parms on the right, this might beempty
        var paramsHash = new Hash();
        if (requestString[1]) {
            paramsHash = $H(requestString[1].toQueryParams());
        }
        //if we've already refreshed, we don't do it again.
        if (paramsHash.get("fbReload")) return;
        //alert(paramsHash);
        // add the one we need
        paramsHash.set('fbReload', 'true');
        paramsHash.set('cacheBust', new Date().getTime());

        //alert('about to reload in static login');
        window.location.href = requestString[0] + '?' + paramsHash.toQueryString() + '#' + hashPipe;
        //alert("Invite.Facebook.doStaticFBLogin() finishing");
    },

    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    handleNewLogin: function(calledFromFBLogin) {
        var fbEmailGranted = false;
        if (calledFromFBLogin == true) {
            var params = (window.location + '').toQueryParams();
            //alert("Invite.Facebook.handleNewLogin called.");
            /* we need to see if we have an email address for this user
             if (_USER && _USER.user.uniqueId == null) {
             Invite.Facebook.gatherEmailModal = Invite.Facebook.buildGatherEmailModal($('gather-email-modal'), null);
             Invite.Facebook.gatherEmailModal.open();
             } else {
             Invite.RegisterLogin.onSuccess();
             }
             */
            //alert("Invite.Facebook.handleNewLogin called.");
            // This section below to do the extended permissions through facebook
            var permission = 'email';
            //alert(FB.Facebook);
            FB.ensureInit(function() {
                FB.Facebook.apiClient.users_hasAppPermission(permission, function(result) {
                    //alert("hello in fb callback");
                    // prompt offline permission
                    if (result == 0) {
                        fbEmailGranted = false;
                    } else {
                        // permission already granted.
                        fbEmailGranted = true;
                    }
                    //alert("fbEmailGranted = " + fbEmailGranted + ", _USER = " + _USER);
                    if (fbEmailGranted == false) {
                        Invite.Facebook.launchFBEmailPermissionDialog();
                        //Invite.Facebook.gatherEmailModal = Invite.Facebook.buildGatherEmailModal($('gather-email-modal'), null);
                        //Invite.Facebook.gatherEmailModal.open();

                    } else {
                        Invite.Facebook.doFBRefresh();
                    }
                }); // end, check FB email
            });
        }

    },


    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    buildGatherEmailModal: function(container, options) {
        var window_header = new Element('div', {className: 'window_header'});
        var window_title = new Element('div', {className: 'window_title'});
        var window_close = new Element('div', {className: 'window_close'});
        var window_contents = new Element('div', {className: 'window_contents'});
        var w = new Control.Modal(container, Object.extend({
            overlayOpacity:'0.8',
            fade: 'true',
            fadeDuration: '.5',
            className: 'window',
            closeOnClick: window_close,
            draggable: window_header,
            insertRemoteContentAt: window_contents,
            afterOpen: function() {
                window_title.update(container.readAttribute('title'));
                //$('user-name').activate();
            }
        }, options || {}));
        w.container.insert(window_header);
        window_header.insert(window_title);
        window_header.insert(window_close);
        w.container.insert(window_contents);
        return w;

    },

    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    launchFBEmailPermissionDialog: function() {
        FB.Connect.showPermissionDialog('email', function(accepted) {
            //alert("accepted: " + accepted); //this comes back as 'email' if email selected, not boolean.
            //Invite.Facebook.doStaticFBLogin();
            if (accepted == 'email') {
                Invite.RegisterLogin.onSuccess();
            } else {
                //they don't want us to communicate with them in facebook.
                //let's see if we are missing an email address ( the case where they came from broadcast link )
                if (_USER && ( _USER.user.uniqueId == null || _USER.user.uniqueId.indexOf('@proxymail.facebook.com') > 0)) {
                    if (confirm("You have chosen NOT to receive communication from invite. Click 'cancel' to change your mind.")) {
                        //we could gather email here.
                    } else {
                        //let's try to get permissions again.
                        Invite.Facebook.launchFBEmailPermissionDialog();
                    }
                    ;
                } else {
                    //we have an email address
                    Invite.RegisterLogin.onSuccess();
                }
            }
            //Invite.Facebook.gatherEmailModal.close();

            /* parse q string
             var params = (window.location + '').toQueryParams();

             // add fbreload
             params['fbReload'] = true;

             // refresh using the current URL, plus rb
             window.location = params.toQueryString();
             */
        });

        return false;
    },

    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    gatherEmailOk: function(event) {

        new Ajax.Request('/invite2/fb-user-set-email.iggli', {
            method:'post',
            parameters:{
                userEmail:$('gather-email-address').value},
            onSuccess:function() {

            },
            onError:function() {

            },
            onComplete:function() {
                Invite.Facebook.gatherEmailModal.close();
            }
        }); // end AJAX request

        return false;
    },


    testShowEmailModal: function() {
        Invite.Facebook.gatherEmailModal = Invite.Facebook.buildGatherEmailModal($('gather-email-modal'), null);
        Invite.Facebook.gatherEmailModal.open();
    },


    testParse: function(event) {
        // split the request on ? , 0 is main action, 1 is everything else
        var requestString = (window.location + '').split('?');

        var hashPipe = ((window.location + '').split('#'))[1];

        // make a hash out of the parms on the right, this might beempty
        var paramsHash = $H(requestString[1].toQueryParams());

        // add the one we need
        paramsHash.set('fbReload', 'true');

        $('test-parse').update(requestString[0] + '?' + paramsHash.toQueryString() + '#' + hashPipe);
    }

}

Invite.HeaderNav = {

    // track open / closed state of menus
    menuStates: {'header-nav-invite':false,'header-nav-iggli':false},

    menuResponseTimeSeconds: 0.3,
    menuResponseTimeMS: 300,

    popupMenuTop: null,
    popupMenuLeft: null,
    popupMenuWidth: null,
    popupMenuHeight: null,
    mouseOverTimestamp: null,
    mouseMoveTimestamp: null,

    menuCloseTimers:{'header-nav-iggli':null, 'header-nav-invite':null},

    mouseMoveTimeout: null,

    logoutTimer: null,

    menuPopupEnabled: false,

    hoverIntentMS: 300,



    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    handleNavItemClick: function(event) {

        var element = Event.findElement(event, 'a');

        var openCloseElements = Invite.HeaderNav.getOpenCloseElements(element.id);

        Invite.HeaderNav.openMenu(openCloseElements.openId);
        Invite.HeaderNav.closeMenu(openCloseElements.closeId);

        new Effect.toggle($(openCloseElements.openId), 'appear', {duration:Invite.HeaderNav.menuResponseTimeSeconds});
        new Effect.Fade(openCloseElements.closeId, {duration:Invite.HeaderNav.menuResponseTimeSeconds});
        return false;
    },


    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    openMenu: function(modalPopupElmId) {
        if (!Invite.HeaderNav.menuStates[modalPopupElmId]) {
            Invite.HeaderNav.menuStates[modalPopupElmId] = true;

            // first we need to position the div w javascript
            // grab the positioin of the thing we clicked on
            var menuElmId = null;
            if (modalPopupElmId == 'header-nav-invite') {
                menuElmId = 'nav-invite';
            } else {
                menuElmId = 'nav-iggli';
            }

            // $(modalPopupElmId).style.left = $(menuElmId).viewportOffset().left + "px";


            new Effect.Appear(modalPopupElmId, {duration:Invite.HeaderNav.menuResponseTimeSeconds,afterFinish: function(obj) {
                // after the menu opens, get dimensions so we can hide it on mouse out
                Invite.HeaderNav.popupMenuTop = $(modalPopupElmId).viewportOffset().top;
                Invite.HeaderNav.popupMenuLeft = $(modalPopupElmId).viewportOffset().left;
                Invite.HeaderNav.popupMenuWidth = $(modalPopupElmId).getWidth();
                Invite.HeaderNav.popupMenuHeight = $(modalPopupElmId).getHeight();
            }});
        }
    },




    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    closeMenu: function(id) {
        if (Invite.HeaderNav.menuStates[id]) {
            Invite.HeaderNav.menuStates[id] = false;
            new Effect.Fade(id, {duration:Invite.HeaderNav.menuResponseTimeSeconds});
        }
    },



    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    handleNavItemMouseOver: function(event) {
        Invite.HeaderNav.menuPopupEnabled = true;
        //$('debug-enabled').update('enabled');

        //$('debug-show-mouse-over').update('over ' + new Date().getTime());
        //Invite.HeaderNav.mouseOverTimestamp = new Date().getTime();

        return false;
    },


    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    handleNavItemMouseOut: function(event) {
        var element = Event.findElement(event, 'a');

        Invite.HeaderNav.menuPopupEnabled = false;
        //$('debug-enabled').update('disabled');


        var openCloseIds = Invite.HeaderNav.getOpenCloseElements(element.id);

        //$('debug-out-indicator').update('set timout: ' + element.id);

        Invite.HeaderNav.menuCloseTimers[openCloseIds.openId] = window.setTimeout(function() {
            Invite.HeaderNav.closeMenu(openCloseIds.openId);
            //Invite.HeaderNav.closeMenu('header-nav-invite');
        }, Invite.HeaderNav.menuResponseTimeMS);

        return false;
    },


    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    handleLogoutMouseOver: function() {
        Invite.HeaderNav.logoutTimer = window.setTimeout(function() {
            Invite.HeaderNav.closeMenu('header-nav-iggli');
            Invite.HeaderNav.closeMenu('header-nav-invite');
        }, Invite.HeaderNav.menuResponseTimeMS);

    },


    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    menuOnMouseInOut: function(e) {
        //$('menu-mouseover').update('menu: ' + e.toString());

        var mouseX = Event.pointerX(e);
        var mouseY = Event.pointerY(e);

        var offset = 4;

        var element = Event.element(e).up('.dropdown'); // the div element

        if (mouseX >= Invite.HeaderNav.popupMenuLeft + offset && mouseX <= (Invite.HeaderNav.popupMenuLeft + Invite.HeaderNav.popupMenuWidth) - offset && mouseY >= Invite.HeaderNav.popupMenuTop + offset && mouseY <= (Invite.HeaderNav.popupMenuTop + Invite.HeaderNav.popupMenuHeight) - offset) {
            //$('menu-mouseover').update('clearing timout: ' + element.id);

            window.clearTimeout(Invite.HeaderNav.menuCloseTimers[element.id]);
        } else {
            //$('menu-mouseover').update('OUTSIDE');

            // just close both menus here
            Invite.HeaderNav.closeMenu('header-nav-iggli');
            Invite.HeaderNav.closeMenu('header-nav-invite');
        }
    },


    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    handleNavItemMouseMove: function(event) {
        var element = Event.findElement(event, 'a');

        Invite.HeaderNav.mouseMoveTimestamp = new Date().getTime();
        var diff = Invite.HeaderNav.mouseMoveTimestamp - Invite.HeaderNav.mouseOverTimestamp;
        //$('debug-show-mouse-move').update('diff ' + diff);

        window.clearTimeout(Invite.HeaderNav.mouseMoveTimeout);
        Invite.HeaderNav.mouseMoveTimeout = setTimeout(function() {
            //$('debug-move-indicator').update('you hovered: ' + new Date().getTime());

            if (Invite.HeaderNav.menuPopupEnabled) {
                var openCloseIds = Invite.HeaderNav.getOpenCloseElements(element.id);
                Invite.HeaderNav.openMenu(openCloseIds.openId);
                Invite.HeaderNav.closeMenu(openCloseIds.closeId);
            }

        }, Invite.HeaderNav.hoverIntentMS);


    },

    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    observeNavItems: function() {
        $$('.header-nav-link').each(function(n) {
            n.observe('click', Invite.HeaderNav.handleNavItemClick);
            n.observe('mouseover', Invite.HeaderNav.handleNavItemMouseOver);
            n.observe('mouseout', Invite.HeaderNav.handleNavItemMouseOut);
            n.observe('mousemove', Invite.HeaderNav.handleNavItemMouseMove);
        });

        $$('.link-nav-logout').each(function(n) {
            n.observe('mouseover', Invite.HeaderNav.handleLogoutMouseOver);
        });

        $$('.link-nav-login').each(function(n) {
            n.observe('mouseover', Invite.HeaderNav.handleLogoutMouseOver);
        });

        $$('div.dropdown').each(function(n) {
            n.observe('mouseover', Invite.HeaderNav.menuOnMouseInOut);
            n.observe('mouseout', Invite.HeaderNav.menuOnMouseInOut);
        });


    },
    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    getOtherMenu: function(id) {
        if (id == 'header-nav-iggli') {
            return 'header-nav-invite';
        } else {
            return 'header-nav-iggli';
        }
    },



    //-----------------------------------------------------------------------------
    //
    //
    //
    //-----------------------------------------------------------------------------
    getOpenCloseElements: function(clickedId) {
        var closeId = null;
        var openId = null;
        if (clickedId == "link-nav-invite") {
            openId = 'header-nav-iggli';
            closeId = 'header-nav-invite';
        } else if (clickedId == "link-nav-iggli") {
            openId = 'header-nav-invite';
            closeId = 'header-nav-iggli';
        }

        return {openId:openId,closeId:closeId};
    },
    
    logout: function(logoutUrl) {
        // split the request on ? , 0 is main action, 1 is everything else
        var requestString = (logoutUrl + '').split('?');
        //alert(requestString);
        // get the hash section too
        var hashPipe = ((logoutUrl + '').split('#'));
        if (!hashPipe[1]) hashPipe = ""; //so the word undefined doesn't get into the hash.
        // make a hash out of the parms on the right, this might beempty
        var paramsHash = new Hash();
        if (requestString[1]) {
            paramsHash = $H(requestString[1].toQueryParams());
        }
        // add the one we need
        paramsHash.set('cacheBust', new Date().getTime());
        var finalUrl = requestString[0] + '?' + paramsHash.toQueryString() + '#' + hashPipe;
        //alert(finalUrl);
        window.location.href = finalUrl;
    }


};

//##############################################################################
//
//
//
//##############################################################################
Event.observe(document, 'dom:loaded', function() {
    Invite.HeaderNav.observeNavItems();
});


/** a class for misc functions **/
Invite.Misc = {

    //wire up the tips o the page
    //IE7 Warning: must be used with window 'load' and not dom:loaded or get operation aborted.
    observeTips : function() {
        var tips = $$("a.tip-icon", "a.tip-link");
        tips.each(function(element) {
            var offset = 10;
            if (element.hasClassName('one')) offset = -300;
            if (element.hasClassName('twelve')) offset = -150;
            if (element.hasClassName('three')) offset = -300;
            new Control.Window(element, {
                position: 'relative',
                hover: false,
                closeOnClick: true,
                offsetLeft: 10,
                width: 300,
                className: 'tooltip'
            });
        });
    },
    
    //Does the hard work of getting the params out of the link and 
    //attaching it all to a Control.Modal
    createTweetThisModalFromLink : function(element) {
    	
    	//you can pass in broadcastUrl and broadcastTitle as tag attributes or just use defaults.
    	var params = {};
    	params.url = element.readAttribute("url") || document.location.href;
    	params.type = element.readAttribute("type") || "simple";
    	params.title = element.readAttribute("title") || document.title;
    	if (element.readAttribute("provider")) {
    		params.provider = element.readAttribute("provider");
    	}
    	if (element.readAttribute("providerItemId")) {
        	params.providerItemId = element.readAttribute("providerItemId")
    	}
    	new Control.Modal(element, {	
    		overlayOpacity:'0.8',
    		fade: 'true', 
    		fadeDuration: '0.5',
    		className: 'tooltip', 
    		parameters: params,
    		closeOnClick: 'overlay', 
    		afterOpen: function() {
    			//do stuff
    		}
    	});

    },
    
    //wire up the tips o the page
    //IE7 Warning: must be used with window 'load' and not dom:loaded or get operation aborted.
    observeTweetThisLinks : function() {
        var tweetLinks = $$("a.tweet-this-link");
        tweetLinks.each(function(element) {
        	Invite.Misc.createTweetThisModalFromLink(element);
        });
    },
    
    //wire up the share this links on the page
    observeShareThisLinks : function() {
        var shareLinks = $$("a.share-this-link");
        shareLinks.each(function(element) {
        	Event.observe(element, 'click', Invite.SocialNetworks.Facebook.handlePostInviteToWall);
        });
    },
    
    /*
     * text to display, style to use, fade ( varied can be #seconds OR false. ), scroll = true/false
     */
    displayMessage : function displayMessage(text, style, fade, scroll) {

        var element = $('message');
        if (scroll == true)
            element.scrollTo();
        element.removeClassName('notice');
        element.removeClassName('error');
        element.removeClassName('success');
        if (style) {
            element.addClassName(style);
        } else {
            element.addClassName('notice');
        }
        var fadeDelay = 2.0;
        if (fade) {
            fadeDelay = fade;
        }
        element.update(text);
        new Effect.Appear(element, { queue: 'front', duration: .5 });
        if (fade !== false) new Effect.Fade(element, { queue: 'end', delay: fadeDelay });

    },

    // --------------------------------------------
    //
    // --------------------------------------------
    handleBuyTicketClick: function(url, inviteId) {
        var width = 1024;
        var height = 600;
        var igUrl = "/invite2/open-buy-tix-window.iggli?tixUrl=" + escape(url);
        window.open(igUrl, '_blank', 'location=1,status=1,toolbar=1,scrollbars=1,menubar=1,resizeable=1,width=' + width + ',height=' + height);
        Invite.Misc.ajaxRecordTicketClick(inviteId, '/outbound/liteviteStatus/buyTickets/');
    },


    // --------------------------------------------
    //
    // --------------------------------------------
    ajaxRecordTicketClick:function (inviteId) {
        new Ajax.Request('/ajax/record-ticket-click.iggli', {
            method:'post',
            parameters: {inviteId: inviteId},
            onSuccess:function(transport) {
            }
        });
        pageTracker._trackPageview('/outbound/liteviteStatus/buyTickets/' + inviteId);
    },

    // ------
    // will add a cachebust to the url, and optional javascript callback.
    // you can pass in new params, or replace existing params
    // you can even pass in an optional whole new url...
    // NOTE: newUrl can't have any query string or hash
    //
    // ALL ARGS ARE OPTIONAL
    // callback = will be attached to url as #Invite.DoThis.dothat
    // newParams = e.g. { partnerId: 500 }
    // newUrl = the base url, no query or hash e.g. /this.iggli or 
    // ------
    reload: function(callback, newParams, newUrl) {
        var requestString = (window.location + '').split('?');
        newUrl = newUrl ? newUrl : requestString[0] ;

        // make a hash out of the parms on the right, this might beempty
        var paramsHash = new Hash();
        if (requestString[1]) {
            paramsHash = $H(requestString[1].toQueryParams());
        }
        paramsHash.set('cacheBust', new Date().getTime());
        if (newParams) {
        	paramsHash = paramsHash.merge(newParams);
        }
        newUrl += "?" + paramsHash.toQueryString();
        //if no callback, then add the hash back to the url.
        var hashPipe = false;
        if (callback) {
        	hashPipe = callback;
        } else {
        	var hashPipeArray = ((window.location + '').split('#'));
        	if (hashPipeArray[1]) hashPipe = hashPipeArray[1];
        }
        
        if (hashPipe) {
        	newUrl += "#" + callback;
        }
        window.location.href = newUrl;
    },
    
    readCookie: function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) {
				return c.substring(nameEQ.length,c.length);
			}
		}
		return null;
	},
	
	writeCookie: function(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		/*
		if (document.cookie) {
			document.cookie = document.cookie + ";" + name+"="+value+expires+"; path=/";
		*/
		document.cookie = name+"="+value+expires+"; path=/";
		//alert("Just wrote cookie: Invite.Misc.readCookie: " + Invite.Misc.readCookie("fbLoginRefresh") + ", doc.cookie: " + document.cookie);
        
	},
	
	eraseCookie: function(name) {
		Invite.Misc.writeCookie(name,"",-1);
	},
	
	popupRedirect : function(width, height, url) {
        var igUrl = "/ajax2/generic-popup.iggli?redirectUrl=" + escape(url);
        window.open(igUrl, '_blank', 'location=1,status=1,toolbar=1,scrollbars=1,menubar=1,resizeable=1,width=' + width + ',height=' + height);
    }
	

}
// You must call init to use this object
Invite.Misc.BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            } else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    dataBrowser: [
        {
            string: navigator.userAgent,
            subString: "Chrome",
            identity: "Chrome"
        },
        {
            string: navigator.userAgent,
            subString: "OmniWeb",
            versionSearch: "OmniWeb/",
            identity: "OmniWeb"
        },
        {
            string: navigator.vendor,
            subString: "Apple",
            identity: "Safari",
            versionSearch: "Version"
        },
        {
            prop: window.opera,
            identity: "Opera"
        },
        {
            string: navigator.vendor,
            subString: "iCab",
            identity: "iCab"
        },
        {
            string: navigator.vendor,
            subString: "KDE",
            identity: "Konqueror"
        },
        {
            string: navigator.userAgent,
            subString: "Firefox",
            identity: "Firefox"
        },
        {
            string: navigator.vendor,
            subString: "Camino",
            identity: "Camino"
        },
        {
            // for newer Netscapes (6+)
            string: navigator.userAgent,
            subString: "Netscape",
            identity: "Netscape"
        },
        {
            string: navigator.userAgent,
            subString: "MSIE",
            identity: "Explorer",
            versionSearch: "MSIE"
        },
        {
            string: navigator.userAgent,
            subString: "Gecko",
            identity: "Mozilla",
            versionSearch: "rv"
        },
        {
            // for older Netscapes (4-)
            string: navigator.userAgent,
            subString: "Mozilla",
            identity: "Netscape",
            versionSearch: "Mozilla"
        }
    ],
    dataOS : [
        {
            string: navigator.platform,
            subString: "Win",
            identity: "Windows"
        },
        {
            string: navigator.platform,
            subString: "Mac",
            identity: "Mac"
        },
        {
            string: navigator.platform,
            subString: "Linux",
            identity: "Linux"
        }
    ]

};

//----------------------------------------------------
//handle forgotten password
//----------------------------------------------------
function ajaxForgotPassword() {
    // return if they didn't type email
    if ($('login-email')) {
        var loginEmail = $('login-email').value;
        if (loginEmail.length <= 0) {
            $('forgot-password-message').update('Please fill out the email section.');
            return false;
        }
    }

    new Ajax.Request('/ajax/forgot-password.iggli', {
        method: 'get',
        parameters: {loginEmail: $('login-email').value},
        onFailure:function(transport) {
            $('forgot-password-message').update('<strong>Unknown email address.</strong>  To reset password, fill out email section and<a class="login-link" href="#poop" onclick="ajaxForgotPassword();"> click here</a>');
        },

        onSuccess:function(transport) {
            $('forgot-password-message').update('Please check your email for password reset instructions');
        }
    });

    new Effect.Highlight('forgot-password-message');

}

//wrapper for Invite.Misc.displayMessage - compatability
function displayMessage(text, style, fade, scroll) {
    Invite.Misc.displayMessage(text, style, fade, scroll);
}


