//var consumables;
var window_width;
var window_height;
var cont_width;
var cont_count;
var scrollTop;
var yOffset;
var min = 150;
var max = 350;
var margin = 20;
var scrollbar_min = 20;
var scrollbar_height = 0;
var getting_data = false;
var item_start = 0;
var img_count = 0;
var img_counter = 0;
var container_number = 0;
var info_timeout;
var items_per_screen = 40;
var scrollTopMultiplier = 1;
var scrollTopSubtractor = 0;
/*var key_user = 0;
var own_page = false;
var loggedIn = false;*/
  
$(document).ready(function() {

	window_height = $(window).height();

	if ($("#left_container").length > 0) {
		var right_width = $("#right_container").outerWidth();
		var width_to_use = $(window).width() - right_width - 60;
		window_width = width_to_use;
		$(".content_header").width(width_to_use - 20);
		min = 150;
		max = 250;	
	}
	else {
		window_width = $(window).width() - margin - getScrollbarWidth();
	}
	
	$("#full_container").width(window_width - 20);
	$("#full_container .content_header").width(window_width - 20);  
   
  cont_count = 1;
  
  while (Math.round((window_width / cont_count) - margin) < min || Math.round((window_width / cont_count) - margin) > max && !(cont_count > 10)) {
  	$("div#content").append("<div id='container" + cont_count +"' class='container'></div>");
  	cont_count++;
  }
  
  cont_width = Math.round((window_width / cont_count) - margin);
  $("div#content").width(window_width + margin);
  $("div.container").width(cont_width);
  $("div#info").width(cont_width);
  
  if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) { 
	items_per_screen = 20;
	scrollTopSubtractor = 600;
	$(".more .button_container").width(cont_width - 8);
  }
  
  if (typeof(consumable_users) != "undefined") {
  	fillUsers(consumable_users);
  }
  else if (typeof(consumables) != "undefined") {
  	fill(consumables);
  }
  else {
  	$.get('/retrieve_some.php?user=' + key_user + '&count=' + items_per_screen + '&start=' + item_start, '', function(data) {
  	eval("var consumables = " + data);
    fill(consumables);
  	});
  }
  
  $("#logo").toggle(function() {
    $("#about").slideDown();
  }, function() {
    $("#about").slideUp();
  });
  
  $("#more_link").click(function() {
    $(".more").fadeOut();
    getting_data = true;
		$.get('/retrieve_some.php?user=' + key_user + '&count=' + items_per_screen + '&start=' + item_start, '', function(data) {
			eval("var consumables = " + data);
      		fill(consumables);
		});
    return false;
  });
  
  $("#info").css("opacity", 0);
  
  $("a.undelete").live("click", function() {
  	var post_id = $(this).attr("href").replace("#", '');
  	$(this).parent().hide().parent().css("background-image", "url(/assets/img/loader.gif)");
  	var that = $(this);
  	$.get('/undo_delete.php?post=' + post_id, '', function(undone) {
  		if(undone) {
  			that.parent().parent().children("a").children("img").animate({opacity: 1.0});
  		}
  	});
  	return false;
  });
  
  $(window).scroll(function() {
    if (window.pageYOffset) scrollTop = window.pageYOffset;
    else scrollTop = $(window).scrollTop();
  	$("img.invisible_post_image").each(function() {
  		if (isVisible($(this))) {
    		var img_src = $(this).parent("a").attr("alt");
    		$(this).attr("src", img_src).removeClass("invisible_post_image").addClass("post_image");
    	}
    });
  });
  
  $(document).bind("touchmove", function() {
    scrollTopMultiplier = 2;
  });
  
  $(window).resize(function() {
  	window_height = $(window).height();  
  });
  
});

function iVisible(img) {
  alert(img.parent().offset().top - (scrollTop * 2));
  alert(window_height);
  return ((img.parent().offset().top - (scrollTop * 2)) <= window_height);  
}

function fillUsers(users) {
	$("div.container").html("");
	if (users.length > 0) {
	for (var i in users) {
		var user = users[i];
		var user_info = document.createElement('div');
		
		user_info.className = "user_info";
		var user_name = document.createElement('div');
		user_name.className = "user_name";
		user_name.innerHTML = "<a href='/" + user.user_name + "'>" + user.user_name + "</a>";
		user_info.appendChild(user_name);
		
		if (user.location) {
			var user_location = document.createElement('div');
			user_location.className = "user_location";
			user_location.innerHTML = user.location;
			user_info.appendChild(user_location);
		}
		
		if (user.bio) {
			var user_bio = document.createElement('div');
			user_bio.className = "user_bio";
			user_bio.innerHTML = user.bio;
			user_info.appendChild(user_bio);
		}
		
		var following = false;
		if (user.key_relationship) following = true;	
		var follow_status = document.createElement('div');
		follow_status.className = "follow_status";
		if (following) follow_status.innerHTML = "You are following " + user.user_name + ".";
		else follow_status.innerHTML = "You are not following " + user.user_name + ".";
		user_info.appendChild(follow_status);
		
		shortestContainer().append(user_info);	
	}
	}
	else {
		shortestContainer().append("<div class='user_info'>No results.</div>");
	}
}

function fill(consumables) {
  image_count = 0;
  
  if (consumables.length > 0) { 
  for (var i in consumables) {  
      
    if (consumables[i].filename) {
      image_count++;
      var img = new Image();
      var link = document.createElement('a');
      var div = document.createElement('div');
      var info_div = document.createElement('div');
      info_div.className = 'post_info';
      img.className = 'invisible_post_image';
      
      var img_server = parseInt(consumables[i].filename.substr(0, consumables[i].content.indexOf('.')), 16) % 4 + 1;
      
      var width = consumables[i].width;
      var height = consumables[i].height;
      
      if (width > cont_width) {
      	var ratio = cont_width / width;
      	width = cont_width;
      	height = height * ratio;
      }
      
      if (consumables[i].title) {
	      $(info_div).append("<div class='inner_post_info'>" + consumables[i].title + "</div>");
      }
      
      if (consumables[i].users) {
      	var posted_by = "<div class='posted_by'>posted by: ";
      	for (var j in consumables[i].users) {
      		if (j > 0) posted_by += ", ";
      		posted_by += "<a class='user_link' href='/" + consumables[i].users[j] + "'>" + consumables[i].users[j] + "</a>";
      	}
      	posted_by += "</div>";
      	$(info_div).append(posted_by);       
      }  
      
      $(div).mouseenter(function() {
	      	var this_height = $(this).height();
	      	var animate_height = $(this).outerHeight();
	      	$(this).find(".post_info").css("top", (this_height / 2) - (animate_height / 2)).stop().animate({height: animate_height + "px"}, 200);
	      }).mouseleave(function() {
	        var this_height = $(this).height();
	        var animate_height = $(this).outerHeight();
	      	$(this).find(".post_info").stop().animate({height: animate_height + "px"}, 50, function() {
            $(this).animate({top: (this_height / 2) + (animate_height / 2), height: "0px"}, 200);
          });
	      });
      
      $(link).attr("alt", '/stream/' + cont_width + '/' + consumables[i].filename);

      img.del = function() {
        var filename = $(this).attr("src").substr($(this).attr("src").lastIndexOf("/") + 1);
    		$(this).css("opacity", 0.50);
    		$(this).siblings(".post_info").css("opacity", 0);
    		clearTimeout(info_timeout);
    		var that = $(this);
    		$.get('/delete.php?filename=' + filename, '', function(deleted_key) {
      			if (deleted_key > 0) {
      				that.animate({opacity: 0.25}, function() {
      				  var post_container = that.parents("div.post_container");
      				  post_container.css("background-image", "none");
      					post_container.append("<div class='deleted'>DELETED<br /><a href='#" + deleted_key + "' class='undelete'>Undo?</a>");
      				});
      			}
    		});
      }
      
      img.undel = function() {
      
      }
      
      img.add = function() {
      	var filename = $(this).attr("src").substr($(this).attr("src").lastIndexOf("/") + 1);
      	$(this).css("opacity", 0.50);
      	clearTimeout(info_timeout);
    		$(this).attr("alt", "");
    		$("#info").css("opacity", 0);
    		var that = $(this);
    		$.get('/add.php?filename=' + filename, '', function(added_key) {
      			if (added_key > 0) {
      				that.animate({opacity: 1.00}, function() {
      					var post_container = that.parents("div.post_container");
      					post_container.append("<div class='added'>ADDED</a>");
      				});
      			}
    		});
      }
      
      
      var post_controls = document.createElement("div");
      post_controls.className = "post_controls";
      
      var add_button = document.createElement("a");
      add_button.innerHTML = "+";
      add_button.style.float = "left";
      add_button.style.lineHeight = "35px";
      add_button.title = "Add this post to your page";
      
      var del_button = document.createElement("a");
      del_button.innerHTML = "-";
      del_button.style.float = "left";
      del_button.style.paddingTop = "5px";
      del_button.title = "Remove this post from your page";
      
      var permalink_button = document.createElement("a");
      permalink_button.innerHTML = "&#8734;";
      permalink_button.style.cssFloat = "right";
      permalink_button.style.paddingTop = "5px";
      permalink_button.style.paddingRight = "12px";
      permalink_button.title = "Permalink to this post";
      permalink_button.href = "/post/" + consumables[i].key_post;
      
      $(add_button).click(function() {
      	$(this).parent().parent().siblings("img.post_image").trigger("add");
      	return false;
      });
      
      $(del_button).click(function() {
      	$(this).parent().parent().siblings("img.post_image").trigger("del");
      	return false;
      });
      
      $(permalink_button).click(function(evnt) {
      	var e = (window.event) ? window.event : evnt;
		e.cancelBubble = true;
		window.location.href = $(this).attr("href");
		return false;
      });
      
      if (own_page) post_controls.appendChild(del_button);
      else if (loggedIn) post_controls.appendChild(add_button);
      post_controls.appendChild(permalink_button);
      $(info_div).append(post_controls);
      
      img.width = width;
      img.height = height;
      link.href = consumables[i].source;
      link.target = "_blank";
      link.className = "post";
      $(link).attr("date", consumables[i].date);
      
      $(img).hide();
      $(link).append(img);
      $(link).append(info_div);
      
      div.className = "post_container";
      $(div).attr("date", consumables[i].date);
      $(div).append(link);
      
      if (consumables[i].via_title) {
        $(div).append("<div class='via'>Via: <a href='" + consumables[i].via_link + "'>" + consumables[i].via_title + "</a></div>");
      }
      
      div.style.height = height + "px";      
      insertByDate($(div), shortestContainer());
       
      $(img).load(function() { 
      	var that = $(this);        
        if ($("img:animated").length > 4) setTimeout(function() { that.trigger("load") }, 100);
      	else {
      		$(this).fadeIn(250);
        	image_count--;
        }
      });
    }
    else if (consumables[i].content.indexOf('<object') != -1) {
    	var div = document.createElement('div');
    	div.className = 'post_container';
    	$(div).attr("date", consumables[i].date);
    	$(div).attr("alt", consumables[i].title);
    	$(div).append(consumables[i].content);
    	$(div).children("object, embed").each(function() {
    		var width = $(this).attr("width");
    		var height = $(this).attr("height");
    		if (width > cont_width) {
    			var ratio = cont_width / width;
    			$(this).attr("width", cont_width);
    			$(this).attr("height", height * ratio);
    		}
    	});
    	insertByDate($(div), shortestContainer());
    	if ($(div).attr('alt') != "") {
        $(div).children("object").mousemove(function(event) {
          var xCoord = 18;
          var yCoord = ($('#info').height() / 2) + 2;
          
          if (container_number == (cont_count - 1))
            xCoord = 0 - $('#info').width() - 35;
            
        	$('#info').css("top", event.pageY - yCoord).css("left", event.pageX + xCoord);
        }).mouseover(function() {
          container_number = $(this).parents(".container").attr("id").replace("container", "");
          $('#info').html($(this).parents('div').attr('alt')).show();
        }).mouseout(function() {
        	$('#info').hide();
        });
      }
    }
    else {
      var quote = document.createElement('div');
      var author = document.createElement('div');
      
      quote.className = "quote";
      author.className = "author";
      $(quote).attr("date", consumables[i].date);
      
      if (consumables[i].content.length > 100)
      	$(quote).addClass("long");
      
      $(quote).hide().html(unescape(consumables[i].content));
      $(author).html(consumables[i].source);
      $(quote).append(author);
      insertByDate($(quote), shortestContainer());
      $(quote).fadeIn();
    }       
  }
  
  	if (consumables.length < items_per_screen) { }
  	else {
    	item_start = item_start + items_per_screen;
    	getting_data = false;
    	$(".more").fadeIn();
  	}
  	
  	setTimeout(function() { $(window).trigger("scroll") }, 1);
  }
  else { 
  	shortestContainer().append("<div class='user_info'>No results.</div>");
  }
}

function shortestContainer() {
  var container;
  
  $(".container").each(function() {
    if (!container || $(this).height() < container.height())
      container = $(this);  
  });
  
  return container;
}

function insertByDate(toInsert, whichContainer) {
  /*if (user_name == "tim" || user_name == "jeff") {
    whichContainer.children('.loader').before(toInsert);
  }
  else {
    var nextEarliest;
    if (!toInsert.attr("date")) { }
    else {
    var thisDate = mysqlTimeStampToDate(toInsert.attr("date"));
    whichContainer.children(".quote, .post_container").each(function() {
      var nextDate = mysqlTimeStampToDate($(this).attr("date"));
      if (!nextEarliest && (nextDate < thisDate)) {
        nextEarliest = $(this);
      }
    });
    }
    
    if (!nextEarliest)
      whichContainer.append(toInsert);
    else
      nextEarliest.before(toInsert);
  }*/
  whichContainer.append(toInsert);
}

function getScrollbarWidth() {
  var scr = null;
     var inn = null;
     var wNoScroll = 0;
     var wScroll = 0;
     scr = document.createElement('div');
     scr.style.position = 'absolute';
     scr.style.top = '100px';
     scr.style.left = '100px';
     scr.style.width = '200px';
     scr.style.height = '150px';
     inn = document.createElement('div');
     inn.style.width = '100%';
     inn.style.height = '200px';
     scr.appendChild(inn);
     document.body.appendChild(scr);
     scr.style.overflow = 'hidden';
     wNoScroll = inn.offsetWidth;
     scr.style.overflow = 'scroll';
     wScroll = inn.offsetWidth;
     if (wNoScroll == wScroll) wScroll = scr.clientWidth;
     document.body.removeChild(document.body.lastChild);
     var a = (wNoScroll - wScroll);
     return a;
}

function mysqlTimeStampToDate(timestamp) {
    var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
    var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
    return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}

function isVisible(img) {
	return ((img.parent("a").offset().top - (scrollTop * scrollTopMultiplier) - scrollTopSubtractor) <= (window_height));
}

function setUserID(id) {
	key_user = id;
}

function setOwnPage(isOwnPage) {
	own_page = isOwnPage;
}

function setLoggedIn(isLoggedIn) {
	loggedIn = isLoggedIn;
}