﻿
        // Config
        var scrollTime = 400;
        var animeTime = 600;
        var searchTxt = "Store name, keyword, or category";
        var invalidColor = "#E4573F";
        var validColor = "#736765";
        var userIsSubscribed = false;
        var subscriptionUser = null;
        
        // Global tweet array
        var tweetArray = new Array();
        
        // Page events
        $(document).ready(function() {

            $(".tweetContainer").each(function(i) {
                tweetArray[i] = new TweetUi();
                tweetArray[i].container = $(this);
                tweetArray[i].init();
            });

            // Set userIsSubscribed
            if (!$("#SubscriptionUser").html().replace("\n", "").trim() == "") {
                userIsSubscribed = true;
            }

            CreateIpCookie();

            subscriptionUser = $("#SubscriptionUser").html();

            // Bind modal clicks
            $(".modal-overlay").click(function() {
                modalDialog.toggleVisibility();
            });
            $(".modal-close-btn").click(function() {
                modalDialog.toggleVisibility();
            });
            $(".subscribe-button").click(function() {
                modalDialog.submitSubscribe($(this).parent().find(".email-field"));
            });
            $(".confirmed-link").click(
                function() {
                    $(".resend-tooltip-container")
                        .css(
                            {
                                "top": $(".confirmed-link").position().top + 15,
                                "left": $(".confirmed-link").position().left
                            }
                        )
                        .show();
                }
            );
            $(".validation-close-btn").click(function() {
                $(this).parent().parent().hide();
            });
            $(".resend-tooltip-close-btn").click(function() {
                $(this).parent().parent().hide();
            });
            $(".resend-link").click(function() {
                modalDialog.resendConfirmation();
            });
            $(".email-field").bind("keydown", (function(e) {
                var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
                if (key == 13) {
                    modalDialog.submitSubscribe($(this));
                    return false;
                }
            }));
            $(".subscription-mgmt-done-btn").click(function() {
                modalDialog.toggleVisibility();
            });
            $(".unsubscribe-link").click(function() {
                modalDialog.deleteSubscription($(this).attr("id"), $(this).parent().parent().parent());
            });
            $(".modal-wrapper").click(function(e) {
                var $clicked = $(e.target);
                if ($clicked.is(".resend-tooltip-container") || $clicked.parents().is(".resend-tooltip-container") || $clicked.is(".confirmed-link")) {
                }
                else {
                    $(".resend-tooltip-container").hide();
                }
            });

            if (userIsSubscribed) {
                $("#SubManagerLink").click(function() {
                    modalDialog.width = 400;
                    modalDialog.subscriptionData = null;
                    modalDialog.subscriptionDataType = null;
                    modalDialog.toggleVisibility("divSubscriptionManagement");
                });
            }
            else {
                $("#SubManagerLink").click(function() {
                    modalDialog.width = 300;
                    modalDialog.subscriptionData = 1;
                    modalDialog.subscriptionDataType = "newsletter";
                    modalDialog.toggleVisibility("divNewsletterSubscribe");
                });
            }

            // Set search input on focus and on blur
            $("#searchtxt").attr({ value: searchTxt }).focus(function() {
                if ($(this).val() == searchTxt) {
                    $(this).val("");
                }
            }).blur(function() {
                if ($(this).val() == "") {
                    $(this).val(searchTxt);
                }
            });

            // Bind document click events
            $(document).bind("click", function(e) {

                var $clicked = $(e.target);

                // This is retarded, agreed
                if ($clicked.is("#liveSearchResults") || $clicked.parents().is("#liveSearchResults") || $clicked.is("#searchtxt")) {

                    for (var i = 0; i < tweetArray.length; ++i) {
                        tweetArray[i].shareDialogVisible = false;
                    }
                    for (var i = 0; i < tweetArray.length; ++i) {
                        tweetArray[i].voteDialogVisible = false;
                    }

                    $(".share-container").css("display", "none");
                    $(".vote-reasons-container").css("display", "none");
                }
                else if ($clicked.is(".share-container") || $clicked.parents().is(".share-container") || $clicked.is(".coupon-share-link")) {
                    $("#liveSearchResults").css("display", "none");

                    for (var i = 0; i < tweetArray.length; ++i) {
                        tweetArray[i].voteDialogVisible = false;
                    }

                    $(".vote-reasons-container").css("display", "none");
                }
                else if ($clicked.is(".vote-reasons-container") || $clicked.parents().is(".vote-reasons-container") || $clicked.is(".coupon-vote-reason-btn")) {
                    $("#liveSearchResults").css("display", "none");

                    for (var i = 0; i < tweetArray.length; ++i) {
                        tweetArray[i].shareDialogVisible = false;
                    }

                    $(".share-container").css("display", "none");
                }
                else {

                    for (var i = 0; i < tweetArray.length; ++i) {
                        tweetArray[i].shareDialogVisible = false;
                    }
                    for (var i = 0; i < tweetArray.length; ++i) {
                        tweetArray[i].voteDialogVisible = false;
                    }

                    $("#liveSearchResults").css("display", "none");
                    $(".share-container").css("display", "none");
                    $(".vote-reasons-container").css("display", "none");
                }
            });

            // TweetList footer click events
            $(".list-footer-add-coupon-link").click(function() {
                if ($(".empty-page-dialog").css("display") == "none") {
                    $(".empty-page-dialog").slideDown(animeTime);
                }
                else {
                    $(".empty-page-dialog").slideUp(animeTime);
                }
            });

            $(".list-footer-new-search-link").click(function() {
                $.scrollTo({ top: 0, left: 0 }, 600, { onAfter: function() {
                    $("#searchtxt").focus();
                }
                });
            });

            // Apply background images to prevent flicker
            $("html").css("background-image", "url('/images/bg-scene-extension.gif')");
            $("body").css("background-image", "url('/images/bg-scene.gif')");

            // Setup Promotional modal links
            $("#AutoTweetLink").click(function() {
                modalDialog.width = 400;
                modalDialog.subscriptionData = null;
                modalDialog.subscriptionDataType = null;
                modalDialog.toggleVisibility("divAutoTweet");
            });

            $(".tweetit-button").click(function() {

                function PostToTwitter_Success(result) {
                    $("#twtResult").html(result.Message);
                }

                function PostToTwitter_Error(result) {
                    $("#twtResult").html("Your login information was not correct; please try again.");
                }

                $("#twtResult").show().html("submitting...");

                PageMethods.PostToTwitter($("#twtUsername").val(), $("#twtPassword").val(), $("#twtTweet").html(), PostToTwitter_Success, PostToTwitter_Error);
            });
        });
        
        window.onload = function () {
            $(".coupon-avatar").each(function() {
                if (imageCheck(this) == false) {
                    $(this).attr("src", "http://static.twitter.com/images/default_profile_normal.png");
                }
            });
        }

        // Page utility methods
        function CreateSubscriptionCookie(username) {
            var expireDate = new Date();
            expireDate.setDate(expireDate.getDate() + 365);

            var cookie = "CouponTweetSubscriptionUser=" + username + ";path=/; expires=" + expireDate.toGMTString();

            document.cookie = cookie;
        }

        function CreateIpCookie() {
            var expireDate = new Date();
            expireDate.setDate(expireDate.getDate() + 365);

            var cookie = "CouponTweetIpAddress=" + GetClientIp() + ";path=/; expires=" + expireDate.toGMTString();

            document.cookie = cookie;
        }

        function charCount(textArea, displaySpan) {
            $(displaySpan).html(140 - $(textArea).val().length);
        }
        
        function imageCheck(img) {
            if (!img.complete) {
                return false;
            }
            if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
                return false;
            }
            return true;
        }
        
        function encodeHtml(str)
        {
           var div = document.createElement('div');
           var text = document.createTextNode(str);
           div.appendChild(text);
           return div.innerHTML;
        }
        
        // Live search methods
        function doSearch() {
            var searchTerms = $("#searchtxt").val().trim();

            // Trim trailing spaces
            
            if (searchTerms == searchTxt || !isValidSearch(searchTerms)) {
                return true;
            }
            else {
                window.location = "/coupons/search/" + encodeURIComponent(searchTerms) + "/";
            }
        }

        String.prototype.trim = function() {
            return this.replace(/^\screen+/, '').replace(/\screen+$/, '');
        }

        function isValidSearch(text) {
            if (text == "")
                return false;
            for (var i = 0; i < text.length; ++i) {
                if (text.toString().charAt(i) != ' ') {
                    return true;
                }
            }
            return false;            
        }

        var searchBusy = false

        function liveSearch(qString) {
            if (qString == "") {
                // Hide result container
                $("#liveSearchResults").css("display", "none");
            }
            else if (searchBusy == false) {
                // Show result container
                $("#liveSearchResults").css("display", "block");
                // Perform search via web method
                searchBusy = true
                PageMethods.getLiveSearchResults(encodeHtml(qString), getLiveSearchResults_Success, getLiveSearchResults_Error, null);
            }
        }

        function getLiveSearchResults_Success(result, userContext, methodName) {
            // Display in results container
            searchBusy = false
            $("#liveSearchResults").html(result);
            $("#liveSearchResults > ul > li > a").mouseover(function() {
                $(this).addClass("searchHover");
            });
            $("#liveSearchResults > ul > li > a").mouseout(function () {
                $(".searchHover").removeClass("searchHover");
                $(this).removeClass("searchHover");
            });
        }
        
        function getLiveSearchResults_Error(errors, userContext, methodName) {
            //alert(errors._message);
        }

        function submitarrow(myfield, e) {
                   var keycode;

            if (window.event)
                keycode = window.event.keyCode;
            else if (e)
                keycode = e.which;
            else
                return true;
            if(keycode == 38) {
                // UP arrow was pressed
                
                var $current = $(".searchHover");
                $current.removeClass("searchHover");
                
                var $parent = $current.parent();
                var $next = $parent.prev();
                
                // We're at the beginning of a set - traverse up, over, then back down the DOM to find
                // either more elements or nothing
                if($next.length == 0) {
                
                    $parent = $parent.parent().prev().prev();
                    
                    if($parent.length == 0) {
                        // We're at the beginning of the list; do nothing - no rows should be highlighted
                        return;
                    }
                    else {
                        // We're now at a different set of rows. Get the last row in the set so that
                        // it will be traversed upward.
                        $next = $parent.children(":last");
                    }
                }
                
                $next.children().addClass("searchHover");
                
                return;
            } else if (keycode == 40) {
                // DOWN arrow was pressed
                
                var $current = $(".searchHover");
                $current.removeClass("searchHover");
                
                if($current.length == 0) {
                    // No row is currently highlighted. Highlight the first row.
                    $currNode = $("#liveSearchResults");
                    $currNode = $currNode.children(":first").next().children(":first").children().addClass("searchHover");
                    return;
                }
                
                var $parent = $current.parent();
                var $next = $parent.next();
                
                // We're at the beginning of a set - traverse up, over, then back down the DOM to find
                // either more elements or nothing
                if($next.length == 0) {
                
                    $parent = $parent.parent().next().next();
                    
                    if($parent.length == 0) {
                        // We're at the end of the list; keep the last row highlighted
                        $current.addClass("searchHover");
                        return;
                    }
                    else {
                        // We're now at a different set of rows. Get the first row in the set so that
                        // it will be traversed downward.
                        $next = $parent.children(":first");
                    }
                }
                
                $next.children().addClass("searchHover");
                return;
            }
            return;
        }

        function submitenter(myfield, e) {
            var keycode;

            if (window.event)
                keycode = window.event.keyCode;
            else if (e)
                keycode = e.which;
            else
                return true;

            if(keycode == 13) {
                // Enter/return was pressed
                
                // First, check to see if a row in the livesearch is highlighted
                var $node = $(".searchHover");
                if($node.length != 0) {
                    // Something is highlighted - use that link rather than the current search terms.
                    window.location = $node.attr("href");
                    return false;
                }
                
                doSearch();
                return false;
            }
            else if(keycode < 37 || keycode > 40) {
                liveSearch($("#searchtxt").val())
                return;
            }
        }
        
        function liveSearchHover(source) {
            alert(source);
        }
        
        function tweetLinkCallback(tid) {
            PageMethods.linkCallback(tid);
        }

        function GetIp() {
            var clientIp = 'IP Unresolved';
            if (typeof GetClientIp == 'function') {
                clientIp = GetClientIp();
            }
            return clientIp;
        }

        // Empty page, post coupon
        function validateRequiredField(inputField) {

            if ($(inputField).val() == "") {
                $(inputField).css("background-color", invalidColor);
                return false;
            }
            else {
                $(inputField).css("background-color", validColor);
                return true;
            }
        }

        function validateTweetField(inputField) {

            if ($(inputField).val().length > 140 || $(inputField).val() == "") {
                $(inputField).css("background-color", invalidColor);
                return false;
            }
            else {
                $(inputField).css("background-color", validColor);
                return true;
            }
        }
        
        function postCoupon(submitBtn, providerId) {

            var container = $(submitBtn).parents().filter(".empty-page-dialog");
            
            var userText = $(container).find(".dialog-username");
            var passwordText = $(container).find(".dialog-password");
            var tweetText = $(container).find(".dialog-textarea");

            var dialogFormValid = true;

            if (!validateRequiredField(userText) | !validateRequiredField(passwordText) | !validateTweetField(tweetText)) {
                dialogFormValid = false;
                $(container).find(".dialog-valid-summary").html("Your Twitter Username, Password, and a Coupon are required.");
            }

            if (dialogFormValid) {
                PageMethods.PostCoupon($(userText).val(), $(passwordText).val(), $(tweetText).val(), providerId, postCoupon_Posted, postCoupon_Error, container);
                $(container).find(".empty-page-dialog-controls").css("display", "none");
                $(container).find(".empty-page-dialog-loading").css("display", "block");
            }
        }

        function postCoupon_Posted(result, container) {
            window.location = result;
        }

        function postCoupon_Error(error, container) {

            $(container).find(".empty-page-dialog-controls").css("display", "block");
            $(container).find(".empty-page-dialog-loading").css("display", "none");

            var validSummary = $(container).find(".dialog-valid-summary");

            if (error._message.indexOf("401") != -1) {

                $(validSummary)
                .show()
                .html("Your Twitter username or password was incorrect.");

                $(container).find(".dialog-username").css("background-color", invalidColor);
                $(container).find(".dialog-password").css("background-color", invalidColor);
            }
            else {

                $(validSummary)
                .show()
                .html("There was an error submitting to Twitter, please try again.");
            }
        }

//        function facebookPostLink(url, title) {
//            url = encodeURIComponent(url);
//            title = encodeURIComponent(title);
//            window.open('http://www.facebook.com/sharer.php?u='+url+'&t='+title,'sharer','toolbar=0,status=0,width=626,height=436');
//            return false;
        //        }
