﻿var David = {};
var twitterFeed = "#tweets";
var seconds = -1;
var t;
var launched = false;
var sixtySecsToLaunch = false;
var tweeting = false;
var maxTweetChars = 125;
var activeTweet = 0;
var ytVideos = new Array();
var highlightArray = new Array();
var banArray = new Array();
var updateTweetTimer;
var moreTweetsFired = false;

$(function() {
    if ($(".launch").length != 0) {
        launched = true;
    }
    David.initLinks();
    David.initTwitter();
    setTimeout(David.keepTweetTime, 60000);

    if (launched == false){
        David.initPrelaunch();
    } else {
        David.initYoutube();
        David.initFacebook();
        // check for youtube modal deep linking
        var q = window.location.search;
        if (q.match(/v=/gi) != null) {
            var start = q.indexOf("v=");
            var end = q.indexOf("&", start);
            var id = "";
            if (end == -1) {
                id = q.slice(start + 2);
            } else {
                id = q.slice(start + 2, end);
            }
            if ($("#" + id).length == 1) {
                var title = $("#" + id).children("a").html();
                var url = $("#" + id).children("a").attr("rel");
                var type = $("#" + id).children("a").attr("rev");
                $(window).load(function() {
                    David.youtubeModal(title, url, type);
                });
            }
        }
    }

    $("body").bind("ajaxError", function(event, request, settings) {
        David.ajaxError(event, request, settings);
    });
});

$(window).load(function() {
    if (launched == true) {
        //David.loadJustin();
        David.loadSlideshow();
        David.loadTwitterImgs();
    }
});


// ---------------------------------------------------
// Functions called by Flash
//

closePlayer = function(){ 
    David.showTime();
    $.post("/home/HasSeenIntroVideo");
};
Facebook = function(){
    window.open("http://www.facebook.com/sharer.php?u=http://davidondemand.com&t=Check out DavidonDemand.com","_blank");
};
Tweeter = function(){
    window.open("http://twitter.com/home?status=Check out DavidonDemand.com: http://davidondemand.com","_blank");
};


// ---------------------------------------------------
// Page Initialization functions
//

David.initLinks = function(){
    $("#sponsors a, #wildfire a, #wildfireLaunch a, .tweet a, a.ext, #aboutModal p a").live("click", function(e) {
        e.preventDefault();
        window.open($(this).attr("href"), "_blank");
    });

    $("a.done").live("click", function(e) {
        e.preventDefault();
    });

    $("a#aboutLink").colorbox({ transition: "none", width: "700px", height: "491px", inline: true, href: "#aboutModal", close: "X" }).click(function(e) {
        if (launched == false) {
            document.getElementById("flash").pauseVideo();
        }
    });

    $("#cboxClose, #cboxOverlay").live('click', function() {
        if (launched == false) {
            document.getElementById("flash").playVideo();
        } else if($(".youtubeModal").length != 0){
            try {
                document.getElementById("justinPlayer").resumeFeed();
            } catch(e){ }
        }
    });

    $(".reloadFeed").click(function(e){
        e.preventDefault();
        try {
            document.getElementById("justinPlayer").resumeFeed();
        } catch(e){ }
    });

    $("#locationSubmit").click(function(e){
        e.preventDefault();
        var locationTxt = $("#location").attr("value");
        if(locationTxt != ""){
            $("#location").attr("readOnly",true).css("color","#999");
            $.post("/Home/AddNextLocation", { Location: locationTxt }, function(r) {
                if(r.ReturnCode == 0){
                    // thanks
                    $("#location").css("opacity",0).attr("value","");
                    $("#locationSubmit").hide();
                    $("#locationResult").html("Thank you.<br/><a href=\"#\">Click here to submit another location.</a>").show();
                } else {
                    // error
                    $("#location").css("opacity",0);
                    $("#locationSubmit").hide();
                    $("#locationResult").html("Sorry, an error occured.<br/><a href=\"#\">Please click here to try again.</a>").show();
                }
                
            }, "json");
        }
    });

    $("#locationResult a").live("click",function(e){
        e.preventDefault();
        $("#locationResult").hide();
        $("#locationSubmit").show();
        $("#location").attr("readOnly",false).css({color:"#000",opacity: 1});
    });
};

David.initPrelaunch = function(){
    $("#signup a").bind("click", function(e) {
        e.preventDefault();
        var email = $(this).siblings("input").attr("value");
        $.post("/Home/AddNotifyEmail", { EmailAddress: email }, function(r) {
            David.emailResponse(r);
        }, "json");
    });

    $("#signup input").focus(function(e) {
        if ($(this).attr("value") == "your email") {
            $(this).attr("value", "").css("color", "#333");
        }
    }).blur(function(e) {
        if ($(this).attr("value") == "") {
            $(this).attr("value", "your email").css("color", "#999");
        }
    });

    $("a#rewind").bind("click", function(e) {
        e.preventDefault();
        $("#countDownBack").fadeOut();
        $("#countDown").fadeOut();
        document.getElementById("flash").rewindVideo();
    });
};

David.initTwitter = function(){
    David.scrollTweets();
    David.checkTweets();
    clearTimeout(updateTweetTimer);
    if (launched == false) {
        if (sixtySecsToLaunch == false){
            updateTweetTimer = setTimeout(David.updateTweets, 24000);
        }
        David.countSeconds();
    } else {
        updateTweetTimer = setTimeout(David.updateTweets, 5000);
    }

    $(".moreTweets a").bind("click", function(e) {
        e.preventDefault();
        David.moreTweets();
    });

    $("#tweetTxt").bind("keyup", function() {
        var c = maxTweetChars - $(this).attr("value").length;
        if (c < 0) {
            c = 0;
            var txt = $(this).attr("value");
            $(this).attr("value", txt.slice(0, maxTweetChars));
        }
        $("#charCount").html(c);
    });

    $("#tweetFooter a").bind("click", function(e) {
        e.preventDefault();
        David.postTweet();
    });
};

David.initYoutube = function(){
    if ($("#youtubeVideos li").length > 8) {
        $("#showhideVideos").show();
    }
    $("#youtubeVideos li").each(function(i) {
        ytVideos.push($(this).attr("id"));
    });
    David.youtubeHeight();

    $(".moreVideos").live("click", function(e) {
        e.preventDefault();
        $("#youtubeVideos").css({overflow: "auto", height: ($("#youtubeVideos").attr("clientHeight") - 15) + "px" });
        $("#youtubeVideos li.hide").show();
        $(".moreVideos").delay(300).hide();
    });
    $(".lessVideos").live("click", function(e) {
        e.preventDefault();
        var videos = $("#youtubeVideos li:not(.hide)").length;
        if (videos % 8 == 0) {
            videos -= 8;
        } else {
            videos -= videos % 8;
        }
        $("#youtubeVideos li:not(.hide)").each(function(i, li) {
            if (i >= videos) {
                $(li).slideUp(400, function() {
                    $(this).addClass("hide");
                });
            }
        });
        $(".moreVideos").show();
        if (videos <= 8) {
            $(".lessVideos").hide();
        }
    });

    $("#youtubeOrder .new").bind("click", function(e) {
        e.preventDefault();
        if (!$(this).hasClass("active")) {
            David.youTubeNewest();
            $(this).addClass("active");
            $("#youtubeOrder .popular").removeClass("active");
            David.youtubeHeight();
        }
    });
    $("#youtubeOrder .popular").bind("click", function(e) {
        e.preventDefault();
        if (!$(this).hasClass("active")) {
            David.youTubePopular();
            $(this).addClass("active");
            $("#youtubeOrder .new").removeClass("active");
            David.youtubeHeight();
        }
    });

    $("#youtubeVideos li a").bind("click", function(e) {
        // call YouTube modal
        e.preventDefault();
        try {
            document.getElementById("justinPlayer").pauseFeed();
        } catch(e){ }
        var title = $(this).html();
        var url = $(this).attr("rel");
        var type = $(this).attr("rev");
        var sUrl = $(this).siblings(".ShareURL").attr("value");
        David.youtubeModal(title, url, type, sUrl);
    });
    $("#youtubeVideos li img").bind("click", function(e) {
        // call YouTube modal
        e.preventDefault();
        try {
            document.getElementById("justinPlayer").pauseFeed();
        } catch(e){ }
        var title = $(this).siblings("a").html();
        var url = $(this).siblings("a").attr("rel");
        var type = $(this).siblings("a").attr("rev");
        var sUrl = $(this).siblings(".ShareURL").attr("value");
        David.youtubeModal(title, url, type, sUrl);
   });
};

David.initFacebook = function(){
    David.updatePageNo(1);
    David.sizeFrame($("#page1 li").length);

    $("#facebookPhotos li a").live("click", function(e) {
        // call Facebook modal
        e.preventDefault();
        var facebookModalCaption = $(this).siblings("input.Caption").attr("value");
        if (facebookModalCaption == "") {
            facebookModalCaption = "David on Demand";
        } else {
            facebookModalCaption = $(this).siblings("input.Caption").attr("value");
        }
        var facebookModalSourceURL = $(this).siblings("input.SourcePhotoURL").attr("value");
        var facebookModalTags = "This photo has not been tagged yet";
        if ($(this).siblings("div.NamesTagged").children("span").html() != "") {
            facebookModalTags = $(this).siblings("div.NamesTagged").html();
        }
        var facebookModalPhotoURL = $(this).siblings("input.FacebookURL").attr("value");
        var facebookModalPhotoHeight = $(this).siblings("input.Height").attr("value");
        var facebookModalPhotoWidth = $(this).siblings("input.Width").attr("value");
        David.facebookModal(facebookModalCaption, facebookModalSourceURL, facebookModalTags, facebookModalPhotoURL, facebookModalPhotoHeight, facebookModalPhotoWidth);
    });

    $("#facebookPages a").bind("click", function(e) {
        e.preventDefault();
        David.flipPage($(this).html());
    });
    
    $("#facebookPages a.fbEllipsesAfter").unbind();
    $("#facebookPages a.fbEllipsesAfter").bind("click", function(e) {
        e.preventDefault();
        var currentPage = $("#facebookPhotos ul:not(.inactive)").attr("id");
        if(currentPage == null){
            return false;
        }
        var a = currentPage.match(/\d+/);
        var currentNo = parseInt(a[0]);
        David.flipPage(parseInt((currentNo - 1)/20) * 20 + 21);
    });
    
    $("#facebookPages a.fbEllipsesBefore").unbind();
    $("#facebookPages a.fbEllipsesBefore").bind("click", function(e) {
        e.preventDefault();
        var currentPage = $("#facebookPhotos ul:not(.inactive)").attr("id");
        if(currentPage == null){
            return false;
        }
        var a = currentPage.match(/\d+/);
        var currentNo = parseInt(a[0]);
        David.flipPage(parseInt((currentNo - 1)/20) * 20);
    });
};

David.loadJustin = function(){
    $("div#justinPlayer").html("<div>This site requires Adobe Flash version 10<br/><a href=\"http://www.adobe.com/go/getflashplayer\" class=\"serif\" target=\"_blank\">Get it here</a></div>");
    swfobject.embedSWF('/_res/swf/intro/streamPlayer1.swf', "justinPlayer", "691", "361", "9.0.0", "", {}, { wmode: "opaque" }, { id: "justinPlayer", name: "justinPlayer" });
};

David.loadSlideshow = function(){
    $("div#justinPlayer").html("<div>This site requires Adobe Flash version 10<br/><a href=\"http://www.adobe.com/go/getflashplayer\" class=\"serif\" target=\"_blank\">Get it here</a></div>");
    swfobject.embedSWF('/_res/swf/slideshow.swf', "justinPlayer", "691", "361", "9.0.0", "", {}, { wmode: "opaque" }, { id: "justinPlayer", name: "justinPlayer" });

};


// ---------------------------------------------------
// Count down related functions
//

David.countSeconds = function() {
    if (launched == false) {
        // keep track of time between page load and counter display
        t = setTimeout(David.countSeconds, 1000);
        seconds++;
        if(sixtySecsToLaunch == false && secondsLeft - seconds <= 65){
            sixtySecsToLaunch = true;
            David.disableMoreTweets();
        }
    }
};

David.showTime = function(){
    // display counter
    clearTimeout(t);
    secondsLeft -= seconds;
    David.calcSeconds();
    $("#countDown").css({opacity:"0",display:"block"}).delay(400).animate({opacity: 1});
    $("#countDownBack").fadeIn();
};

David.calcSeconds = function() {
    // update counter
    if (sixtySecsToLaunch == false && secondsLeft <= 65) {
        //disable all timed executions...get latest tweets, get more tweets
        sixtySecsToLaunch = true;
        David.disableMoreTweets();
    }

    if (secondsLeft <= 0) {
        // launch David
        David.replacePreLaunchWithLaunch();
        for(var i = 0; i < 4; i++){
            $("#time" + i).html("00");
        }
    } else {
        var time = new Array();
        time.push(parseInt(secondsLeft / 86400), parseInt((secondsLeft % 86400) / 3600), parseInt(((secondsLeft % 86400) % 3600) / 60), parseInt(((secondsLeft % 86400) % 3600) % 60));
        for (var i = 0; time.length > i; i++) {
            if (time[i] < 10) {
                time[i] = "0" + time[i];
            }
            $("#time" + i).html(time[i]);
        }

        t = setTimeout(David.calcSeconds, 1000);
        secondsLeft--;
    }
};


// ---------------------------------------------------
// Twitter related functions
//

David.scrollTweets = function(){
    // scroll to bottom of twitter feed
    var $tf = $(twitterFeed);
    var sH = $tf.attr("scrollHeight");
    var cH = $tf.attr("clientHeight");
    $tf.attr("scrollTop", sH - cH);
};

David.checkScroll = function(){
    // check if scrollbar is at bottom of twitter feed
    var $tf = $(twitterFeed);
    var sH = $tf.attr("scrollHeight");
    var cH = $tf.attr("clientHeight");
    if($tf.attr("scrollTop") == sH - cH){
        return true;
    } else {
        return false;
    }
};

David.buildTweet = function(tw){
    // returns HTML for a tweet
    var css = "tweet";
    if(launched == true && tw.IsDavid == true){
        css = css + " david";
    } else if(launched == true && tw.Highlighted == true){
        css = css + " highlight";
    }
    var title = "";
    var data = new Object();
    data.avatar = tw.TwitterProfileImageUrl;
    data.html = tw.TextHtml;
    data.time = tw.TimeString;
    data.screenname = tw.TwitterScreenName;
    if(launched == false){
        data.id = tw.Id;
        data.username = "David On Demand";
        data.timeStamp = "";
        data.background = "style=\"background-image: url(" + data.avatar + ");\" ";
    } else {
        data.id = tw.DoDTweetId;
        data.username = tw.TwitterScreenName;
        data.timeStamp = "<input type=\"hidden\" name=\"CreatedDateMinutesSince2010\" id=\"CreatedDateMinutesSince2010\" value=\"" + tw.CreatedDateMinutesSince2010 + "\">";
        data.background = "";
    }
    if(data.id == activeTweet){
        css = "tweet activeTweet";
        title = " title=\"What is David doing now? This.\"";
    }
    var tweet = "<div " + data.background + "id=\"" + data.id + "\" class=\"" + css + "\"" + title + "><a href=\"http://www.twitter.com/" + data.screenname + "\" target=\"_blank\" class=\"username\">" + data.username + "<span></span></a><p>" + data.html + "</p><p class=\"time\">" + data.time + "</p>" + data.timeStamp + "<input type=\"hidden\" value=\"" + data.avatar + "\" name=\"hdn_" + data.id + "\" id=\"hdn_" + data.id + "\" class=\"iconUrl\"></div>";
    return tweet;
};

David.checkTweets = function() {
    if (sixtySecsToLaunch == true){
        return false;
    }
    // verify more tweets exist; if none exist disable the More Tweets button
    var $tweet = $("#tweets .tweet");
    if ($tweet.length == 0) {
        David.disableMoreTweets();
        if ($("#twitterFail").length == 0) {
            David.twitterFail(".moreTweets");
        }
        return;
    }
    var oldId = parseInt($tweet[0].id);
    $($tweet).each(function(i) {
        var tw = parseInt($tweet[i].id);
        if (tw < oldId && tw != 0 || oldId == 0) {
            oldId = tw;
        }
    });

    var purl = "";
    if (launched == false) {
        purl = "/Home/GetMoreTweets";
    } else {
        purl = "/Home/GetMoreLaunchTweets";
    }
    $.post(purl, { OldestTweetId: oldId, TweetCount: 20 }, function(r) {
        if (r.Result != null) {
            if (r.Result.length == 0) {
                David.disableMoreTweets();
            } else {
                David.enableMoreTweets();
            }
        } else {
            David.disableMoreTweets();
        }
    }, "json");
};

David.moreTweets = function() {
    if(sixtySecsToLaunch == true || moreTweetsFired == true){
        return false;
    }
    moreTweetsFired = true;
    // get older tweets, fired from More Tweets button
    var $tweet = $("#tweets .tweet");
    if ($tweet.length == 0) {
        return;
    }
    var oldId = parseInt($tweet[0].id);
    $($tweet).each(function(i) {
        var tw = parseInt($tweet[i].id);
        if (tw < oldId && tw != 0 || oldId == 0) {
            oldId = tw;
        }
    });

    var purl = "";
    if (launched == false) {
        purl = "/Home/GetMoreTweets";
    } else {
        purl = "/Home/GetMoreLaunchTweets";
    }
    $.post(purl, { OldestTweetId: oldId, TweetCount: 20 }, function(r) {
        if (r.ReturnCode == 0 && r.Result != null) {
            var rl = r.Result.length;
            David.showMoreTweets(r.Result);
            if (rl != 0) {
                var $oldTweet = $("#" + oldId);
                //$(twitterFeed).attr("scrollTop", $oldTweet[0].offsetTop - $oldTweet[0].parentNode.offsetTop - $(".moreTweets").attr("offsetHeight"));
                $(twitterFeed).attr("scrollTop", $oldTweet[0].offsetTop - $(".moreTweets").attr("offsetHeight"));
            }
            if (rl < 20) {
                David.disableMoreTweets();
            } else {
                David.checkTweets();
            }
            moreTweetsFired = false;
        }
    }, "json");
};

David.showMoreTweets = function(tweets){
    // parse More Tweets Ajax response and add results
    if(tweets.length != 0){
        while(tweets.length != 0){
            var tId = 0;
            var k = 0;
            $(tweets).each(function(i){
                var tw = parseInt(tweets[i].Id);
                if(launched == true){
                    tw = parseInt(tweets[i].CreatedDateMinutesSince2010);
                }
                if(tw > tId){
                    tId = tw;
                    k = i;
                }
            });
            $("#tweets .tweet:first").before(David.buildTweet(tweets[k]));
            tweets.splice(k,1);
        }
        David.loadTwitterImgs();
    }
};

David.disableMoreTweets = function(){
    $(".moreTweets a").css({"color":"#c0c0c0","cursor":"default"});
    $(".moreTweets a span").css({"background-position":"0 -24px","opacity":"0.25"});
};

David.enableMoreTweets = function(){
    $(".moreTweets a").css({"color":"","cursor":""});
    $(".moreTweets a span").css({"background-position":"","opacity":""});
};

David.updateTweets = function() {
    if(sixtySecsToLaunch == true){
        return false;
    }
    // check for new Tweets - looped
    var $tweet = $("#tweets .tweet");
    var newId = 0;
    var oldId = 0;
    var checkMore = false;
    if ($tweet.length != 0) {
        newId = parseInt($tweet[0].id);
        oldId = newId;
        $($tweet).each(function(i) {
            var tw = parseInt($tweet[i].id);
            if (tw > newId) {
                newId = tw;
            } else if (tw < oldId && tw != 0 || oldId == 0) {
                oldId = tw;
            }
        });
    } else {
        checkMore = true;
    }

    var scroll = false;
    if (David.checkScroll() == true) {
        var scroll = true;
    }

    if (launched == false) {
        $.post("/Home/GetLatestTweets", { LastTweetId: newId }, function(r) {
            if (r.Result != null) {
                var rl = r.Result.length;
                David.showNewTweets(r);
                if (scroll == true) {
                    David.scrollTweets();
                }
                if (rl != 0 && checkMore == true) {
                    David.checkTweets();
                }
            }
            updateTweetTimer = setTimeout(David.updateTweets, 24000);
        }, "json");
    } else {
        $.post("/Home/GetLatestLaunchTweets", { LastTweetId: newId, FirstTweetId: oldId }, function(r) {
            if (r.Result != null) {
                var rl = r.Result.length;
                David.showNewTweets(r);
                if (scroll == true) {
                    David.scrollTweets();
                }
                if (rl != 0 && checkMore == true) {
                    David.checkTweets();
                }
            }
            if(tweeting == false){
              clearTimeout(updateTweetTimer);
              updateTweetTimer = setTimeout(David.updateTweets, 5000);
            }
        }, "json");
    }

};


David.showNewTweets = function(r){
    // parse Update Tweets Ajax response and add results
    if(r.ReturnCode != 0){
        return;
    }
    var tweets = r.Result;
    if(launched == false && r.Result.length != 0){
        while(tweets.length != 0){
            var tId = parseInt(tweets[0].Id); 
            var k = 0;
            $(tweets).each(function(i){
                var tw = parseInt(tweets[i].Id);
                if(tw < tId){
                    tId = tw;
                    k = i;
                }
            });
            if($("#tweets .tweet").length != 0){
                $("#tweets .tweet:last").after(David.buildTweet(tweets[k]));
            } else {
                // fail whale present; remove him
                $(".moreTweets").after(David.buildTweet(tweets[k]));
                $("#twitterFail").remove();
            }
            tweets.splice(k,1);
        }
        David.loadTwitterImgs();
    } else if(launched == true){
        if(tweets.length != 0){
            var $displayedTweets = $("#tweets .tweet");
            if($displayedTweets.length > 200){
                var del = $displayedTweets.length - 200;
                for(var i = 0; i < del; i++){
                    $($displayedTweets[i]).remove();
                }
            }
            var tweetIds = new Array();
            $($displayedTweets).each(function(i,t){
                tweetIds.push(t.id);
            });
            while(tweets.length != 0){
                if($.inArray(tweets[0].DoDTweetId,tweetIds) == -1){
                    var tTime = parseInt(tweets[0].CreatedDateMinutesSince2010); 
                    var dt = $.makeArray($displayedTweets);
                    dt.reverse();
                    i = 0;
                    var j = $(dt[i]).children("input").attr("value");
                    while(tTime < j){
                        i++;
                        j = $(dt[i]).children("input").attr("value");
                    }
                    $(dt[i]).after(David.buildTweet(tweets[0]));
                    $displayedTweets.push($("#tweets #" + tweets[0].DoDTweetId));
                }
                tweets.splice(0,1);
            }
            David.loadTwitterImgs();
        }
        if(r.Highlighted.length != 0){
            // highlight completed tweets
            $(r.Highlighted).each(function(i,t){
                if($.inArray(t,highlightArray) == -1){
                    if(!$("#tweets #" + t).hasClass("activeTweet") && !$("#tweets #" + t).hasClass("david")){
                        $("#tweets #" + t).addClass("highlight");
                    }
                    highlightArray.push(t);
                }
            });
            var n = 0;
            $(highlightArray).each(function(i,t){
                if($.inArray(t,r.Highlighted) == -1){
                    $("#tweets #" + t).removeClass("highlight");
                    highlightArray.splice(n,1);
                } else {
                    n++;
                }
            });
        } else {
            $(highlightArray).each(function(i,t){
                $("#tweets #" + t).removeClass("highlight");
                highlightArray.splice(0,1);
            });
        }
        if(r.Banned.length != 0){
            // removed banned tweets
            $(r.Banned).each(function(i,t){
                if($.inArray(t,banArray) == -1){
                    $("#tweets #" + t).hide();
                    banArray.push(t);
                }
            });
            var n = 0;
            $(banArray).each(function(i,t){
                if($.inArray(t,r.Banned) == -1){
                    $("#tweets #" + t).show();
                    banArray.splice(n,1);
                } else {
                    n++;
                }
            });
        } else {
            $(banArray).each(function(i,t){
                $("#tweets #" + t).show();
                banArray.splice(0,1);
            });
        }
        if(r.ActiveTweet != null){
            // display the active tweet
            var tw = r.ActiveTweet;
            var id = parseInt(tw.DoDTweetId);
            if(id != activeTweet && tw.IsDavid == false && activeTweet != 0){
                $("#"+activeTweet).removeClass("activeTweet").addClass("highlight").attr("title","");
                if($.inArray(activeTweet,r.Highlighted) == -1){
                    $("#" + activeTweet).removeClass("highlight").attr("title","");
                }
                $("#"+id).addClass("activeTweet").removeClass("highlight").attr("title","What is David doing now? This.");
/*              var html = "<div class=\"blue\"></div><div class=\"twUser\"><p>Active Tweet</p><a href=\"http://www.twitter.com/" + tw.TwitterScreenName + "\" target=\"_blank\">" + tw.TwitterScreenName + "</a></div>";
                html += "<div class=\"twMsg\"><p>" + tw.TextHtml + "</p><div><span></span><p class=\"time serif\">" + tw.TimeString + "</p></div></div>";
                $("#activeTweet").html(html);
                $("#activeTweet .blue").fadeIn(150).fadeOut(150).fadeIn(150).fadeOut(150).fadeIn(150).fadeOut(150);
                // load image and check for errors
                var activePreload = new Image();
                activePreload.onload = function(){
                    $("#activeTweet .twUser").css("background-image","url(" + this.src + ")");
                };
                activePreload.onerror = function(){
                    $("#activeTweet .twUser").css("background-image","url(/_res/i/twitter-default.png)");
                };
                activePreload.src = tw.TwitterProfileImageUrl;
                //*/
                activeTweet = id;
            } else if(activeTweet == 0){
                activeTweet = id;
                $("#" + id).addClass("activeTweet").removeClass("highlight").attr("title","What is David doing now? This.");
            }
        } else {
            if(activeTweet != 0){
                $("#"+activeTweet).removeClass("activeTweet").attr("title","");
                activeTweet = 0;
            }
        }
    }
};

David.keepTweetTime = function(){
    // update time stamp on tweets every minute
    var $tweet = $(".tweet");
    if($tweet.length == 0){
        return;
    }

    $($tweet).each(function(i){
        var $time = $($tweet[i]).find("p.time");
        var html = $($time).html();
        if(html.match("about") != null && html.match("minutes") != null){
            var d = parseInt(html.match(/\d+/));
            d++;
            if(d >= 60){
                $($time).html("about an hour ago");
            } else {
                $($time).html(html.replace(/\d+/,d));
            }
        } else if(html.match("just now") != null){
            $($time).html("about a minute ago");
        } else if(html.match("about a minute ago") != null){
            $($time).html("about 2 minutes ago");
        }
    });

    setTimeout(David.keepTweetTime,60000);
};

David.twitterFail = function(s){
    // post the fail whale after the specified selector, s
    $(s).after("<div id=\"twitterFail\">Twitter is currently down. Stay tuned for updates from David.</div>");
};

David.davidFail = function(s){
    // post the fail whale after the specified selector, s
    $(s).after("<div class=\"davidFail\">David on Demand is experiencing technical difficulties. Please try again.</div>");
};

David.postTweet = function(){
    // post a user's Tweet
    var tweetText = $("#tweetTxt").attr("value");
    if(tweetText == "" || tweeting == true){
        return;
    }
    tweetText = tweetText.slice(0,maxTweetChars);
    tweeting = true;

    $("#tweetTxt").attr("readOnly","true").fadeTo(300,0.4);
    $("#tweetLoading").fadeIn();

    clearTimeout(updateTweetTimer);
    $.post("/home/SubmitTweetOnBehalfOfUser",{Text:tweetText},function(r){
        tweeting = false;
        if(r.ReturnCode == 2){
            window.location = "/Home/TwitterSignInAndFollow";
            return;
        }
        clearTimeout(updateTweetTimer);
        updateTweetTimer = setTimeout(David.updateTweets, 5000);
        if(r.Result != null && r.Result.length != 0){
            $("#tweetTxt").attr({value:"",readOnly:false}).fadeTo(200,1);
            $("#tweetLoading").fadeOut(200);
            $("#charCount").html(maxTweetChars);
            if(r.Result.TwitterProfileImageUrl == ""){
                r.Result.TwitterProfileImageUrl = "/_res/i/twitter-default.png";
            }
            var $displayedTweets = $("#tweets .tweet");
            var tweetIds = new Array();
            $($displayedTweets).each(function(i,t){
                tweetIds.push(t.id);
            });
            if($.inArray(r.Result.DoDTweetId,tweetIds) == -1){
                $("#tweets .tweet:last").after(David.buildTweet(r.Result));
                David.loadTwitterImgs();
            }
        } else {
            $("#tweetTxt").attr({readOnly:false}).fadeTo(200,1);
            $("#tweetLoading").fadeOut(200);
            David.twitterFail("#tweets .tweet:last");
        }
        David.scrollTweets();
    });
};

David.loadTwitterImgs = function(){
    // preload twitter images to decrease page load time and replace missing images
    var tweets = $("#tweets .tweet");
    $(tweets).each(function(i,t){
        if($(t).children(".iconUrl").length != 0){
            var img = $(t).children(".iconUrl").attr("value");
            $(t).children(".iconUrl").remove();
            eval("var imgPreload" + i + " = new Image();");
            eval("var tweet" + i + " = $(t).attr(\"id\")");
            eval("imgPreload" + i + ".onload = function(){ $(\"#\" + tweet" + i + ").append(\"<img src='\" + this.src + \"' class='twitterIcon' />\"); };");
            eval("imgPreload" + i + ".onerror = function(){ $(\"#\" + tweet" + i + ").append(\"<img src='/_res/i/twitter-default.png' class='twitterIcon' />\"); };");
            eval("imgPreload" + i + ".src = \"" + img + "\";");
        }
    });
}

// ---------------------------------------------------
// YouTube related functions
//

David.youTubeNewest = function(){
    var $videos = $("#youtubeVideos li").detach();
    var j = 0;
    var showEight = false;
    if($(".moreVideos").length != 0){
        showEight = true;
    }
    while($videos.length != 0){
        $($videos).each(function(i){
            if($videos[i].id == ytVideos[j]){
                $("#youtubeVideos ul").append($videos[i]);
                var li = "li#" + ytVideos[j];
                if(showEight == true && j > 7){
                    $(li).addClass("hide");
                } else if($(li).hasClass("hide")){
                    $(li).removeClass("hide").css("display","");
                }
                $videos.splice(i,1);
                j++;
                return false;
            }
        });
    }
}

David.youTubePopular = function(){
    var $videos = $("#youtubeVideos li").detach();
    var j = 0;
    var showEight = false;
    if($(".moreVideos").length != 0){
        showEight = true;
    }
    while($videos.length != 0){
        var views = 0;
        var k = 0;
        $($videos).each(function(i){
            var v = parseInt($($videos[i]).children(".ViewCount").attr("value"));
            if(v > views){
                views = v;
                k = i;
            }
        });
        $("#youtubeVideos ul").append($videos[k]);
        var li = "li#" + $videos[k].id;
        if(showEight == true && j > 7){
            $(li).addClass("hide");
        } else if($(li).hasClass("hide")){
            $(li).removeClass("hide").css("display","");
        }
        $videos.splice(k,1);
        j++;
    }
}

David.youtubeModal = function (title,url,type,shareUrl){
    $.fn.colorbox({transition:"none", close:"X", width: "680px", photo: true, html: function(){
        return "<div class=\"youtubeModal\"><h2>" + title + "</h2><object width=\"642\" height=\"390\"><param name=\"movie\" value=\"" + url + "\"></param><embed src=\"" + url + "\" type=\"" + type + "\" width=\"642\" height=\"390\"></embed></object><div><a class=\"facebook\" href=\"http://www.facebook.com/sharer.php?u=" + shareUrl + "&t=Check out this video from DavidonDemand.com\" target=\"_blank\">Share</a> <a class=\"twitter\" href=\"http://twitter.com/home?status=Check out this video from DavidonDemand.com: " + shareUrl + "\" target=\"_blank\">Tweet</a></div></div>";
    }});
}

David.youtubeHeight = function(){
    var $vids = $("#youtubeVideos li");
    $($vids).css("height","");
    while($vids.length != 0){
        var row = $vids.splice(0,4);
        var h = 0;
        $(row).each(function(i,r){
            var hide = false;
            if($(r).hasClass("hide")){
                $(r).removeClass("hide");
                hide = true;
            }
            if(r.offsetHeight > h){
                h = r.offsetHeight;
            }
            if(hide){
                $(r).addClass("hide");
            }
        });
        $(row).css("height",h - 25);
    }
}



// ---------------------------------------------------
// Facebook related functions
//

David.flipPage = function(i){
    // transition one Facebook photo page to another
    var currentPage = $("#facebookPhotos ul:not(.inactive)").attr("id");
    if(currentPage == null){
        return false;
    }
    if($("#fbError").length != 0){
        $("#fbError").remove();
    }
    var a = currentPage.match(/\d+/);
    var currentNo = parseInt(a[0]);
    if(i == "First"){
        targetPage = 1;
    } else if(i == "Prev"){
        targetPage = currentNo - 1;
    } else if(i == "Next") {
        targetPage = currentNo + 1;
    } else {
        targetPage = parseInt(i);
    }
    if(targetPage == currentNo){
        return;
    }

    if(targetPage > currentNo){
        $("#" + currentPage).animate({left: "-650px",opacity: 0},600).addClass("inactive");
        if($("#page" + targetPage).length == 0){
            David.loadPhotos(1, targetPage);
        } else {
            $("#page" + targetPage).css("left","650px").animate({left: "0",opacity: 1},600).removeClass("inactive");
            David.sizeFrame($("#page" + targetPage + " li").length);
        }
    } else {
        $("#" + currentPage).animate({left: "650px",opacity: 0},600).addClass("inactive");
        if($("#page" + targetPage).length == 0){
            David.loadPhotos(-1, targetPage);
        } else {
            $("#page" + targetPage).css("left","-650px").animate({left: "0",opacity: 1},600).removeClass("inactive");
            David.sizeFrame($("#page" + targetPage + " li").length);
        }
    }
    David.updatePageNo(targetPage);
}

David.loadPhotos = function(x, targetPage){
    $("#photoFrame").css("background","transparent url(/_res/i/dod-loader.gif) no-repeat center center");
    $.post("/home/FacebookPhotos",{PageIndex:targetPage - 1},function(r){   // add in proper AJAX URL and data
        if(r.ReturnCode == 0 && r.Result != null && r.Result.length != 0){
            var fbHtml = David.formatPhotoPage(r.Result);
            var imgCount = 0;
            var imgObj = new Image();
            $(r.Result).each(function(i,img){
                imgObj.src = img.ThumbnailURL;
                imgCount++;
            });
            David.sizeFrame(imgCount);
            setTimeout(function(){
                $("#photoFrame").css({background:"transparent none"}).append("<ul id=\"page" + targetPage + "\"></ul>");
                x *= 650;
                $("#page" + targetPage).css("left",x).html(fbHtml).animate({left: 0,opacity: 1},600);
            },2000);
        } else {
            // show error
        }
    });
}

David.formatPhotoPage = function(result){
    // return LIs for each photo
    var html = "";
    var fbUrl = $("input.FacebookProfileURL").attr("value");
    $(result).each(function(i,img){
        html += "<li><a href=\"#\"><img src=\"" + img.ThumbnailURL + "\"></a>";
        html += "<input type=\"hidden\" class=\"SourcePhotoURL\" value=\"" + img.SourcePhotoURL + "\"/>";
        html += "<input type=\"hidden\" class=\"Caption\" value=\"" + img.Caption + "\"/>";
        html += "<input type=\"hidden\" class=\"FacebookURL\" value=\"" + img.FacebookURL + "\"/>";
        var tags = "";
        if(img.NamesTagged != null){
            $(img.NamesTagged).each(function(i,d){
                if(d.FacebookID != ""){
                    tags += "<a href=\"" + fbUrl + d.FacebookID + "\">" + d.Name + "</a>";
                } else {
                    tags += d.Name;
                }
                if(img.NamesTagged[i + 1] != null){
                    tags += ", ";
                }
            });
        }
        html += "<div class=\"NamesTagged\"><span>" + tags + "</span></div>";
        html += "<input type=\"hidden\" class=\"Width\" value=\"" + img.Width + "\"/>";
        html += "<input type=\"hidden\" class=\"Height\" value=\"" + img.Height + "\"/></li>";
    });
    return html;
}

David.updatePageNo = function(currentNo){
    //update Facebook page number link
    var totalPages = parseInt(David.roundUp($(".TotalNumberOfResults").attr("value"),$(".PhotosPerPage").attr("value")));
    if(currentNo == 1 && totalPages != 1){
        $(".fbFirst").hide();
        $(".fbPrev").hide();
        $(".fbNext").show();
    } else if(currentNo == totalPages && currentNo != 1){
        $(".fbFirst").show();
        $(".fbPrev").show();
        $(".fbNext").hide();
    } else if(currentNo != 1){
        $(".fbFirst").hide();
        $(".fbPrev").show();
        $(".fbNext").show();
    }
    if(totalPages > 20){
      for(var i = 1; i <= totalPages; i++){
        if(parseInt((i - 1)/20) == parseInt((currentNo - 1)/20)){
          $("#facebookPages a:econtains('" + i + "')").show();
        } else {
          $("#facebookPages a:econtains('" + i + "')").hide();
        }
      }
      if(parseInt((currentNo - 1)/20) < parseInt((totalPages - 1)/20)){
        $(".fbEllipsesAfter").show();
      } else {
        $(".fbEllipsesAfter").hide();
      }
      if(currentNo > 20){
        $(".fbEllipsesBefore").show();
      } else {
        $(".fbEllipsesBefore").hide();
      }
    } else {
        $(".fbEllipsesAfter").hide();
        $(".fbEllipsesBefore").hide();
    }
    $("#facebookPages a.active").removeClass("active");
    $("#facebookPages a:econtains('" + currentNo + "')").addClass("active");
}

David.sizeFrame = function(imgCount){
    imgCount = David.roundUp(imgCount,4);
    $("#photoFrame").animate({height: imgCount * 145 + 10});
}

David.facebookModal = function (facebookModalCaption,facebookModalSourceURL,facebookModalTags,facebookModalPhotoURL,facebookModalPhotoHeight,facebookModalPhotoWidth){
    $.fn.colorbox({transition:"none", close:"X", photo:true, html: function(){
        return "<div id=\"facebookPhotosModal\" class=\"modal\"><h1 style=\"width:" + facebookModalPhotoWidth + "px\"><span class=\"facebook\"></span>" + facebookModalCaption + "</h1><img src=\"" + facebookModalSourceURL + "\" height=\"" + facebookModalPhotoHeight + "\" width=\"" + facebookModalPhotoWidth + "\" /><div id=\"facebookPhotosMeta\" style=\"width:" + facebookModalPhotoWidth + "px\"><div class=\"tagLabel\">In this photo:</div><div class=\"tags\">" + facebookModalTags + "</div><div class=\"tagLink\">See someone you know? <a href=\"" + facebookModalPhotoURL + "\" target=\"_blank\">Tag them</a></div></div></div>";
    }});
    $("#facebookPhotosModal #facebookPhotosMeta .tags a").attr("target", "_blank");
}


// ---------------------------------------------------
// Email submission related functions
//

David.emailResponse = function(r){
    if(r == null){
        // error
        return;
    }
    var error = "An error has occured. Please try again.";
    var invalid = "Please enter a valid email address.";
    switch(r.ReturnCode){
        case 2:
            // failed
            if($("#signup .error").html() != error){
                $("#signup .form").before("<div class=\"error\">" + error + "</div>");
            }
            break;
        case 3:
            // error
            if($("#signup .error").html() != error){
                $("#signup .form").before("<div class=\"error\">" + error + "</div>");
            }
            break;
        case 4: 
            // invalid
            if($("#signup .error").html() != invalid){
                $("#signup .form").before("<div class=\"error\">" + invalid + "</div>");
            }
            break;
        default:
            // ok
            var social = $("#socialMedia").html();
            $("#signup").html("<h6>Thanks, look for an email June 21st.</h6><div id=\"socialMediaForm\">" + social + "</div>");
    }
};


// ---------------------------------------------------
// AJAX error handling
//

David.ajaxError = function(e, r, settings){
    if(settings.url == "/home/SubmitTweetOnBehalfOfUser"){
        clearTimeout(updateTweetTimer);
        updateTweetTimer = setTimeout(David.updateTweets, 5000);
        tweeting = false;
        $("#tweetTxt").attr({readOnly:false}).fadeTo(200,1);
        $("#tweetLoading").fadeOut(200);
        David.davidFail($("#tweets").children(":last"));
        David.scrollTweets();
        $(".davidFail").delay(4000).fadeOut(function(){
            $(this).remove();
        });
    } else if(settings.url == "/Home/GetLatestLaunchTweets"){
        clearTimeout(updateTweetTimer);
        updateTweetTimer = setTimeout(David.updateTweets, 5000);
    } else if(settings.url == "/home/FacebookPhotos"){
        if($("#photoFrame") != 0){
            $("#photoFrame").css("background","transparent none");
            $("#photoFrame").prepend("<div id=\"fbError\">Sorry, Facebook photos are temporarily unavailable.<br/>Please <a href=\"/\">refresh</a> your browser or check back again shortly.</div>");
        } else {
            David.getFacebook();
        }
    } else if(settings.url == "home/JustinTvVideo"){
        David.getJustin();
    } else if(settings.url == "home/TwitterLaunchFeed"){
        David.getTwitter();
    } else if(settings.url == "home/YouTubeVideos"){
        David.getYoutube();
    } else if(settings.url == "home/FacebookPhotos"){
        David.getFacebook();
    } else if(settings.url == "home/WildfireBanner"){
        David.getWildfire();
    } else if(settings.url == "home/FoursquareGoogleMap"){
        David.getFoursquare();
    } else if(settings.url == "home/SponsorsBanner"){
        David.getSponsors();
    } else if(settings.url == "home/TweetHeader"){
        David.getTwitterHead();
    } else if(settings.url == "/home/Masthead"){
        David.getMasthead();
    }
};


// ---------------------------------------------------
// Utilities
//

$.expr[":"].econtains = function(obj, index, meta, stack){
    return (obj.textContent || obj.innerText || $(obj).text() || "").toLowerCase() == meta[3].toLowerCase();
}

David.roundUp = function(i,div){
    i = parseInt(i);
    div = parseInt(div);
    j = (i/div).toFixed();
    if(i%div != 0 && i%div < div/2){
        j++;
    }
    return j;
}


// --------------------------------------------------
// Launch methods for the client side switchover when the clock reaches zero
//

David.replacePreLaunchWithLaunch = function() {
    launched = true;
    sixtySecsToLaunch = false;
    David.replaceDivContent();
};

David.replaceDivContent = function() {
    if (launched == true) {
        $("#secondary .left").html("");
        $("#secondary .right").html("");
        $("#primary .right").children().animate({opacity:0},400);
        $("#primary .left").children("#countDown").fadeOut();
        David.getJustin();
        David.getTwitter();
        David.getTwitterHead();
        David.getYoutube();
        David.getFacebook();
        David.getWildfire();
        David.getFoursquare();
        David.getSponsors();
        David.getMasthead();
    }
};
David.getJustin = function(){
    $.get('home/JustinTvVideo', function(data) {
        if(data != ""){
            $("#primary .left").html(data);
            David.loadJustin();
        } else {
            setTimeout(David.getJustin(),5000);
        }
    });
};
David.getTwitter = function(){
    $.get('home/TwitterLaunchFeed', function(data) {
        if(data != ""){
            $("#primary .right").html(data);
            $(".moreTweets a").unbind();
            David.initTwitter();
            David.loadTwitterImgs();
        } else {
            setTimeout(David.getTwitter(),5000);
        }
    });
};
David.getTwitterHead = function(){
    $.get('home/TweetHeader', function(data) {
        if(data != ""){
            $("#nav div").remove();
            $("#nav").append(data);
        } else {
            setTimeout(David.getTwitterHead(),5000);
        }
    });
};
David.getYoutube = function(){
    $.get('home/YouTubeVideos', function(data) {
        if(data != ""){
            $("#secondary .left").prepend(data);
            David.initYoutube();
        } else {
            setTimeout(David.getYoutube(),5000);
        }
    });
};
David.getFacebook = function(){
    $.get('home/FacebookPhotos', function(data) {
        if(data != ""){
            $("#secondary .left").append(data);
            David.initFacebook();
        } else {
            setTimeout(David.getFacebook(),5000);
        }
    });
};
David.getWildfire = function(){
    $.get('/home/WildfireBanner', function(data) {
        if(data != ""){
            $("#secondary .right").prepend(data);
        } else {
            setTimeout(David.getWildfire(),5000);
        }
    });
};
David.getFoursquare = function(){
    $.get('/home/FoursquareGoogleMap', function(data) {
        if(data != ""){
            if($("#wildfireLaunch").length != 0){
                $("#secondary .right #wildfireLaunch").after(data);
            } else {
                $("#secondary .right").prepend(data);
            }
        } else {
            setTimeout(David.getFoursquare(),5000);
        }
    });
};
David.getSponsors = function(){
    $.get('/home/SponsorsBanner', function(data) {
        if(data != ""){
            $("#secondary .right").append(data);
        } else {
            setTimeout(David.getSponsors(),5000);
        }
    });
};
David.getMasthead = function(){
    $.get('/home/Masthead', function(data) {
        if(data != ""){
            $("#header .left").html(data);
        } else {
            setTimeout(David.getMasthead(),5000);
        }
    });
};
