$(function() {

    function twitterButton(link) {
        var src = 'http://platform.twitter.com/widgets/tweet_button.html?'
        src += encodeURI("via=paper_c");
        src += encodeURI("&related=paper_c:PaperC");
        src += encodeURI("&text=I'm on the list for PaperC - closed beta ... use this link for early access:");
        src += "&url=" + encodeURIComponent(link);
        src += encodeURI("&count=none");

        // Build twitter button
        var $iframe = $('<iframe></iframe>');
        $iframe.attr('allowtransparency', 'true');
        $iframe.attr('frameborder','0');
        $iframe.attr('scrolling','no');
        $iframe.attr('style','width:130px; height:20px;');
        $iframe.attr('src', src);
        return $iframe
    }

    function setFacebookButton(link) {
        var href = 'http://www.facebook.com/sharer.php?';
        href += 'u=' + encodeURIComponent(link);
        href += encodeURI('&t=PaperC - closed beta');
        $('a[name="fb_share"]').attr('href', href);
    }

    PaperC.Forms.ajaxify($('#signForInviteForm'), function(data, textStatus, jqXHR) {
        var $frame, $trackingId, $socialButtons, url, data, trackingId, link;
        data = JSON.parse(data);
        trackingId = data['tracking_id'];
        $socialButtons = $('#socialButtons');

        if (trackingId !== undefined) {
            // success
            url = 'http://' + window.location.host + '/';
            
            link = url + trackingId + '/';
            $('#personalLink').val(link);
            $frame = $('#thanksForInvite');
            $socialButtons.append(twitterButton(link));
            setFacebookButton(link);

            $('#signForInvite').fadeOut(150, function() {                
                $frame.fadeIn(150);
            });
        } else {
            // Remove the old error list
            $('.errorlist').fadeOut(150, function() {

                // Create a new error list
                var $errorList = $('<ul class="errorlist"></ul>');
                    $errorList.css('display:none;');

                // Append li's for each error from the server
                $.each(data, function(key, error){
                    $errorList.append('<li class="error">' + error + '</li>')
                });

                // Display the error list under the submit button
                $(this).replaceWith($errorList);
                $errorList.fadeIn(150);
            });
        }
    });
});

