$(document).ready(function() {
	// ICON HOVERS
	$(".expand").hover(function() {
		$(this).attr("src", "/img/icons/expand_h.png");
	}, function() {
		$(this).attr("src", "/img/icons/expand.png");
	});
	$(".reply").livequery(function() {
		$(this).hover(function() {
			$(this).attr("src", "/img/icons/reply_h.png");
		}, function() {
			$(this).attr("src", "/img/icons/reply.png");
		});
	});
	$(".ambassadors").hover(function() {
		$(this).attr("src", "/img/icons/flag_h.png");
		$(".ambassador_link a").addClass("a_hover");
	}, function() {
		$(this).attr("src", "/img/icons/flag.png");
		$(".ambassador_link a").removeClass("a_hover");
	});
	$(".ambassador_link").hover(function() {
		$(".ambassadors").attr("src", "/img/icons/flag_h.png");
	}, function() {
		$(".ambassadors").attr("src", "/img/icons/flag.png");
	});
		
	// TWITTER ROLLOVERS
    $(".twitter_post").livequery("mouseover", function() {
    	$(this).addClass("tweet_hover");
	});
	$(".twitter_post").livequery("mouseout", function() {
		$(this).removeClass("tweet_hover");
	});
	
	
	// TWITTER RETRIEVE POSTS	
    // Declare variables to hold twitter API url and user name
    var twitter_api_url = 'http://search.twitter.com/search.json';
    var twitter_user    = 'metaphorage';
    
    var number_print_tweets = 5;
    if (number_tweets == 0)
    	number_tweets = number_print_tweets;
    var number_tweet_retries = 3;
    var tweet_retries = 0;
    
    $(".twitter_post p").html("<img src=\"/img/loader.gif\" />").children("img").css({"margin-bottom": "-17px"});
    $(".twitter_post .timestamp").html("");
    
    createTweets();
    
    function createTweets() {
    	$(".twitter_post:last").clone().insertAfter($(".twitter_post:last"));
    	if ($(".twitter_post").length < number_print_tweets) {
    		createTweets();
		}
	}

    // Enable caching
    $.ajaxSetup({ cache: true });

    // Send JSON request
    // The returned JSON object will have a property called "results" where we find
    // a list of the tweets matching our request query
    var tweet_timeout;
    tweet_timeout = setTimeout(twitter_timeout, 10000);
    getTweets();
    
    function twitter_timeout() {
        tweet_retries++;
        if (tweet_retries < number_tweet_retries) {
            tweet_timeout = setTimeout(twitter_timeout, 10000);
            getTweets();
        } else {
    	    $(".twitter_post").each(function(ind,ele) {
    		    if ($(ele).children("p").children("img").length > 0) {
    			    $(ele).fadeOut(100,function() {
    				    $(ele).remove();
				    });
			    }
		    });
        }
	}
    
    function getTweets() {
        $.getJSON(
            twitter_api_url + '?callback=?&rpp='+number_tweets+'&q=from:'+twitter_user,
            function(data) {
        	    var rel_i = 0;
        	    $.each(data.results, function(i, tweet) {
        		    if ((i-rel_i)==(number_print_tweets-1)) {
        			    clearTimeout(tweet_timeout);
				    }
        		    if(tweet.text !== undefined) {
                	    var tweetDate = new Date(tweet.created_at);
                	    var tweet_time = tweetDate.getTime()/1000;

                	    $.post("/webpages/code/upload_tweet.php", {
						    "timestamp": tweet_time,
						    "tweetID": tweet.id,
						    "username": twitter_user,
						    "content": tweet.text
					    });
					    
					    if (i<=(number_print_tweets-1)) {
                            if ($(".twitter_post:eq("+(i-rel_i)+")").children("p").children("img").length == 0)
                                return true;
                	    
                		    var tweet_text = tweet.text;
                		    tweet_text = tweet_text.replace(/\u00a0/g," ");
                		    tweet_text = tweet_text.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,"<a href=\"$1\">$1</a>");
                		    tweet_text = tweet_text.replace(/[\@]+([A-Za-z0-9-_]+)/gi,"<a href=\"http://twitter.com/$1\">@$1</a>");
                		    tweet_text = tweet_text.replace(/(?:^| )[\#]+([A-Za-z0-9-_]+)/gi,' <a href="http://search.twitter.com/search?q=&tag=$1&lang=all&from='+tweet.from_user+'">#$1</a>');

                		    var reply = "<a title=\"Reply\" href=\"http://twitter.com/?status=@"+tweet.from_user+"%20&in_reply_to_status_id="+tweet.id+"&in_reply_to="+tweet.from_user+"\"><img class=\"right reply\" alt=\"reply\" src=\"/img/icons/reply.png\" /></a>";
                		    
                		    $.post("/framework/time.php", {"time": tweet_time, "short": 1}, function(timestamp) {
                			    var ind = i - rel_i;
							    $(".twitter_post:eq("+ind+")").children("p").html(tweet_text);
							    $(".twitter_post:eq("+ind+")").children(".timestamp").html(timestamp+reply);
							    
							    $(".twitter_post:eq("+ind+")").children("p").css({"opacity": 0});
							    $(".twitter_post:eq("+ind+")").children(".timestamp").css({"opacity": 0});
							    
							    $(".twitter_post:eq("+ind+")").children("p").animate({"opacity": 1.0}, 250, function() {
								    $(this).css("opacity","");	
							    });
							    $(".twitter_post:eq("+ind+")").children(".timestamp").animate({"opacity": 1.0}, 250, function() {
								    $(this).css("opacity","");
							    });
						    });
					    }
                    } else {
                	    if (i<=number_tweets) {
                		    $(".twitter_post:eq("+i+")").remove();
                		    rel_i++;
					    }
				    }
			    });
            }
        );
    }
    
    /*
    // BLOG Image resizing
    $("#blog_content").children("img").each(function(ind,ele) {
    	var ww = $(ele).outerWidth();
    	var hh = $(ele).outerHeight();
    	
    	var new_w = 212;
    	var new_h = Math.round(hh * (212 / ww));

    	$(ele).css("width",new_w);
    	$(ele).css("height",new_h);
    	$(ele).css("display","block");
	});
	*/
});
