Zipcar wanted a tool members could use to send a coupon to their friends on various social networks.

define (function() {
    var followers_list = {followers :[]};
    var gigya_user;
    var gigya_start_time;

    var credit_message;
    var credit_message_long;

    var error_message_status = 'error retrieving followers!';
    var error_message_detail = 'An error occurred while retrieving your Twitter followers.  Please try again later.'; 

    function setcredit_message (creditNetwork) {
        //credit_chosen - 1: split, 2:give
        creditChosen = $("#credit-choice option:selected").val();
        $(".display-copy").hide();
        $(".tc-" + creditChosen + "-default").css("display", "block");
        credit_message = $(".tc-" + creditChosen + "-" + creditNetwork).html();
        credit_message_long = $(".tcl-" + creditChosen + "-" + creditNetwork).html();
    }
    
    $('#socialPop').jqm({
        modal: true,
        trigger: 'raf-trigger',
        toTop: true
    }).jqmAddClose('.close');

    function displayOverlay(section) {
        $(".socialContent").hide();
        $(".social" + section).show();
        $("#socialPop").jqmShow();
        /*$("#socialPop").overlay({
            mask: {color: '#000', opacity: 0.4},
            fixed:false,
            closeOnClick:false,
            api:true
        }).load();
        */ 
    }

    var conf = {
        APIKey: '2_pNr1115h3GVroGTNCFddDRVrz_64bSUpp6Zx7z_q15q7H0weTIWsNlrymjCuIrPA',
        //APIKey: '2_Y82PzwJ_chSFImHXaIDJClnLyJzmk-VFOavSsaNTzl6m901s_NNxRAS0xJ3bd3_N',
        signIDs: true
    };

    //Facebook
    function facebookConnection(response) {

        setcredit_message("facebook");
    
        if ( response.errorCode == 0 ) {
            gigya_user = response.user;
            // Get promotion code
            $.ajax({
                type : "POST",
                url  : "/social-networks/xml/facebook-promo",
                data : {user_msg:credit_message, credit_chosen:creditChosen},
                success : shareFaceBookLink,
                error   : facebookErrorHandler
            });
        } else {
           facebookDisconnect(null);
        }
    }

    function facebookDisconnect(event) {
        gigya.services.socialize.removeConnection(conf,{provider:'facebook'});
    }

    function facebookErrorHandler(data) {
        error_message_status = 'error retrieving followers!';
        error_message_detail = data.responseText;

        $(".socialMessage").html('

'+error_message_status+'

'+error_message_detail); displayOverlay("Message"); facebookDisconnect(); } function shareFaceBookLink(data) { // Constructing a UserAction Object var act = new gigya.services.socialize.UserAction(); act.setUserMessage("My wheels are your wheels. (Really!) Just reserve online, swipe in with your Zipcard and drive. " + "Gas and insurance is included. So what are you waiting for?"); setcredit_message("facebook"); act.setTitle(credit_message); act.setLinkBack(data); act.setDescription(credit_message_long); var params = { userAction : act, enabledProviders : 'facebook', defaultProviders :'facebook', useFBDialog : 'false', useHTML : 'true', shortURLs : 'always', successMessage : 'true', showEmailButton: 'false', showMoreButton : 'false', grayedOutScreenOpacity : 40, onError : facebookErrorHandler, onClose : facebookDisconnect }; // Show the "Share" dialog gigya.services.socialize.showShareUI(conf, params); } //Twitter var directive = { 'tr' : { 'follower<-followers' : { 'td.twitterCheck input@value' : 'follower.twitterUID', 'td.twitterIcon img@src' : 'follower.twitterIcon', 'td.twitterFollower h3 span' : 'follower.twitterUsername', '+td.twitterFollower h3' : 'follower.twitterFollower' }, filter:function(follower) { var val = $('.twitterInput').val(); if (!val) { val = follower.item.twitterFollower; } return follower.item.twitterFollower.search(val) != -1; } } }; var twitMax = { 'maxCharacterSize': 43, 'warningStyle': 'warning', 'warningNumber': 40, 'displayFormat': '#left' }; var followersHtml = $p('#followersTable table'); var followersRfn = followersHtml.compile(directive); function twitterFollowers(data) { try { var items = followers_list.followers; var props = data; if (props.statusCode == 100) { gigya.services.socialize.getUserInfo(conf, {callback:twitterUserInfo}); return; } if (props.statusCode == 200 && !(props.friends.length == 0)) { displayOverlay("Results"); $.each(props.friends, function(index, data) { var username = ''; if (data.firstName && data.lastName) { username = data.firstName + ' ' + data.lastName; } items.push({twitterUID:data.UID, twitterIcon:data.photoURL.replace('http://a', 'https://si'), twitterFollower:data.nickname, twitterUsername:username}); }); } else { noTwitterFollowersFound(); return; } } catch (e) { followers_list.followers = []; } if (followers_list.followers.length != 0) { followersHtml = followersHtml.render(followers_list, followersRfn); } else { twitterFollowersError(); } $('#socialMessage').textareaCount(twitMax,function(data) { $('#remainingChars').html(data.left); }); } function twitterFollowersError(data) { error_message_status = 'error retrieving followers!'; error_message_detail = data.responseText; $(".socialMessage").html('

'+error_message_status+'

'+error_message_detail); displayOverlay("Message"); twitterDisconnect(); } function noTwitterFollowersFound() { error_message_status = 'no followers found!'; error_message_detail = 'hmm we don\'t seem to find your Twitter followers. Please try again later.'; $(".socialMessage").html('

'+error_message_status+'

'+error_message_detail); displayOverlay("Message"); twitterDisconnect(); } function twitterDisconnect() { followers_list.followers = []; gigya.services.socialize.removeConnection(conf,{provider:'twitter'}); } function twitterConnection(response) { if ( response.errorCode == 0 ) { gigya_user = response.user; $.ajax({ type : "POST", url : "/social-networks/xml/followers", data : {user_id:response.user.UID, ts:response.user.signatureTimestamp}, success : twitterFollowers, error : twitterFollowersError }); } else { twitterFollowersError(); } } function twitterUserInfo(response) { if ( response.errorCode == 0 ) { if ( response.user != null && response.user.isConnected ) { // User already connected twitterConnection(response); } else { gigya.services.socialize.addConnection(conf,{callback:twitterConnection, provider:'twitter', sessionExpiration:900}); } } else { twitterFollowersError(); } } function sendMessageHandler() { var somethingChecked = 0; $(".twitterCheck img").each(function() { if ($(this).hasClass("checked")) { somethingChecked++; } if (somethingChecked > 0) { $("#sendMessageId").removeAttr("disabled").removeClass("inactive"); } else { $("#sendMessageId").attr("disabled","disabled").addClass("inactive"); } }); } function showConfirmation(confirmationMessage, elapsedTime) { /** the following vars will need to be populated from the sendMessageId info **/ var bigTwitterIcon = '/images/template/css/twitterIconBig.jpg'; var twitterUser = gigya_user.nickname; if (gigya_user && gigya_user.photoURL) { //hack - we want secure protocol for our icons bigTwitterIcon = gigya_user.photoURL.replace('http://a', 'https://si'); } if (gigya_user.firstName && gigya_user.lastName) { twitterUser = gigya_user.firstName + ' ' + gigya_user.lastName; } /** following vars pulled from existing input **/ var tweetedMessage = '' + $("#socialMessage").val() + ' ' + credit_message; var postTime = elapsedTime + ' seconds ago'; error_message_status = 'message sent!'; /** confirmation pop-up */ $(".socialMessage").html('

'+error_message_status+'

'+confirmationMessage+ '

'+twitterUser+'

'+tweetedMessage+ '

'+postTime+'

'); displayOverlay("Message"); } function sendTwitterMessage(resp) { var today = new Date(); var elapsedTime = today.getTime() - gigya_start_time; if (resp.statusCode != 200) { failTwitterMessage(); } else { scroll(0,0); showConfirmation($(".confirmation-copy").html(), elapsedTime); displayOverlay("Message"); } } function failTwitterMessage(data) { error_message_status = 'message not sent!'; error_message_detail = data.responseText; scroll(0,0); $(".socialMessage").html('

'+error_message_status+'

'+error_message_detail); displayOverlay("Message"); } var goodAddys = true; function parseEmails(data) { goodAddys = true; var invitees = data.split(','); // Plaxo widget returns a comma delimited list of emails. // Each email may be of the form: // '"first last|email" ' // alternatively, users may type a simple comma delimited list of emails $.each(invitees, function(idx, invitee) { var singleAddy; var namePieces; var firstName; var lastName; //plaxo emails are inside <>, typed lists aren't if (invitee.match(/<(.*)>/) == null) { singleAddy = invitee; firstName = lastName = ""; } else { singleAddy = invitee.match(/<(.*)>/)[1]; namePieces = invitee.match(/"(.*)"/)[1].split(" "); if (namePieces.length == 1) { firstName = namePieces[0]; lastName = ""; } else { firstName = namePieces[0]; lastName = namePieces[namePieces.length - 1]; } }; singleAddy = singleAddy.replace(/\s/, ""); if (singleAddy && !cleanEmails(singleAddy)) { alert(singleAddy + ' does not appear to be a valid email. Please fix or replace.'); goodAddys = false; return false; } firstName = firstName.replace(/</, ''); firstName = firstName.replace(/>/, ''); lastName = lastName.replace(/</, ''); lastName = lastName.replace(/>/, ''); var appendString = '' + '' + ''; $("#referral_form fieldset").append(appendString); }); var message = $('#your-message').val(); $('input:hidden#message').val(message); return goodAddys; } function cleanEmails (value) {     // rewritten by Gregory Ramsperger     var validLocalChars = "[-_a-z0-9'+*$^&%=~!\\?{}#/`|]";         var localReStr = "("+validLocalChars+"+?(\\."+validLocalChars+"+)*?)";         var domainReStr = "(([a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?\\.)+[a-z]{2,6}|(\\d{1,3}\\.){3}\\d{1,3})(:\\d+)?";         var m = value.match( new RegExp("^" + localReStr + "@" + domainReStr + "$", "i") );         if( !m ) return false;         if ( !m[1] || m[1].length > 255 || !m[3] || m[3].length > 255 ) return false;         return true; } //initing from calling page return { init: function() { //general setup, shared functions //email message is default for display purposes setcredit_message("default"); $("#credit-choice").change(function() { setcredit_message("default"); }); $('#raf-twitter').click(function() { followers_list.followers = []; displayOverlay("Waiting"); gigya.services.socialize.getUserInfo(conf, {callback:twitterUserInfo}); }); $('#raf-facebook').click(function() { gigya.services.socialize.addConnection(conf,{callback:facebookConnection, provider:'facebook'}); }); $(".import-action").click(function() { doPlaxo(); }); $("#sendMessageId").click(function(){ var followerIds = []; $(".twitterCheck img").each(function() { if ($(this).hasClass("checked")) { var uid = $(this).parent().find("input").val(); followerIds.push(uid); } }); if (followerIds.length != 0) { var today = new Date(); gigya_start_time = today.getTime(); var message = $('#socialMessage').val(); setcredit_message("twitter"); message += ' ' + credit_message; $.ajax({ type : "POST", url : "/social-networks/xml/tweets", data : {twitter_id:gigya_user.UID, message_body:message, recipient_ids:followerIds.toString(), credit_chosen: creditChosen}, success : sendTwitterMessage, error : failTwitterMessage }); } }); $(".twitterCheck").live('mousedown',function(e) { e.preventDefault(); var checkThis = $(this).find("img"); var inputThis = $(this).find("input"); if (checkThis.hasClass("unchecked")) { checkThis.removeClass("unchecked").addClass("checked"); sendMessageHandler(); } else if (checkThis.hasClass("checked")) { checkThis.removeClass("checked").addClass("unchecked"); sendMessageHandler(); } }); $(".twitterSearch").click(function(e){ e.preventDefault(); followersHtml = followersHtml.render(followers_list, followersRfn); }); //email invites (Plaxo widget) function doPlaxo() { $("#invites-textarea").focus(); showPlaxoABChooser('invites-textarea', '/social-networks/plaxo'); } $("#inner-invites").click(function() { $("#invites-textarea").focus(); }); $("#friend-invites").click(function() { $("#invites-textarea").focus(); }); $("#selectAll").click(function(e) { e.preventDefault(); $(".twitterCheck img").each(function() { $(this).removeClass("unchecked"); $(this).addClass("checked"); $("#sendMessageId").removeAttr("disabled"); $("#sendMessageId").removeClass("inactive"); }); }); $("#removeAll").click(function(e) { e.preventDefault(); $(".twitterCheck img").each(function() { $(this).removeClass("checked"); $(this).addClass("unchecked"); $("#sendMessageId").attr("disabled","disabled"); $("#sendMessageId").addClass("inactive"); }); }); $("#viewAll").click(function(e) { e.preventDefault(); var searched = $('.twitterInput').val(); if (searched!='') { $('.twitterInput').val(''); followersHtml = followersHtml.render(followers_list, followersRfn); } $("#followersTable table tbody tr").each(function() { $(this).show(); }); }); $("#viewSelected").click(function(e) { e.preventDefault(); var selectedFollowersList = {followers :[]}; var followerIds = []; $(".twitterCheck img").each(function() { if ($(this).hasClass("checked")) { var uid = $(this).parent().find("input").val(); followerIds.push(uid); } else { $(this).parent().parent().hide(); } }); if (followerIds.length != 0) { $.each(followers_list.followers, function( index, data ) { if ($.inArray(data.twitterUID, followerIds) != -1) { selectedFollowersList.followers.push(data); } }); } }); $("#email-friends-action").click(function(e) { e.preventDefault(); var invites = $("#invites-textarea").val(); if (invites == "" || invites == undefined) { error_message_detail = 'Please enter at least one email address.'; alert(error_message_detail); } else { if(parseEmails(invites)) { $("#referral_key").val($(".ek-"+creditChosen).text()); $('#referral_form').submit(); } } }); } }; });