function whatsthis() {
    hideAllContent();
    resetAllTabs();
    $('whatsthis-container').show();
    pageTracker._trackPageview('/LiteviteModal/whatsThis/');
}

function sentSocialConfirmation() {
    confirmTab();
    sentConfirmation();
}

function sentConfirmation() {
    if ($('confirm-tab-holder').visible() == false) {
        Effect.Appear('confirm-tab-holder', { duration: .5 });
    }
    getSocialShareLink();
    refreshInviteesList();
    refreshInviteesCount();
    //post to facebook link appears on the confirmation page if the user is logged into facebook.
    //if this element is present, we're going to automatically trigger the post to facebook flow 1 time.
    if ($('post-to-facebook') && Invite.SocialNetworks.Facebook.alreadyPostedToWall == false) {
        Invite.SocialNetworks.Facebook.postInviteToWall($('post-to-facebook'));
        Invite.SocialNetworks.Facebook.alreadyPostedToWall = true;
        pageTracker._trackPageview('/LiteviteModal/facebook-post-to-wall-auto-opened/');
    }
    pageTracker._trackPageview('/LiteviteModal/sentConfirmation/');
}

function previewTab() {
    //participants
    var parts = '[Please fill out the "TO" section.]';
    var partsList = $F('tmp-participants');
    if (partsList.length > 0) {
        if (partsList.length > 40) {
            partsList = partsList.substring(0, 40) + "...";
        }
        parts = partsList;
    }
    $('participants-list').update(parts);
    //from section
    var from = '[Please fill out the "FROM" section.]';
    var fromEmail = $F('tmp-email');
    var fromName = "[your name]";
    if (fromEmail.length > 0 && fromEmail != "your email address") {
        var fromName = $F('tmp-name');
        if (fromName.length > 0 && fromName != "your name") {
            from = fromName = fromName;
        } else {
            from = fromName = fromEmail;
        }
    }
    $('from-preview').update(from);
    if (theTitle && theTitle.length > 33) {
        theTitle = theTitle.substring(0, 30) + "...";
    }
    $('subject-preview').update(fromName + " invites you to " + theTitle);
    //message section
    var message = $F('tmp-message');
    if (message.length == 0) message = "[your personal message here]";
    if (message.length > 0) {
        if (message.length > 250) {
            message = message.substring(0, 250) + "...";
        }
        $('message-preview').update('&quot;' + message + '&quot;');
        $('message-signature').update('&#8212; ' + fromName);
    }
    //
    hideAllContent();
    resetAllTabs();
    $('preview-tab').addClassName("current");
    $('preview-tab-content').show();
    pageTracker._trackPageview('/LiteviteModal/preview');

}

function inviteTab() {
    hideAllContent();
    resetAllTabs();
    //$('litevite-container').show();
    $('invite-tab').addClassName("current");
    $('invite-tab-content').show();
}

function csvHelpTab() {
    hideAllContent();
    resetAllTabs();

    $('csv-help-container').show();
}

function focusInviteTabToField() {
    inviteTab();
    $$('input.inline-input')[0].focus();
}

function confirmTab() {
    hideAllContent();
    resetAllTabs();
    $('confirm-tab').addClassName("current");
    $('confirm-tab-content').show();
}

function showLogin() {
    hideAllContent();
    resetAllTabs();
    $('login-container').show();
    Invite.RegisterLogin.bindKeys();
    $('login-email').activate();
    pageTracker._trackPageview('/LiteviteModal/login/');
}

function showImportContacts() {
    hideAllContent();
    resetAllTabs();
    $('import-contacts-container').show();
    pageTracker._trackPageview('/LiteviteModal/import-contacts/');
}

function showImportWebmail(serviceName) {
    hideAllContent();
    resetAllTabs();

    setInputValue($('email-service-select'), serviceName);
    $('import-webmail-container').show();
    setInputValue($('email-address-input'), '');
    setInputValue($('email-password-input'), '');
    $('email-address-input').focus();

    pageTracker._trackPageview('/LiteviteModal/import-webmail/');
}

function hideAllContent() {
    $('preview-tab-content').hide();
    $('confirm-tab-content').hide();
    $('whatsthis-container').hide();
    $('invite-tab-content').hide();
    $('social-instruction-container').hide();
    $('login-container').hide();
    $('import-contacts-container').hide();
    $('import-webmail-container').hide();
    $('csv-help-container').hide();
}

function resetAllTabs() {
    $('preview-tab').removeClassName("current");
    $('invite-tab').removeClassName("current");
    $('confirm-tab').removeClassName("current");
}

/**
 *
 * @param network
 */
function openSocialShareWindow(network, width, height) {
    var url = '/social-share-popup.iggli?';
    url += $H({ "network": network, "inviteId": thisInviteId, "message": $F('tmp-message'), "regName":$F('tmp-name'), "regEmail":$F('tmp-email'), "userId":thisUserId }).toQueryString();
    window.setTimeout("sentSocialConfirmation()", 3000);
    // record outbound clicks
    pageTracker._trackPageview('/outbound/socialTab/' + network);

    window.open(url, '_blank', 'location=1,status=1,toolbar=1,scrollbars=1,menubar=1,resizable=1,width=' + width + ',height=' + height);
    return false;
}

// ---------------------------------------------
//
// ---------------------------------------------
function openSocialShareInsructions(network) {


    new Ajax.Updater('social-instruction-container', '/litevite-modal-social-instructions.iggli', {
        method:'get',
        parameters:{
            network:network
        },
        onComplete: function(transport) {
            hideAllContent();

            // copy fields from main form
            $('instructions-name').value = $F('tmp-name');
            $('instructions-email').value = $F('tmp-email');

            $('social-instruction-container').show();

            hideFacebookFromSafari();
        }
    });
}


/**
 * This method is responsible for sending invitations to the various social networks.
 * unless email is clicked, then it calls the liteviteTab function to return to the default first page.
 */
function socialNav(network, emailFieldElm, nameFieldElm) {
    if (validateEmail(emailFieldElm.value, false, null) == false) {

        displayMessage('We need your email address<br />( <strong>Or connect with Facebook</strong> ) <br />to send a link to the invite where <br />friends RSVP, add messages, and more.');
        emailFieldElm.activate();
        return false;
    }
    switch (network) {
        case 'email':
            if (nameFieldElm) return false;
            liteviteTab('invite');
            break;
        case 'facebook':
            openSocialShareWindow((network), 990, 550);
            break;
        case 'twitter':
            openSocialShareWindow((network), 550, 290);
            break;
        case 'myspace':
            openSocialShareWindow((network), 980, 600);
            break;
        case 'bebo':
            openSocialShareWindow((network), 640, 360);
            break;
        case 'linkedin':
            openSocialShareWindow((network), 500, 540);
            break;
        case 'friendfeed':
            openSocialShareWindow((network), 735, 320);
            break;
        default: inviteTab();


    } // end switch

    $('confirm-email-instructions').hide();
    $('confirm-social-instructions').show();

    getSocialShareLink(network);

    return true;
}


/**
 * This method is responsible for formatting everything to send an invitation by email.
 * it uses several helper methods to validate and deal with the data.
 */
function sendInviteByEmail() {
    if (doLiteviteValidation() == false) {
        inviteTab();
        return false;
    }

    $('working').show();
    $('send-email-link').hide();

    var name = $F('tmp-name');
    if (name == 'your name') name = "";
    // cookies not being sent on invite contacts ajax call from Safari so pass userId to user interceptor
    var participantsArray = splitParticipants();
    // now normalize the array into a comma separated string with no spaces.
    var newEmailsString = "";
    participantsArray.each(function(email, index) {
        newEmailsString = newEmailsString + email;
        if (index < (participantsArray.length - 1)) {
            newEmailsString = newEmailsString + ",";
        }
    });
    //alert("before send parts array: " + participantsArray.inspect());
    //alert("before send parts str: " + newEmailsString);

    var url = "/ajax/litevite-send-by-email.iggli";
    var params = { "regName":name, "regEmail":$F('tmp-email'), "recipientsByEmail":newEmailsString, "message":$F('tmp-message'), "inviteId":thisInviteId, "userId":thisUserId  };
    new Ajax.Request(url, {
        parameters: params,
        evalJSON: "force",
        onSuccess: function(transport) {
            var json, message;
            //try to parse as json.
            //but if an error, catch SyntaxError and display the error message.
            //alert("success");
            //alert(transport.responseText);
            //alert(Object.toJSON(json));

            try {
                //We used to do a bunch of stuff depending on response code
                //which is related to whether a user is logged in or not.
                //we don't really care anymore...but we might in future so stuff is still here.
                json = transport.responseJSON;
                if (json.responseCode) {
                    if (1 == json.responseCode) { //user is logged in.  give them a link.

                        confirmTab();
                        sentConfirmation();
                        clearToField();


                    } else if (2 == json.responseCode) { //use needs to validate email first.

                        confirmTab();
                        sentConfirmation();
                        clearToField();


                    } else {
                        //it's a json object without the expected response code.  Pray it has a message.
                        confirmTab();
                        sentConfirmation();
                        clearToField();
                    }
                } else {
                    //it's a json object without the expected response code.  Pray it has a message.
                    confirmTab();
                    sentConfirmation();
                    clearToField();

                }
            } catch(err) {
                //not a json object probably.
                confirmTab();
                sentConfirmation();
                clearToField();
            }
        },
        onComplete: function(transport) {
            $('working').hide();
            $('send-email-link').show();
            $('confirm-social-instructions').hide();
            $('confirm-email-instructions').show();
            pageTracker._trackPageview(url);
        },
        onFailure: function(transport) {
            inviteTab();
            if (transport.responseText.length < 500) {
                displayMessage(transport.responseText);
            } else {
                displayMessage("Oops! Something went wrong.");
            }
        }
    });
}

/**
 * This helper method validates the data for sending by email.
 */
function doLiteviteValidation() {
    if (validateEmail($F('tmp-email'), false, null) == false) {
        displayMessage('Please provide a valid email address.');
        $('tmp-email').activate();
        return false;
    }
    var toEmails = $F('tmp-participants');
    if (toEmails.blank()) {
        //let's see if there's anything waiting in the autocompleter input field.
        var toFieldInlineInput = $$("input.inline-input")[0];
        if (toFieldInlineInput && toFieldInlineInput.value.length == 0) {
            displayMessage("please enter at least one email address.");
            toFieldInlineInput.focus();
            //$('tmp-participants').focus();
            return false;
        }
    }
    var participantsArray = splitParticipants();
    //alert("parts array: " + participantsArray);
    if (participantsArray.length > 0) {
        //enumerate through the emails and validate each.  Display message show any/every failure.
        if (participantsArray.all(function(email, index) {
            //validate email...display it if fails.
            //alert(email);
            if (validateEmail(email, false, null) == false) {
                displayMessage("'" + email + "' doesn't look like a valid email address.");
                //find and highlight the specific element.
                var emailElements = $$("a.contact-token[title='" + email + "']");
                if (emailElements && emailElements.size && emailElements.size() > 0) {
                    $(emailElements[0]).setStyle({color:"red"});
                }
                return false;
            }
            return true;

        }) == false) {
            //one email fails validation
            $('tmp-participants').focus();
            return false;
        }

    }
    return true;

}

/**
 * This method creates an array of participants
 * taking care to strip out many issues with email formatting.
 */
function splitParticipants() {

    var toEmails = $F('tmp-participants');
    var toFieldInlineInput = $$("input.inline-input")[0];
    var emailsArray = new Array();
    if (toEmails.empty()) {
        //let's see if there's anything waiting in the autocompleter input field.
        if (toFieldInlineInput && toFieldInlineInput.value.length == 0) {
            //nothing entered...return empty array.
            return emailsArray;
        }
    }
    var split;
    if (toEmails.indexOf(',') > 1) {
        split = ",";
    } else if (toEmails.indexOf(';') > 1) {
        split = ";";
        /*
         } else if (toEmails.indexOf(' ') > 1) {
         split = " ";
         */
    }
    //let's grab the stuff out of the autocompleter input field if there is anything.
    if (toFieldInlineInput && toFieldInlineInput.value.length > 0) {
        //if there's an existing split character defined, use it.
        if (split) {
            toEmails = toEmails + split + toFieldInlineInput.value;
        } else {
            //else we'll use a comma and define split to be comma.
            toEmails = toEmails + "," + toFieldInlineInput.value;
            split = ",";
        }
        //alert(toEmails);
    }
    if (split) {
        emailsArray = toEmails.split(split);
        emailsArray = pluckEmailAddressFromCaratSyntax(emailsArray);
        emailsArray = emailsArray.invoke('strip');
        //get rid of any empty array elements;
        emailsArray = emailsArray.select(function(email) {
            return (email);
        });
        emailsArray = emailsArray.select(function(email) {
            return !email.empty();
        });
        return emailsArray;

        //return it.
    } else {
        //alert('hello');
        emailsArray.push(toEmails.strip());
        emailsArray = pluckEmailAddressFromCaratSyntax(emailsArray);
        return emailsArray;

    }
}


/**
 * This method deals with email address in the "Dehru Cromer" <dehru@yahoo.com> format.
 * for now, it just uses the email address portion.
 */
function pluckEmailAddressFromCaratSyntax(emailsArray) {
    //check for email format "blah" <blah@blah.com>
    if (emailsArray && emailsArray.length > 0) {
        var newEmailsArray = new Array();
        emailsArray.each(function(email) {
            if (email.indexOf('<') > 1 && email.indexOf('>') > 1) {
                lessThan = email.indexOf('<');
                greaterThan = email.indexOf('>');
                email = email.substring(lessThan + 1, greaterThan);
            }
            newEmailsArray.push(email);
        });
        return newEmailsArray;
    }
    return emailsArray;
}


function getSocialShareLink() {

    var url = "/ajax2/tweet-this-invite.iggli";
    var params = { "inviteId":thisInviteId,
        "title":document.title};
    new Ajax.Request(url, {
        parameters: params,
        onSuccess: function(transport) {
            //make sure this seems like a valid link.
            if (transport.responseText && transport.responseText.length < 500) {
                $('tweet-this-link').update(transport.responseText);
                var shareLink = $('tweet-this-link').select("a");
                if (shareLink && shareLink[0]) {
                    $('social-share-link').value = shareLink[0].readAttribute("url");
                }

            }
        }
    });
}

function refreshInviteesList() {

    var url = "/ajax/invite-modal-refresh-invitees.iggli";
    var params = { "inviteId":thisInviteId  };
    new Ajax.Request(url, {
        parameters: params,
        onSuccess: function(transport) {
            //make sure this seems like a valid list of invitees and not an error page or something strange.
            if (transport.responseText && transport.responseText.length < 500) {
                $('invitees-list').update(transport.responseText);
            }
        }
    });
}

function refreshInviteesCount() {

    var url = "/ajax/invite-modal-invitee-count.iggli";
    var params = { "inviteId":thisInviteId  };
    new Ajax.Request(url, {
        parameters: params,
        onSuccess: function(transport) {
            //make sure this seems like a valid count return.
            if (transport.responseText && transport.responseText.length < 20) {
                $('invitee-count').update(transport.responseText).show();
            }
        }
    });
}

function setInputValue(obj, value) {
    var use_default = (arguments.length > 1) ? arguments[1] : false;
    if (isArray(obj) && (typeof(obj.type) == "undefined")) {
        for (var i = 0; i < obj.length; i++) {
            setSingleInputValue(obj[i], value);
        }
    } else {
        setSingleInputValue(obj, value);
    }
}

function setSingleInputValue(obj, value) {
    switch (obj.type) {
        case 'radio': case 'checkbox':
        if (obj.value == value) {
            obj.checked = true;
            return true;
        } else {
            obj.checked = false;
            return false;
        }
        case 'text': case 'hidden': case 'textarea': case 'password':
        obj.value = value;
        return true;
        case 'select-one': case 'select-multiple':
        var o = obj.options;
        for (var i = 0; i < o.length; i++) {
            if (o[i].value == value) {
                o[i].selected = true;
            } else {
                o[i].selected = false;
            }
        }
        return true;
    }
    alert("FATAL ERROR: Field type " + obj.type + " is not supported for this function");
    return false;
}

function isArray(obj) {
    return(typeof(obj.length) == "undefined") ? false : true;
}

function clearToField() {
    var emailElements = $$("a.contact-token");
    if (emailElements && emailElements.size() > 0) {
        emailElements.each(function(el) {
            el.remove();
        });
    }
    var toFieldInlineInput = $$("input.inline-input")[0];
    if (toFieldInlineInput && toFieldInlineInput.value.length > 0) {
        toFieldInlineInput.value = "";
    }
    $('tmp-participants').value = "";
}

//called from initAutocomplete function
//if this user is not logged in, start them on the Your Name field
var setDefaultFocus = function() {
    var nameElement = $('tmp-name');
    if (nameElement) {
        if (nameElement.readAttribute('disabled')) {
            //try to figure out if we're using an autocompleter or not.
            //alert("here with autocompleter: " + autocompleter + " and tmp-participants: " + $('tmp-participants') );
            if (autocompleter) {
                //autocompleter focuses itself.
            } else if ($("tmp-participants")) {
                $("tmp-participants").activate();
            }
        } else {
            nameElement.activate();
        }
    }
}

var theAutocompleter;
function initAutocomplete()
{
    autocompleter = true;
    theAutocompleter = jQuery('input[name=recipients]').toField({
        search: function(text) {
            var toField = this;
            //alert(text);
            jQuery.get('/ajax2/litevite-contacts-autocomplete.iggli', { search: text }, function(data, status) {
                //alert(data);
                toField.handleExternalSearchResults(data);
            }, 'json');
        },
        maxTokenRows: 2,
        ready: setDefaultFocus
    });

    // now set the tab index correctly.
    $('tmp-participants').writeAttribute("tabindex", "");
    $$('input.inline-input')[0].writeAttribute("tabindex", "3");

}

function hideFacebookFromSafari() {
    //Invite.Misc.BrowserDetect.init();
    //alert("browser: " + Invite.Misc.BrowserDetect.browser + ", version: " + Invite.Misc.BrowserDetect.version);
    //Safari does not support iframe facebook login so hide all fb buttons.
    if (!Invite.Misc.BrowserDetect.browser) Invite.Misc.BrowserDetect.init();
    if (Invite.Misc.BrowserDetect.browser == "Safari") {
        $$('a.fb').each(function(e) {
            e.hide()
        });
        $('fb-login1').hide();
        $('fb-login2').hide();
    }
}



