﻿apiCallsLeft = 0;
//displayMatrix = [9, 9, 9, 11, 11, 11];
//colEnds = ["1979px","515px","1979px","149px","881px","149px"];
displayMatrix = [3, 3, 3, 5, 5, 5];
//colEnds = ["881px","515px","881px","149px","881px","149px"];
colEnds = ["844px","478px","844px","112px","844px","112px"];
var totalShown = 0;
timeBetweenLaunch = 300;
searching = false;
prevPageURL = "";
var MinTweetID=999999999999999;
var MaxTweetID=0;


$(document).ready(function() {
    //This sets up the search box interactions
    $("#search-criteria").each(function() {
        var id = $(this).attr("id"), 
            $label = $("label[for="+id+"]");
        
        //If the value is prefilled (user hit back button), hide the label.   
        if($(this).val() != "") { 
            $label.hide(); 
        } 
         
        //Add interactions for label field.
        $(this).focus(function() { 
            $label.addClass("focus"); 
        }); 
        $(this).blur(function() { 
            $label.removeClass("focus"); 
        });
        
        //Add interactions for key presses.
        $(this).bind("keydown", function(e) { 
            if(e.keyCode >= 48 ) { 
                $label.hide(); 
            } else if(e.keyCode == 13) {
                $(".search-button").click();
                return false;
            }
        }); 
        $(this).bind("keyup", function() { 
            if($(this).val() == "") { 
                $label.show(); 
            } 
        });
    });
    
    //Make powered by link work.
    $(".powered-by-box").click(function() {
        window.open("http://www.victorsandspoils.com");
    });
    
    //Make sort link work.
    $(".search-button").click(function() {
        MaxTweetID=0;
        MinTweetID=99999999;
        totalShown=0;
        $(".previous-pages").html("");
        FindTweets($("#search-criteria").val(), MinTweetID);
        searching = true;
    });
    
    //Make the see more suggestions button work.
    $(".see-more").click(function() {
        ShowPreviousPage($("#search-criteria").val());
    });
       
    
    //Make the back to top button work.
    $(".back-to-top").click(function() {
    	jQuery("html,body").animate({scrollTop: '0px'}, 1000, 'swing'); 
    });
    
    //Get the number of API calls available and then call FindTweets if there are calls available.
    CheckAPILimit("FindTweets");
});

function CheckAPILimit(cbFunc) {
    if(cbFunc == "FindTweets") {
        FindTweets($("#search-criteria").val());
    } else if(cbFunc == "GetNewTweets") {
        GetNewTweets($("#search-criteria").val());
    }
}

function FindTweets(searchCrit) {
    $("body").css("cursor", "wait");
    $.ajax({
           type: "POST", 
           url: "api/get_tweets.aspx", 
           data: {lastid:MaxTweetID, criteria:searchCrit,type:"N"},
           dataType: "json",
           success: function(data){
                if (data == null || data.tweets.length==0){
                    alert("We're sorry, there are no tweets that match your search terms.");
                }else{
                    $(".more-tweets").hide();    
                    //Clear out whatever is in there already.
                    ClearTweets();
                    //Get the position of the big box.
                    var logoOffset = $(".logo").position();
                    logoOffset.left -= $("#tweet-container").position().left;
                    logoOffset.top -= $("#tweet-container").position().top;
                    var startX = logoOffset.left + 2;
                    var startY = parseInt(logoOffset.top + $(".logo").innerHeight()) + 25;
                    var firstStart = startY;
                    //Store the last ID so the next call will use it.
                    
                    //Loop through and create the tweet boxes.
                    var col = 0;
                    var row = 0;
                    var bigColHit = false;
                    
                    for(var i=0; i<data.tweets.length; i++) {
                        MaxTweetID= parseInt(data.tweets[i].id)>MaxTweetID ? parseInt(data.tweets[i].id) : MaxTweetID;
                        MinTweetID= parseInt(data.tweets[i].id)<MinTweetID ? parseInt(data.tweets[i].id) : MinTweetID;
                        totalShown+=1;
                        //Calculate the x/y pos
                        var x = startX + (col * (141 + (col > 0 ? 23 : 0)));
                        var y = startY + (row * (163 + (row > 0 ? 20 : 0)));
                    
                        $("#tweet-container").append(
                            $("<div></div>").attr("id", data.tweets[i].id).attr("class", "tweet-box").attr("row", row).attr("col", col)
                                        .html("<p class='tweet'>" + data.tweets[i].tweet + "</p><p class='name'><a href=\"http://twitter.com/home?status=@" + data.tweets[i].fromuser + "%20\" target=\"_blank\">@" + data.tweets[i].fromuser + "</a></p>")
                                        .css({left:startX+"px",top:firstStart+"px",display:"none"}));
                               
                        var theTO = 0;
                        theTO = ((data.tweets.length * timeBetweenLaunch)-(i * timeBetweenLaunch));
                        setTimeout("ShowTweet(" + data.tweets[i].id + "," + col + "," + row + "," + x + "," + y + ")", theTO);
                                            
                        if(col%2==0) {
                            row++;
                        } else {
                            row--;
                        }
                        if(row == displayMatrix[col] || row == -1) {
                            col++;
                            if(col%2==0) {
                                row = 0;
                            } else {
                                row = displayMatrix[col]-1;
                            }
                            if(displayMatrix[col] > displayMatrix[0] && !bigColHit) {
                                //Now that we're in the columns past the big box.  Reduce the startY.
                                startY -= 366;
                                bigColHit = true;
                            }
                        }
                    }
                    if (data.tweets[0].total> totalShown){
                        $(".more-tweets").show();
                        $(".see-more").show();
                        $(".back-to-top").hide();                      
                    }
                    setTimeout("PollTweets()", 30000);
                }    
            }, 
            error: function(xhr, errorStr, errorThrown) {
                alert(errorStr);
            } 
            });
        $("body").css("cursor", "default");        
            
}

function ShowTweet(tweetID, endCol, endRow, endX, endY) {
    //$("#" + tweetID).slideDown(100);
    var tweet = $("#"+tweetID);
    tweet.slideDown(100);
    
    var curCol = 0;
    var animStr = "";
    for(var i=0; i<=endCol; i++) {
        var animateToY = colEnds[i];
        if(i==endCol) {
            animateToY = endY;
            animStr += ".animate({top:'" + animateToY + "'},250)";
        } else {
            curCol++;
            var logoOffset = $(".logo").position();
            logoOffset.left -= $("#tweet-container").position().left;
            var nextX = logoOffset.left + 2 + (curCol * (141 + (curCol > 0 ? 23 : 0)));
            animStr += ".animate({top:'" + animateToY + "'},250).animate({left:'" + nextX + "'},100)";
        }
    }
    eval("tweet"+animStr+";");
}

function PollTweets() {
   CheckAPILimit("GetNewTweets");
}

function GetNewTweets(searchCrit) {
    $("body").css("cursor", "wait");
    $.ajax({
           type: "POST", 
           url: "api/get_tweets.aspx", 
           data: {lastid:MaxTweetID, criteria:searchCrit,type:"N"},
           dataType: "json",
           success: function(data){
                //Get the position of the big box.
                var logoOffset = $(".logo").position();
                logoOffset.left -= $("#tweet-container").position().left;
                logoOffset.top -= $("#tweet-container").position().top;
                var startX = logoOffset.left + 2;
                var startY = parseInt(logoOffset.top + $(".logo").innerHeight()) + 25;
                var firstStart = startY;
            
                if(data.tweets.length > 0) {
                    //Loop through and create the tweet boxes.
                    var col = 0;
                    var row = 0;
                    var bigColHit = false;
                    for(var i=(data.tweets.length-1); i>=0; i--) {
                        MaxTweetID= parseInt(data.tweets[i].id)>MaxTweetID ? parseInt(data.tweets[i].id) : MaxTweetID;
                        MinTweetID= parseInt(data.tweets[i].id)<MinTweetID ? parseInt(data.tweets[i].id) : MinTweetID;
                        totalShown+=1;
                        //Lets figure out which row and column this one should ultimately live in.
                        var curNum = i;
                        while(curNum > displayMatrix[col]) {
                            curNum -= displayMatrix[col];
                            col++;
                        }
                        row = curNum;
                        //Add this new tweet to the page.
                        $("#tweet-container").prepend(
                            $("<div></div>").attr("id", data.tweets[i].id).attr("class", "tweet-box").attr("row", row).attr("col", col)
                                        .html("<p class='tweet'>" + data.tweets[i].tweet + "</p><p class='name'><a href=\"http://twitter.com/home?status=@" + data.tweets[i].fromuser + "%20\" target=\"_blank\">@" + data.tweets[i].fromuser + "</a></p>")
                                        .css({left:startX+"px",top:firstStart+"px",display:"none"}));
                
                        //Now animate everything down and around.
                        ShuffleTweets(true);
                    }
                    if (data.tweets[0].total> totalShown){
                        $(".see-more").show();
                        $(".back-to-top").hide();   
                    }else{
                        $(".see-more").hide();
                    } 
                }
                //Set a timer to call again.
                setTimeout("PollTweets()", 30000);
            }, 
            error: function(xhr, errorStr, errorThrown) {
                alert('Error:' + errorStr);
            } 
            });
        $("body").css("cursor", "default");            
}

function ShuffleTweets(killLast) {
    var animSpeed = 500;
    if(killLast == null) {
        killLast = false;
    }
    $("#tweet-container div").each(function() {
        $b = $(this);
        if($b.css("display") == "none") {
            $b.slideDown(animSpeed);
        } else {
            if(parseInt($b.attr("col")) == (displayMatrix.length-1) && parseInt($b.attr("row")) == 0 && killLast) {
                //This is the very last div of the page, kill it.
                $b.fadeOut(animSpeed);
            } else {
                var logoOffset = $(".logo").position();
                var nextX = logoOffset.left + 2 + (parseInt($b.attr("col")) * (141 + (parseInt($b.attr("col")) > 0 ? 23 : 0)));
                //var nextY =  + (row * (163 + (row > 0 ? 20 : 0)));
                if(parseInt($b.attr("col")) % 2 == 0) {
                    //If they're in an even row, push down.
                    if(parseInt($b.attr("row")) == (displayMatrix[parseInt($b.attr("col"))]-1)) {
                        //This is the last box in this column, push right.
                        $b.animate({left:"+=164"},animSpeed).attr("col", parseInt($b.attr("col"))+1).attr("row", (displayMatrix[parseInt($b.attr("col"))]-1));
                    } else {
                        //Not the last box, push down.
                        $b.animate({top:"+=183"},animSpeed).attr("row", parseInt($b.attr("row"))+1);
                    }
                } else {
                    //If they're in an odd row, push up.
                    if(parseInt($b.attr("row")) == 0) {
                        //This is the first box in this column, push right.
                        $b.animate({left:"+=164"},animSpeed).attr("col", parseInt($b.attr("col"))+1);
                    } else {
                        //Not the first box, push up.
                        $b.animate({top:"-=183"},animSpeed).attr("row", parseInt($b.attr("row"))-1);
                    }
                }
            }
        }
    });
}

function ShowPreviousPage(searchCrit) {
    $("body").css("cursor", "wait");
    $.ajax({
           async: false,
           type: "POST", 
           url: "api/get_tweets.aspx", 
           data: {lastid:MinTweetID, criteria:searchCrit,type:"P"},
           dataType: "json",
           success: function(data){
                if(data.tweets.length > 0) {
                    for(var i=0; i<data.tweets.length; i++) {
                        MaxTweetID= parseInt(data.tweets[i].id)>MaxTweetID ? parseInt(data.tweets[i].id) : MaxTweetID;
                        MinTweetID= parseInt(data.tweets[i].id)<MinTweetID ? parseInt(data.tweets[i].id) : MinTweetID;
                        totalShown+=1;
                        $(".previous-pages").append(
                                $("<div></div>").attr("id", data.tweets[i].id).attr("class", "tweet-box")
                                            .html("<p class='tweet'>" + data.tweets[i].tweet + "</p><p class='name'><a href=\"http://twitter.com/home?status=@" + data.tweets[i].fromuser + "%20\" target=\"_blank\">@" + data.tweets[i].fromuser + "</a></p>")
                                            .css({position: "static",display:"inline-block",marginRight:"23px",marginBottom:"20px"})
                        );
                    }
                    $(".previous-pages").slideDown(1000, function() {
                    //Figure out if there are more, if not switch the see more suggestions to back to top.
                    if(data.tweets[0].total>totalShown) {
                	    $(".see-more").show();
                	    $(".back-to-top").hide();
               	    } else {
               		    $(".see-more").hide();
               		    $(".back-to-top").show();
               	    }
                });
                }
            }, 
            error: function(xhr, errorStr, errorThrown) {
                alert(errorStr);
            } 
    });
    $("body").css("cursor", "default");
     

}

function ClearTweets() {
    $("#tweet-container div").fadeOut("fast").remove();
}

function CleanVariable(str) {
    str = str.replace(" ", "+");
    str = escape(str);
    return str;
}
