﻿
function TweetUi() {

    this.tweetData;
    this.container;
    this.twitterForm;
    this.replyContainer;
    this.tweetControls;
    this.clip;
    
    this.copied = false;
    this.tweetThisDialogVisible = false;
    this.replyDialogVisible = false;
    this.repliesContainerVisible = false;
    this.shareDialogVisible = false;
    this.voteDialogVisible = false;
    this.hasTwitterForm = false;

    this.init = function() {

        var parent = this;

        this.tweetData = this.container.metadata({ type: "elem", name: "script" });

        var controls = new TweetControls();
        controls.Subscribe = this.container.find(".coupon-subscribe-link");
        controls.TweetThis = this.container.find(".coupon-tweet-this-link");
        controls.Reply = this.container.find(".coupon-reply-link");
        controls.VoteUp = this.container.find(".coupon-vote-up");
        controls.VoteDown = this.container.find(".coupon-vote-down");
        controls.Share = this.container.find(".coupon-share-link");
        controls.VoteReason = this.container.find(".coupon-vote-reason-btn");
        this.tweetControls = controls;

        // Bind tweet click events
        if (this.tweetData.Curl != "") {
            this.container.click(function() {
                parent.container.append($(document.createElement("img"))
                    .attr("src", parent.tweetData.Curl)
                    .css("display", "none")
                );
            });
        }

        this.tweetControls.Subscribe.click(function() {
            parent.subscribeToProvider(parent.tweetData.ProviderId);
        });
        this.tweetControls.TweetThis.click(function() {
            parent.toggleTweetThisDialog();
        });
        this.tweetControls.Reply.click(function() {
            parent.toggleRepliesContainer();
        });

        this.tweetControls.VoteUp.click(function() {
            if (!$(this).hasClass("coupon-vote-up-inactive")) {
                parent.voteUp();
            }
        });
        this.tweetControls.VoteDown.click(function() {
            parent.voteDown(-1);
        });
        this.tweetControls.Share.click(function() {
            parent.toggleShareDialog();
        });
        this.tweetControls.VoteReason.click(function() {
            parent.toggleReasonsDialog();
        });

        // Bind tweet hover events
        var tweetLink = this.container.find(".coupon-text > a");

        if (this.tweetData.DestinationUrl != "") {

            $(tweetLink).append(
                        $(document.createElement("span"))
                            .addClass("preview-tooltip-link")
                            .html("__")
                            .hover(
                                function() {
                                    parent.showUrlPreview($(this))
                                },
                                function() {
                                    parent.hideUrlPreview();
                                })
                    );
        }

        // Parse bool
        if (this.tweetData.HasReplies == "true") {
            this.tweetData.HasReplies = true;
        }
        else {
            this.tweetData.HasReplies = false;
        }

        var copyElement = this.tweetData.TweetId + "_copy";

        // http://code.google.com/p/zeroclipboard/wiki/Instructions

        if (this.tweetData.CouponCode != "") {
            this.clip = new ZeroClipboard.Client();
            this.clip.setText(this.tweetData.CouponCode);
            this.clip.addEventListener("onMouseOver", function(client) { parent.CodeHoverIn(client); });
            this.clip.addEventListener("onMouseOut", function(client) { parent.CodeHoverOut(client); });
            this.clip.addEventListener("onMouseUp", function(client) { parent.CodeCopied(client); });
            this.clip.glue(copyElement, this.container.attr("id"));
        }
    }

    this.CodeHoverIn = function(client) {
        $(client.domElement).after(
            $(document.createElement("div"))
                .addClass("HoverText")
                .html(!this.copied ? "< Click to Copy and Open Site" : "< Click to Copy")
        );
    }

    this.CodeHoverOut = function(client) {
        $(client.domElement).siblings(".HoverText").remove();
    }

    this.CodeCopied = function(client) {
        if (!this.copied) {
            this.copied = true;
            $(client.domElement).css("background-color", "#FEBF01");
            window.open(this.tweetData.OutboundUrl, '_blank');
        }
    }

    this.appendTwitterForm = function() {

        var parent = this;

        $("#divReplyContainer")
            .clone().appendTo(this.container)
            .attr("id", "");

        $("#divDialogWrapper")
            .clone().appendTo(this.container)
            .attr("id", "");

        var form = new TwitterForm();
        form.Wrapper = this.container.find(".dialog-wrapper");
        form.TextArea = this.container.find(".dialog-textarea");
        form.CharCount = this.container.find(".dialog-char-count");
        form.SubmitButton = this.container.find(".dialog-submit-btn");
        form.UserTextBox = this.container.find(".dialog-username");
        form.PasswordTextBox = this.container.find(".dialog-password");
        form.ValidationSummary = this.container.find(".dialog-valid-summary");
        this.twitterForm = form;

        var replies = new ReplyContainer();
        replies.Wrapper = this.container.find(".replies-container");
        replies.Replies = this.container.find(".replies");
        replies.ReplyButton = this.container.find(".replies-controls-reply");
        this.replyContainer = replies;

        this.twitterForm.SubmitButton.click(function() {
            parent.postDialogForm();
        });
        this.twitterForm.TextArea.keyup(function() {
            charCount(parent.twitterForm.TextArea, parent.twitterForm.CharCount);
        });
        this.replyContainer.ReplyButton.click(function() {
            parent.toggleReplyDialog();
        });

        this.hasTwitterForm = true;
    }

    // Tweet visibility methods
    this.toggleTweetThisDialog = function() {
    
        var parent = this;
        var tweetThisText = "Check out the great " + this.tweetData.ProviderName + " deal I just found on Coupon Tweet " + this.tweetData.ShareUrl;
                
        if (!this.hasTwitterForm) {
            this.appendTwitterForm();
        }

        if (this.repliesContainerVisible || this.replyDialogVisible) {
            this.hideAll();
        }

        if (this.tweetThisDialogVisible) {

            this.twitterForm.Wrapper.slideUp(animeTime);
            $.scrollTo(this.container, scrollTime, { offset: { top: -10, left: 0} });

            this.tweetThisDialogVisible = false;
        }
        else {

            this.twitterForm.Wrapper.slideDown(animeTime, function() {
                parent.twitterForm.TextArea.val(tweetThisText);
                parent.twitterForm.CharCount.html(parent.twitterForm.TextArea.val().length);
            });

            $.scrollTo(this.container, scrollTime, { offset: { top: -10, left: 0} });

            this.tweetThisDialogVisible = true;
        }
    }

    this.toggleRepliesContainer = function() {

        if (!this.hasTwitterForm) {
            this.appendTwitterForm();
        }
    
        if (this.tweetThisDialogVisible) {
            this.hideAll();
        }

        if (this.tweetData.HasReplies && this.repliesContainerVisible) {
            this.hideAll();
        }
        else if (this.tweetData.HasReplies && !this.repliesContainerVisible) {

            this.tweetControls.Reply.addClass("coupon-reply-link-loading");
            
            PageMethods.getReplies(this.tweetData.TweetId, null, this.getReplies_Loaded, this.getReplies_Error, this);
            this.repliesContainerVisible = true;
        }
        else {
            this.toggleReplyDialog();
        }
    }

    this.toggleReplyDialog = function() {

        var parent = this;
        var replyText = "@" + parent.tweetData.TwitterUserName;

        if (!this.hasTwitterForm) {
            this.appendTwitterForm();
        }

        if (this.replyDialogVisible) {

            this.twitterForm.Wrapper.slideUp(animeTime);
            this.replyContainer.ReplyButton.removeClass("reply-controls-reply-active");
            $.scrollTo(this.container, scrollTime, { offset: { top: -10, left: 0} });

            this.replyDialogVisible = false;
        }
        else {

           this.twitterForm.Wrapper.slideDown(animeTime, function() {
                parent.twitterForm.TextArea.val(replyText);
                parent.twitterForm.CharCount.html(parent.twitterForm.TextArea.val().length);
            });

            parent.replyContainer.ReplyButton.addClass("reply-controls-reply-active");

            if (this.repliesContainerVisible) {
                $.scrollTo(this.container, scrollTime, { offset: { top: 200, left: 0} });
            }
            else {
                $.scrollTo(this.container, scrollTime, { offset: { top: -10, left: 0} });
            }

            this.replyDialogVisible = true;
        }
    }

    this.hideAll = function() {

        if (this.tweetThisDialogVisible || this.replyDialogVisible) {
            this.twitterForm.Wrapper.slideUp(animeTime);
            this.tweetThisDialogVisible = false;
            this.replyDialogVisible = false;
        }
        if (this.repliesContainerVisible) {
            this.replyContainer.Wrapper.slideUp(animeTime);
            this.replyContainer.ReplyButton.removeClass("reply-controls-reply-active");
            this.repliesContainerVisible = false;
        }

        this.twitterForm.TextArea.val("");
        $.scrollTo(this.container, scrollTime, { offset: { top: -10, left: 0} });
    }
    
    // Tweet drop down methods
    this.toggleShareDialog = function() {

        var shareDialog = $(".share-container");
        var yOffset = 15;

        var diggUrl = "http://www.digg.com/submit?url=" + this.tweetData.LocalUrl;
        var facebookUrl = "http://www.facebook.com/share.php?u=" + this.tweetData.LocalUrl;
        var mySpaceUrl = "http://www.myspace.com/Modules/PostTo/Pages/?u=" + this.tweetData.LocalUrl;
        var deliciousUrl = "http://delicious.com/save?url=" + this.tweetData.LocalUrl;
        var mixxUrl = "http://www.mixx.com/submit?page_url=" + this.tweetData.LocalUrl;
        
        if (!this.shareDialogVisible) {

            for (var i = 0; i < tweetArray.length; ++i) {
                tweetArray[i].shareDialogVisible = false;
            }

            shareDialog.find(".share-digg").attr("href", diggUrl);
            shareDialog.find(".share-facebook").attr("href", facebookUrl);
            shareDialog.find(".share-myspace").attr("href", mySpaceUrl);
            shareDialog.find(".share-delicious").attr("href", deliciousUrl);
            shareDialog.find(".share-mixx").attr("href", mixxUrl);
            
            shareDialog
                .css({
                    "display": "block",
                    "left": this.container.find(".coupon-share-link").position().left,
                    "top": this.container.find(".coupon-share-link").position().top + yOffset
                });

            this.shareDialogVisible = true;
        }
        else {
            shareDialog.css("display", "none");
            this.shareDialogVisible = false;
        }
    }

    this.toggleReasonsDialog = function() {

        var parent = this;
        var reasonsDialog = $(".vote-reasons-container");
        var reasonBtn = this.container.find(".coupon-vote-reason-btn");
        var xOffset = 18;
        var yOffset = 3;

        if (!this.voteDialogVisible) {

            for (var i = 0; i < tweetArray.length; ++i) {
                tweetArray[i].voteDialogVisible = false;
            }

            reasonsDialog.find("a").each(function() {

                var reasonId = $(this).attr("id");

                $(this)
                    .unbind("click")
                    .click(function() {
                        parent.voteDown(reasonId);
                    });
            });

            reasonsDialog
                .css({
                    "display": "block",
                    "top": reasonBtn.position().top + $(reasonBtn).height() + yOffset,
                    "left": (reasonBtn.position().left - reasonsDialog.width()) + reasonBtn.width() + xOffset
                });

            this.voteDialogVisible = true;
        }
        else {

            reasonsDialog.css("display", "none");
            this.voteDialogVisible = false;
        }
    }

    this.showUrlPreview = function(hoveringLink) {

        var xOffset = -15;
        var yOffset = 0;

        var screenShotContainer = $(".screen-shot-container");
        var screenShotLink = $(".screen-shot-wrapper").find("a");
        var screenShot = $(".screen-shot");
        var destinationUrl = this.tweetData.DestinationUrl;
        var imgSrc = "http://images.websnapr.com/?size=s&key=UrhNdS34AS90&url=" + destinationUrl;

        screenShotLink.attr("href", destinationUrl);

        screenShotContainer
            .css({
                "display": "block",
                "top": hoveringLink.position().top + hoveringLink.height() + yOffset,
                "left": hoveringLink.position().left + xOffset
            })
            .hover
            (
                function() {
                    $(this).css("display", "block");
                },
                function() {
                    $(this).css("display", "none");
                }
            );

        screenShot.css("background-image", "url(" + imgSrc + ")");
    }

    this.hideUrlPreview = function() {
        $(".screen-shot-container").hide();
    }

    // Tweet Subscribe methods
    this.subscribeToProvider = function(providerId) {
    
        if (userIsSubscribed) {
            var sender = this.container.find(".coupon-subscribe-link")[0];
            var left = $(sender).position().left + 6;
            var top = $(sender).position().top - 5;

            var divSubscriptionAddedFader = $(document.createElement('div'))
                                    .addClass("subscription-added-fader")
                                    .css({ top: top, left: left })
                                    .append(document.createTextNode('Subscribed'))
                                    .appendTo('body')
                                    .fadeOut(3500, function() {
                                        $(this).remove();
                                    });

            $(sender).css("visibility", "hidden");
                                    
            PageMethods.AddSubscriptionDetail(subscriptionUser, "provider", providerId, this.AddSubscriptionDetail_Added, this.AddSubscriptionDetail_Error, this);
        }
        else {
            $("#ModalTargetTitle").html(this.tweetData.ProviderName);
            modalDialog.width = 300;
            modalDialog.subscriptionData = providerId;
            modalDialog.subscriptionDataType = "provider";
            modalDialog.toggleVisibility("divSubscribe");
        }
    }

    // Tweet form methods
    this.postDialogForm = function() {
        
        var dialogFormValid = true;

        if (!validateRequiredField(this.twitterForm.UserTextBox) | !validateRequiredField(this.twitterForm.PasswordTextBox) | !validateTweetField(this.twitterForm.TextArea)) {
            $(this.twitterForm.ValidationSummary)
                .show()
                .html("Your Twitter Username, Password, and a Tweet are required.");
            dialogFormValid = false;
        }

        if (dialogFormValid) {

            $(this.twitterForm.ValidationSummary).hide();
            
            if (this.tweetThisDialogVisible) {
                PageMethods.PostToTwitter(this.tweetData.TweetId, this.twitterForm.UserTextBox.val(), this.twitterForm.PasswordTextBox.val(), this.twitterForm.TextArea.val(), "Retweet", this.PostToTwitter_Posted, this.PostToTwitter_Error, this);
            }
            else {
                PageMethods.PostToTwitter(this.tweetData.TweetId, this.twitterForm.UserTextBox.val(), this.twitterForm.PasswordTextBox.val(), this.twitterForm.TextArea.val(), "Reply", this.PostToTwitter_Posted, this.PostToTwitter_Error, this);
            }
            
            this.twitterForm.Wrapper.find(".dialog").css("display", "none");
            this.twitterForm.Wrapper.find(".dialog-loading").css("display", "block");
        }
    }

    // Tweet voting methods
    this.voteUp = function() {
        var voteTotal = parseInt(this.container.find(".vote-total").html());

        this.container.find(".coupon-vote-up").addClass("coupon-vote-up-inactive");
        this.container.find(".coupon-vote-down").addClass("coupon-vote-down-change");

        this.container.find(".coupon-vote-up").unbind("click");

        this.container.find(".vote-total").fadeOut(500, function() {
            $(this).html(voteTotal + 1);
            $(this).fadeIn(500);
        });

        PageMethods.PostVote(this.tweetData.TweetId, 0, GetIp(), this.PostVote_Posted, this.PostVote_Error, this);
    }

    this.voteDown = function(voteReason) {

        this.toggleReasonsDialog();

        if (this.tweetThisDialogVisible || this.replyDialogVisible) {
            this.twitterForm.Wrapper.hide();
        }
        if (this.repliesContainerVisible) {
            this.replyContainer.Wrapper.hide();
        }

        this.container.find(".coupon-text > a > span")
            .removeClass()
            .html("");

        this.container.find(".coupon-tool-list").hide();
        this.container.find(".coupon-controls-wrapper").hide();
        this.container.find(".coupon-avatar").fadeTo(1, 0.25);
        this.container.find(".coupon-body").addClass("body-downvoted");
        this.container.find(".coupon-user-link").css("color", "#ADAD91");
        this.container.find(".coupon-time").css("color", "#ADAD91");
        this.container.find(".coupon-subscribe-link").hide();

        PageMethods.PostVote(this.tweetData.TweetId, voteReason, GetIp(), this.PostVote_Posted, this.PostVote_Error, this);
    }

    // Page method success methods
    this.getReplies_Loaded = function(result, Tweet) {

        Tweet.replyContainer.Replies.html("");

        for (var i in result) {
            Tweet.replyContainer.Replies
                .append
                (
                    $(document.createElement("div"))
                    .addClass("comment-wrapper")
                    .append(
                        $(document.createElement("a"))
                        .attr({
                            "href": "http://www.twitter.com/" + result[i].TwitterUserName,
                            "target": "blank"
                        })
                        .append(
                            $(document.createElement("img"))
                            .addClass("comment-avatar")
                            .attr({
                                "src": result[i].TwitterUserImageUrl
                            })
                        )
                    )
                    .append(
                        $(document.createElement("div"))
                            .addClass("comment-carrot")
                    )
                    .append(
                        $(document.createElement("div"))
                        .addClass("comment-body")
                        .append(
                            $(document.createElement("p"))
                                .append(
                                    $(document.createElement("a"))
                                    .addClass("comment-user-link")
                                    .attr({
                                        "href": "http://www.twitter.com/" + result[i].TwitterUserName,
                                        "target": "blank"
                                    })
                                    .html(result[i].TwitterUserName)
                                )
                                .append(
                                    document.createTextNode(" - " + result[i].TweetText)
                                )
                            )
                        .append(
                            $(document.createElement("p"))
                            .append(
                                $(document.createElement("span"))
                                    .addClass("comment-time-info")
                                    .html(result[i].TweetTime)
                            )
                        )
                    )
                );
        }

        Tweet.replyContainer.Wrapper.slideDown(animeTime, function() {
            Tweet.tweetControls.Reply.removeClass("coupon-reply-link-loading");
        });

        $.scrollTo(Tweet.container, scrollTime, { offset: { top: -10, left: 0} });
    }

    this.PostVote_Posted = function(result) {
    }

    this.PostToTwitter_Posted = function(result, Tweet) {

        Tweet.twitterForm.Wrapper.find(".dialog").css("display", "block");
        Tweet.twitterForm.Wrapper.find(".dialog-loading").css("display", "none");

        if (Tweet.tweetThisDialogVisible) {

            Tweet.hideAll();
            Tweet.container.find(".coupon-tweet-this-link").html("Tweeted!");
        }
        else {
        
            Tweet.hideAll();
            
            Tweet.replyContainer.Wrapper.find(".comment-wrapper").size() == 0 ? Tweet.tweetControls.Reply.html("1 reply") : Tweet.tweetControls.Reply.html((commentCount + 1) + " replies");

            Tweet.hasReplies = true;
            Tweet.toggleRepliesContainer();
        }
    }

    this.AddSubscriptionDetail_Added = function(result, tweet) {
        if (result) {
            modalDialog.addRows(result);
        }
    }

    // Page method error methods
    this.getReplies_Error = function() {
    }

    this.PostVote_Error = function() {
    }

    this.PostToTwitter_Error = function(error, Tweet) {

        Tweet.twitterForm.Wrapper.find(".dialog").css("display", "block");
        Tweet.twitterForm.Wrapper.find(".dialog-loading").css("display", "block");

        if (error._message.indexOf("401") != -1) {

            $(Tweet.twitterForm.ValidationSummary)
                .show()
                .html("Your Twitter username or password was incorrect.");
                
            Tweet.twitterForm.UserTextBox.css("background-color", invalidColor);
            Tweet.twitterForm.PasswordTextBox.css("background-color", invalidColor);
        }
        else {

            $(Tweet.twitterForm.ValidationSummary)
                .show()
                .html("There was an error submitting to Twitter, please try again.");
        }
    }

    this.AddSubscriptionDetail_Error = function() {
    }
}

function TweetControls() {
    this.Subscribe;
    this.TweetThis;
    this.Reply;
    this.VoteUp;
    this.VoteDown;
    this.Share;
    this.VoteReason;
}

function TwitterForm() {
    this.Wrapper;
    this.TextArea;
    this.CharCount;
    this.SubmitButton;
    this.UserTextBox;
    this.PasswordTextBox;
    this.ValidationSummary;
}

function ReplyContainer() {
    this.Wrapper;
    this.Replies;
    this.ReplyButton;
}
