var defaultPostedBy = "Anonymous Lemonaide";  //Default user name
var maxLength = 300; //Maximum input length for textarea
var addBoxVisible = false;
var months = new Array();
months[01] = "January";
months[02] = "February";
months[03] = "March";
months[04] = "April";
months[05] = "May";
months[06] = "June";
months[07] = "July";
months[08] = "August";
months[09] = "September";
months[10] = "October";
months[11] = "November";
months[12] = "December";

$(document).ready(function() {
    //wire up the word counter
    lemons.updateWordCount();

    $("textarea").keyup(function() {
        if ($(this).val().length > lemons.maxLemonLength) {

            $("#mylemoncount").addClass("over");
        } else {

            $("#mylemoncount").removeClass("over");
        }
        lemons.updateWordCount();
    });

    //wire up the submit button
    $("input#add").click(function() {
        if (!lemons.overWordCount) {
            lemons.addLemon();
        } else {
            $("#mylemoncount").effect("highlight", { color: "#FF0000" }, 2000);
            $("p.error").html("Whoops! Your story can only be 500 characters or fewer.").show();
        }
    });

    //wire up the search button
    $("input#dosearch").click(function() {
        if ($("input.searchbox").val() != "") {
            lemons.sortType = "search";
            $("span#sorting a").removeClass("active");
            lemons.refreshFullList();

        } else {
            if (lemons.sortType == "search") {
                $("a#sortrecent").click();
            }
        }
    });

    //wire up the form display button
    $("#addbutton").click(function() {
        if (!addBoxVisible) {
            $("#addbox").show("blind");
        }
        else {
            $("#addbox").hide("blind");
        }
        addBoxVisible = !addBoxVisible;
    });

    $("input#postedby").val(defaultPostedBy)
						.addClass("postedbydefault")
						.focus(function() {
						    var iptPostedBy = $(this);
						    if (iptPostedBy.val() == defaultPostedBy)
						        iptPostedBy.val("");
						    iptPostedBy.removeClass("postedbydefault");

						})
						.blur(function() {
						    var iptPostedBy = $(this);
						    if (iptPostedBy.val() == "" || iptPostedBy.val() == defaultPostedBy) {
						        iptPostedBy.addClass("postedbydefault");
						        iptPostedBy.val(defaultPostedBy);

						    }
						});


    //sorting
    $("a#sortpopular").click(function(e) {
        e.preventDefault();
        lemons.sortType = "popular";
        $("span#sorting a").removeClass("active");
        $(this).addClass("active");
        $("input.searchbox").val("");
        lemons.refreshFullList();
    });

    $("a#sortrecent").click(function(e) {
        e.preventDefault();
        lemons.sortType = "default";
        $("span#sorting a").removeClass("active");
        $(this).addClass("active");
        $("input.searchbox").val("");
        lemons.refreshFullList();
    });

    if (lemons.sortType == "popular") {
        $("a#sortpopular").addClass("active");
    } else {
        $("a#sortrecent").addClass("active");
    }



    lemons.grabTemplateNode();
    lemons.lastLemon = lemons.getLastLemon(); //capture the last lemon to be added


    lemons.updateWordCount();
    lemons.flickr.getPhotos();

    $("a.external").bind("click", function(e) {
        e.preventDefault();
        window.open($(this).attr("href"));
    });
    $("a.external").each(function() { $(this).addClass("linked"); });

    // Tweetstream: load latest tweets
    lemons.twitter.loadTweets();

    // Make sure document isn't loaded already scrolled to the bottom
    if ($(window).scrollTop() == $(document).height() - $(window).height()) {
        window.scrollBy(0, -20);
    }

    // Scroll event handler: load more stories when user gets to the bottom of the page
    $(window).scroll(function() {
        if ($(window).scrollTop() == $(document).height() - $(window).height()) {
            lemons.getMoreLemons();
        }
    });

    lemons.canLoad = true;
    var url = (document.URL);
    if (url.indexOf("#") > -1) {

        var idhash = url.split("#")[1];
        var lemonid = idhash.slice(2);
        if (lemonid.length > 0) {
            $("input.searchbox").val("id:" + lemonid);
            $("input#dosearch").click();
        }

    } else {
        lemons.updateLemons('sortby');
    }

});

//FlickrPics
function jsonFlickrFeed(feed) {
     lemons.flickr.showPhotos(feed);
}



var lemons = {
    lastLemon: 0,
    startAt: 1,
    pageSize: 0, // will be overwritten by server-side value
    cachedXml: null, // will be overwritten by server-side value
    canLoad: false,
    lemonUpdateInterval: 30000,
    maxLemonLength: 500,
    overWordCount: false,
    lemonTimer: null,
    sortType: "default",
    lemonNode: null,
    updateLemons: function() {
        clearTimeout(lemons.lemonTimer);
        $.ajax({
            type: "POST",
            url: "GetList.aspx",
            data: {
                guid: "",
                sortby: lemons.sortType,
                startat: 1,
                cache: false
            },
            success: function(data) {
                $("lemon", data).each(function() {
                    var newitems = Array();
                    if (parseInt($("id", this).text()) > lemons.lastLemon) {
                        $("div#lemonaid ul").prepend(lemons.generateLemon($("id", this).text(), $("post", this).text(), $("postedby", this).text(), $("dateposted", this).text()));
                        newitems.push($("id", this).text());
                    }
                    for (var i = 0; i < newitems.length; i++) {
                        $("li#lemon" + newitems[i]).effect("highlight", {}, 3000);
                    }
                });

                lemons.lastLemon = lemons.getLastLemon();
                lemons.attachListeners();
                lemons.facebook.parse();
                if (lemons.sortType == "default") lemons.lemonTimer = setTimeout("lemons.updateLemons()", lemons.lemonUpdateInterval);
            },
            error: function(data, xml) {
                //TODO: display error
                //alert("error: " + xml);


            }
        });
    },
    renderAllLemons: function() {
        clearTimeout(lemons.lemonTimer);
        $.ajax({
            type: "POST",
            url: "GetList.aspx",
            data: {
                guid: "",
                sortby: lemons.sortType,
                startat: 1,
                searchstring: $("input.searchbox").val(),
                cache: true
            },
            success: function(data) {
                // Refresh paging variables
                lemons.cachedXml = $("DocumentElement", data).attr("id");
                lemons.canLoad = true;
                lemons.startAt = 1;

                if ($("lemon", data).length == 0) {
                    $("div#lemonaid ul").append("<li>Sorry, no lemons were found. Add one above!</li>");
                }

                $("lemon", data).each(function() {
                    var newitems = Array();
                    $("div#lemonaid ul").append(lemons.generateLemon($("id", this).text(), $("post", this).text(), $("postedby", this).text(), $("dateposted", this).text()));
                });


                lemons.lastLemon = lemons.getLastLemon();
                lemons.attachListeners();
                lemons.facebook.parse();
                if (lemons.sortType == "default") lemons.lemonTimer = setTimeout("lemons.updateLemons()", lemons.lemonUpdateInterval);
            },
            error: function(data) {
                //TODO: display error
                alert("error: " + data);
            }
        });
    },
    getMoreLemons: function() {

        if (lemons.canLoad) {
            $.ajax({
                type: "POST",
                url: "GetList.aspx",
                data: {
                    guid: lemons.cachedXml,
                    sortby: lemons.sortType,
                    startat: lemons.startAt + lemons.pageSize,
                    cache: true
                },
                beforeSend: function() {
                    lemons.canLoad = false;
                    clearTimeout(lemons.lemonTimer);
                    $("li.lemonError").fadeOut("fast", function() {
                        $("div#lemonaid ul").append("<li class=\"lemonLoader\"><img src=\"images/g_spinner_more.gif\" /></li>");
                    });
                },
                complete: function() { },
                success: function(data) {
                    // Using a function assigned to a variable to avoid chaining duplicate callbacks
                    $("div#lemonaid ul>li.lemonLoader").fadeOut("fast", lemons.pagingAppend(data));
                },
                error: function(data) {
                    /*
                    $("div#lemonaid ul").append("<li class=\"lemonError\">An error occured. Click here to try again.</li>");
                    $("li.lemonError").click(function() {
                    lemons.canLoad = true;
                    lemons.getMoreLemons();
                    });
                    */
                }
            });
        }

    },
    pagingAppend: function(data) {
        if ($("lemon", data).length > 0) {
            lemons.cachedXml = $("DocumentElement", data).attr("id");
            $("lemon", data).each(function() {
                var newitems = Array();
                $("div#lemonaid ul").append(lemons.generateLemon($("id", this).text(), $("post", this).text(), $("postedby", this).text(), $("dateposted", this).text()));
            });

            lemons.attachListeners();
            lemons.facebook.parse();

            lemons.startAt = lemons.startAt + lemons.pageSize;
            lemons.canLoad = true;
        }

        if (lemons.sortType == "default") lemons.lemonTimer = setTimeout("lemons.updateLemons()", lemons.lemonUpdateInterval);
    },
    grabTemplateNode: function() {
        lemons.lemonNode = $("li.lemon:first").clone();
    },
    generateLemon: function(lemonid, post, postedby, dateposted, fromfacebook, facebookuid) {
        var lemonclone = $(lemons.lemonNode).clone();
        lemonclone.attr("id", "lemon" + lemonid);
        $("a.vote", lemonclone).attr("id", "vote" + lemonid);
        $("a.report", lemonclone).attr("id", "report" + lemonid);
        $("div.entry h2", lemonclone).html(postedby);
        $("div.entry p:not(.date)", lemonclone).html(post);
        $("a#twitterlink", lemonclone).attr("href", "http://twitter.com/home?status=http%3A%2F%2Fembracethelemon.com%2F%23id" + lemonid + "%20");
        $("a#facebooklink", lemonclone).attr("href", "http://www.facebook.com/sharer.php?u=http%3a%2f%2fembracethelemon.com%2f%23id" + lemonid + "&amp;t=Embrace+The+Lemon");
        $("a#deliciouslink", lemonclone).attr("href", "http://del.icio.us/save?v=3&amp;url=http%3a%2f%2fembracethelemon.com%2f%23id" + lemonid + "&amp;title=Embrace+The+Lemon");
        $("a#digglink", lemonclone).attr("href", "http://digg.com/submit?url=http%3a%2f%2fwww.embracethelemon.com%2f%23id" + lemonid + "&amp;title=Embrace+The+Lemon&amp;bodytext=DESCRIPTION&amp;media=news");
        var year = dateposted.slice(0, 4);
        var month = dateposted.slice(5, 7);
        var day = dateposted.slice(8, 10);
        $("div.entry p.date", lemonclone).html("posted on " + months[parseInt(month)] + " " + day + ", " + year);

        return lemonclone;
    },
    attachListeners: function() {
        $("div.voting a.vote:not(.linked)").one("click", function(e) {
            e.preventDefault();
            lemons.addVote($(this).parents("li").attr("id").slice(5));
        });
        $("div.voting a.vote:not(.linked)").each(function() { $(this).addClass("linked"); });

        $("div.voting a.report:not(.linked)").one("click", function(e) {
            e.preventDefault();
            lemons.addReport($(this).parents("li").attr("id").slice(5));
        });
        $("div.voting a.report:not(.linked)").each(function() { $(this).addClass("linked"); });

        $("a.showshare:not(.linked)").bind("click", function(e) {
            e.preventDefault();
            if ($(this).hasClass("showing")) {
                $(this).next().hide();
                $(this).removeClass("showing");

            }
            else {
                $(this).next().show();
                $(this).addClass("showing");

            }
        });
        $("a.showshare:not(.linked)").each(function() { $(this).addClass("linked"); });

        $("div.sharelinks a:not(.linked)").bind("click", function(e) {
            e.preventDefault();
            window.open($(this).attr("href"));
        });
        $("div.sharelinks a:not(.linked)").each(function() { $(this).addClass("linked"); });
    },
    refreshFullList: function() {
        lemons.clearLemons();
        lemons.renderAllLemons();
    },
    clearLemons: function() {
        $("div#lemonaid ul").html("");
        lemons.lastLemon = 0;
    },
    updateWordCount: function() {
        var lemontext = $("textarea").val();
        var charleft = (lemons.maxLemonLength - lemontext.length);
        $("span#mylemoncount").html(charleft);
        lemons.overWordCount = (lemontext.length > lemons.maxLemonLength);
    },
    getLastLemon: function() {
        if ($("div#lemonaid ul li:first").attr("id")) {
            return $("div#lemonaid ul li:first").attr("id").slice(5);
        } else {
            return 0;
        }
    },
    clearForm: function() {
        $("#postedby").val(defaultPostedBy);
        $("#mylemon").val("");
        $("#email").val("");
        $("p.error").html("").hide();
        $("#optin").attr("checked", "");
        lemons.updateWordCount();
    },
    addLemon: function() {
        var postedby = $("#postedby").val();
        var post = $("#mylemon").val();
        var email = $("#email").val();
        var facebookid = lemons.facebook.facebookUID;
        var optin = $("#optin").is(":checked") ? "yes" : "no";

        if ((postedby == "" || post == "" || email == "") && facebookid == 0) {
            $("p.error").html("Oops. Please fill out all fields before submitting " + facebookid).show();
            return false;
        }

        var regemail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if ((!regemail.test(email)) && facebookid == 0) {
            $("p.error").html("Please double check and make sure your email is correct").show();
            return false;
        }

        //TODO: error check
        //TODO: posting status

        var data = "optin=" + optin + "&facebookid=" + facebookid + "&email=" + email + "&postedby=" + postedby + "&post=" + post;
        $.ajax({
            type: "POST",
            url: "AddLemon.aspx",
            data: data,
            success: function(data) {
                //TODO: release posting status
                if ($("#sendtofacebook").is(":checked")) {
                    lemons.facebook.sendToWall();
                }
                else {
                    lemons.clearForm();
                }

                if (lemons.sortType == "default") lemons.updateLemons();
            },
            error: function(data, xml) {
                //TODO: display error
                $("p.error").html("Oops. We had trouble saving your story.<br/> Please make sure there is no HTML in there.").show();
            }
        });
    },
    addVote: function(lemonid) {
        var data = "lemonid=" + lemonid;
        $("li#lemon" + lemonid + " div.voting a.vote img").attr("src", "/images/g_spinner_vote.gif");
        $.ajax({
            type: "POST",
            url: "Vote.aspx",
            data: data,
            success: function(data) {
                var id = $("post", data).attr("id");
                $("li#lemon" + lemonid + " div.voting a.vote img").attr("src", "/images/g_vote_filled.gif");
            },
            error: function(data) {
                //TODO: display error somewhere
                $("li#lemon" + lemonid + " div.voting a.vote img").attr("src", "/images/g_vote_empty.gif");
            }
        });
    },
    addReport: function(lemonid) {
        var data = "lemonid=" + lemonid;
        $("li#lemon" + lemonid + " div.voting a.report img").attr("src", "/images/g_spinner_vote.gif");
        $.ajax({
            type: "POST",
            url: "Report.aspx",
            data: data,
            success: function(data) {
                var id = $("post", data).attr("id");
                $("li#lemon" + lemonid + " div.voting a.report img").attr("src", "/images/g_report.gif");
            },
            error: function(data) {
                //TODO: display error somewhere
                $("li#lemon" + lemonid + " div.voting a.report img").attr("src", "/images/g_report_empty.gif");
            }
        });
    },
    facebook: {
        apiKey: "2a6cb965f9700344332a8393faa245e2",
        receiver: "/facebook/xd_receiver.htm",
        user: 0,
        facebookUID: 0,
        login: function() {
            lemons.facebook.user = 1;
            lemons.facebook.facebookUID = FB.Facebook.apiClient.get_session().uid;
            var userinfohtml = "<span id=\"fbpic\"><fb:profile-pic uid=loggedinuser facebook-logo=true></fb:profile-pic></span>";
            userinfohtml += "<p>Welcome <fb:name uid=loggedinuser useyou=false></fb:name>. You are now signed in with your Facebook account.";
            userinfohtml += "<label for=\"sendtofacebook\" class=\"fb\"><input type=\"checkbox\" id=\"sendtofacebook\" value=\"1\" />Post my lemon to my Facebook wall</label>";
            $("div#fblogin").hide();
            $("div#fbactive").html(userinfohtml).show();
            lemons.facebook.parse();
        },
        sendToWall: function() {
            var user_message_prompt = "What would you like to say about your lemon?";
            var user_message = { value: "" };
            var template_data = { "lemon": $("#mylemon").val(), "href": "http://etl.worktankseattle.com" };
            var body_general = template_data;
            FB.Connect.showFeedDialog(70699018269, template_data, 563683308, "", null, FB.RequireConnect.require, lemons.facebook.sendToWallSuccess, user_message_prompt, user_message);
        },
        sendToWallSuccess: function() {
            lemons.clearForm();
        },
        parse: function() {
            //FB.XFBML.Host.parseDomTree();
        }
    },
    twitter: {
        lastTweetId: 0,
        timer: null,
        interval: 30000,
        loadTweets: function() {
            $.ajax({
                type: "POST",
                url: "Twitter.aspx",
                data: {},
                beforeSend: function() {
                    clearTimeout(lemons.twitter.timer);
                    $("#twitterfeed>ul>li").remove();
                    $("#twitterfeed>ul").append("<li>Loading...</li>");
                },
                complete: function() {
                    lemons.twitter.timer = setTimeout("lemons.twitter.checkForNewTweets()", lemons.twitter.interval);
                },
                success: function(xml, textStatus) {
                    lemons.twitter.lastTweetId = 0;

                    $("#twitterfeed>ul>li").remove();
                    if ($("error", xml).length > 0) {
                        $("#twitterfeed>ul>li").remove();
                        $("#twitterfeed>ul").append("<li id=\"tweetError\">There was a problem connecting to Twitter. Please try again later.</li>");
                    } else if ($("entry", xml).length > 0) {
                        $("entry", xml).each(function() {
                            // ID is prefixed
                            var thisId = $("id", this).text();
                            thisId = thisId.substr(thisId.lastIndexOf(":") + 1);

                            $("#twitterfeed>ul").append(lemons.twitter.formatItem(this));
                            $("#tweet" + thisId).slideDown("slow");
                        });

                        // Make sure at least one valid tweet was found
                        if ($("#twitterfeed>ul>li").length > 0) {
                            // keep track of the latest Tweet ID so we can update the page if it changes
                            lemons.twitter.lastTweetId = lemons.twitter.getLastTweetId();
                        } else {
                            $("#twitterfeed>ul").append("<li id=\"tweetNoEntries\">No responses for this day</li>");
                        }

                    } else {
                        $("#twitterfeed>ul").append("<li id=\"tweetNoEntries\">No responses for this day</li>");
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $("#twitterfeed>ul>li").remove();
                    $("#twitterfeed>ul").append("<li id=\"tweetError\">There was a problem connecting to Twitter. Please try again later.</li>");
                }
            });
        },
        checkForNewTweets: function() {
            $.ajax({
                type: "POST",
                url: "Twitter.aspx",
                data: {},
                beforeSend: function() { clearTimeout(lemons.twitter.timer); },
                complete: function() { lemons.twitter.timer = setTimeout("lemons.twitter.checkForNewTweets()", lemons.twitter.interval); },
                success: function(xml, textStatus) {
                    if ($("entry", xml).length > 0) {
                        // Get first Tweet ID
                        var firstId = $("entry:first>id", xml).text();
                        firstId = firstId.substr(firstId.lastIndexOf(":") + 1);

                        // Add all new tweets to the top of the list if there have been additions
                        if (lemons.twitter.lastTweetId < firstId) {
                            $("entry", xml).each(function() {
                                // Extract Tweet ID
                                var thisId = $("id", this).text();
                                thisId = thisId.substr(thisId.lastIndexOf(":") + 1);

                                // prepend to the list as long as the tweets are more recent than the last logged tweet
                                if (thisId > lemons.twitter.lastTweetId) {
                                    if (lemons.twitter.lastTweetId > 0) {
                                        $("#tweet" + lemons.twitter.lastTweetId).before(lemons.twitter.formatItem(this));
                                    } else {
                                        $("#twitterfeed>ul").append(lemons.twitter.formatItem(this));
                                    }
                                    $("#tweet" + thisId).slideDown("slow");
                                }
                            });
                        }

                        // remove any error messaging
                        if ($("#twitterfeed>ul>li").length > 1) $("#tweetError,#tweetNoEntries").remove();

                        lemons.twitter.lastTweetId = lemons.twitter.getLastTweetId();
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    //##TODO error handling
                }
            });
        },
        formatItem: function(item) {
            var id, text, from_user;

            id = $("id", item).text();
            id = id.substr(id.lastIndexOf(":") + 1);

            text = $("title", item).text();

            from_user = $("author>name", item).text();
            from_user = from_user.substr(0, from_user.indexOf(" "));
            from_user_link = $("author>uri", item).text();
            posted_date = $("published", item).text();

            return "<li id=\"tweet" + id + "\" style=\"display: none;\">" +
			"<a href=\"" + from_user_link + "\" class=\"tweetfrom\">" + from_user + "</a>: " +
			text + "<span class='date'>" + lemons.twitter.getFriendlyDate(posted_date) + "</span>" +
			"</li>";
        },
        getLastTweetId: function() {
            return $("#twitterfeed>ul>li:first").attr("id").substring(5);
        },
        getFriendlyDate: function(tweetstamp) {
            var date = tweetstamp.split("T")[0].split("-");
            var time = tweetstamp.split("T")[1].split(":");
            var then = new Date(parseInt(date[0]), parseInt(date[1]) - 1, parseInt(date[2]), parseInt(time[0]) - 7, parseInt(time[1]));
            var now = new Date();

            var timediff = now.getTime() - then.getTime();
            var weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
            var days = Math.floor(timediff / (1000 * 60 * 60 * 24));
            var hours = Math.floor(timediff / (1000 * 60 * 60));
            var minutes = Math.floor(timediff / (1000 * 60));


            if (hours > 0) {
                var output = "posted about ";
                output += (days > 0) ? days + " day" + ((days > 1) ? "s" : "") : hours + " hour" + ((hours > 1) ? "s" : "");
                output += " ago."
            } else {
                var output = "posted less than an hour ago";
            }
            return output;
        }
    },
    flickr: {
        maxPhotos: 5,
        getPhotos: function() {
            var s = document.createElement("script");
            s.src = "http://api.flickr.com/services/feeds/photos_public.gne?id=38050013@N05&lang=en-us&format=json";
            document.getElementsByTagName("head")[0].appendChild(s);
        },
        showPhotos: function(feed) {
            $("div#flickrphotos").html("");
            var items = feed.items;
            if (items.length < lemons.flickr.maxPhotos) lemons.flickr.maxPhotos = items.length;
            for (i = 0; i < lemons.flickr.maxPhotos; i++) {
                $("div#flickrphotos").append("<a href='" + items[i].link + "' class='external'><img src='" + (items[i].media.m).replace('_m', '_s') + "' /></a>");
            }
        }
    }
};
