function indexInArray(arr,val){
for(var i=0;i<arr.length;i++) if(arr[i]==val) return i;
return -1;
}

///////////////////////
// The Stream Object //
///////////////////////
function Stream(name, id, container) {
	var name = name;
	var contId = container;
	var id = id;
	this.getId = function() {
		return id;
	}
	// Some functions
	this.loadVideo = function() {
		$("#"+id).children(".loader").hide();
		$("#"+id).children(".video").show();
	}
	this.draw = function(size) {
		var psize;
		switch (size) {
			case 'xs':
			psize = 80;
			break;
			case 's':
			psize = 160;
			break;
			case 'm':
			psize = 250;
			break;
			case 'l':
			psize = 350;
			break;
			case 'xl':
			psize = 500;
			break;
			case 'xxl':
			psize = 900;
			break;
			default:
			psize = 250;
			break;
		}
		var width = psize;
		var height = width*0.8;
		safe_name = name.replace(/'/g, "").replace(/ /g, "");
		code = '<div class="stream '+size+' online" id='+id+'><a href="lib/profile.php?id='+id+'" rel="lib/profile.php?id='+id+'" class="basic" id="tooltip_'+safe_name+'" title="'+name+'">'+name+'</a><span class="buttons"><a href="javascript:'+contId+'.removeStream('+id+')" class="removeStream">&nbsp;&nbsp;&nbsp;&nbsp;</a></span></a><div class="loader" style="height:'+height+'px">&nbsp;</div><div class="video"><object width="'+width+'" height="'+height+'" id="utv'+id+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value="autoplay=true&amp;brand=embed" name="flashvars"/><param value="true" name="allowfullscreen"/><param value="transparent" name="wmode"/><param value="always" name="allowscriptaccess"/><param value="http://www.ustream.tv/flash/live/1/'+id+'" name="movie"/><embed width="'+width+'" height="'+height+'" type="application/x-shockwave-flash" src="http://www.ustream.tv/flash/live/1/'+id+'" name="utv_n_'+id+'" id="utv'+id+'" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" flashvars="autoplay=true&amp;brand=embed"/></object></div><div class="name"></div></div>';

return code;
	}
	
	this.videoDelay = function(delay){
		var _self = this;
		setTimeout(function(delay){_self.loadVideo()}, delay);
	}
}

/////////////////////
// The Wall Object //
/////////////////////

function Wall(container,contID, size, number, automode, house, chat, head, blacklist) {
	var blacklist = blacklist;
	var house = house;
	var chat = chat;
	var automode = automode;
	var head = 1;
	var onlineStreams;
	var container = container;
	var contId = contID;
	var size = size; // Size of each stream
	var number = number; //The number of streams per page
	if (number == "All") { number = 100; }
	var streams = new Array()
	var newStreams = 0;
	var activePage = 0;
	var numPages = 0;
	function getPage(id) {
		var pageid = $("#"+id).parent().attr("id");
		if (typeof(pageid) == "undefined") {
		var pageNumber = 1;
		} else {
		var pageNumber = (pageid.substr(4)*1);
		}
		return pageNumber;
	}
function getStreams() {
	return streams;
}
function pruneStreams() {
	//this function will remove offline streams
 $(".stream:not(.online)").each(function (){
				  doRemove($(this).attr("id"), false);
});
}
	function setNewPerPage(newPerPage) {
		nnumber = newPerPage;
		if(nnumber == "All"){
			number = "100";
		} else {
			number = nnumber;
		}
		//destroy the stalkerWall
		$(container).html("");
		// Reset Variables
		streams = "";
		streams = new Array();
		var newStreams = 0;
		var activePage = 0;
		var numPages = 0;
		//redraw the wall
		//update preferences
		make();
	}
	function setNewSize(newSize){
		oldSize = size;
		size = newSize;
		var psize;
		switch (size) {
			case 'xs':
			psize = 80;
			break;
			case 's':
			psize = 160;
			break;
			case 'm':
			psize = 250;
			break;
			case 'l':
			psize = 350;
			break;
			case 'xl':
			psize = 500;
			break;
			case 'xxl':
			psize = 900;
			break;
			default:
			psize = 250;
			break;
		}
		var width = psize;
		var height = width*0.8;
		// set the stream a new class
		$(".stream").removeClass(oldSize).addClass(size);
		$(".stream embed, .stream object").css("width", width).css("height", height);
	}
	function rejigStreams(page) {
		//by rejig i mean remove the gaps!
		// page is the page where the first gap can be found (where a stream was removed from)
		//page*1 to force an integer
		var from = (page*1)+1;
		while (from <= numPages) {
			// This loops through each page promoting streams until it reaches the last page
			//get the first stream on the page
			var id = $("#page"+from+" > div:first").attr("id");
			promoteStream(id);
			from++;
		}
		// Check if the last page is empty
		if (numPages == 1 && $("#page1"+" div").length <= 0) {
			$("#page1").append("<div id=\"noStreams\" class=\"roundedContent\">No streams are available</div>");
		} else if ($("#page"+numPages+" div").length <= 0 && numPages >1) {
			// if it is, delete it and lower numpages
			$("#page"+numPages).remove();
			numPages--;
		}
		return true;
	}
	function lastStreamOnPage(page) {
		var theId = $("#page"+page+" > div:last").attr('id');
		return theId;
	}
	function promoteStream(id, front) {
		// Moves a stream up a page!
		var cur = getPage(id);
		var up = cur - 1;
		if (up > 0) {
			// Its not on the first page - its promotion time!
			// Grab the previous page and append a copy of the stream
			if (front == true) {
			$("#page"+up).prepend($("#"+id));
			} else {
			$("#page"+up).append($("#"+id));
			}
			//now remove the old one
			$("#page"+cur+" #"+id).remove();			
		}
	}
	
	function demoteStream(id) {
		//Moves stream down a page
		var cur = getPage(id);
		var down = cur+1;
		if (down <= numPages) {
			// Its not on the last page - its demotion time!
			// Grab the next page and append a copy of the stream
			//actually prepend - its just been demoted atleast let it be at the top of the page!
			$("#page"+down).prepend($("#"+id));
			//now remove the old one
			$("#page"+cur+" #"+id).remove();			
		}
		}
	
	this.pinStream=function(id) {
	while(getPage(id) > 1) {
		var fromPage = getPage(id);
		var toPage = fromPage-1;
		var toDemote = lastStreamOnPage(toPage);
		demoteStream(toDemote);
		promoteStream(id, true);
		fromPage = null;
	}
}
	
	
	function incrementNew() {
		newStreams++;
		return newStreams;
	}
	function setButtons() {
		if (activePage > 1) {
			$("#previousPage").fadeIn("slow");
		} else {
			$("#previousPage").fadeOut("slow");
		}
		if (activePage < numPages) {
			$("#nextPage").fadeIn("slow");
		} else {
			$("#nextPage").fadeOut("slow");
		}
	}
	function setPage(page) {
		if (page <= numPages) {
		if (activePage != 0) {
			$("#page"+activePage).hide();
			$("#page"+page).fadeIn("slow");
		} else {
			$("#page"+page).fadeIn("slow");
		}
		activePage = page;
		setButtons();
		}
	}
	this.getStream = function(index) {
		return this.streams(index);
	}
	function addStream (name, id, delay, page) {
		streams.push(new Stream(name, id, contId));
		if ($("#page"+page).length <= 0 && ($("#page"+(page-1)).length > 0 || page == 1)) {
			$(container).append('<div class="wallPage" id="page'+page+'"></div>');
			$('#page'+page).hide();
		}
		   $("#page"+page).append(streams[streams.length-1].draw(size));
		   streams[streams.length-1].videoDelay(delay);
		   $("#"+id).fadeIn("slow");
		   safe_name = name.replace(/'/g, "").replace(/ /g, "");
		   $("#tooltip_"+safe_name).cluetip({sticky: true, closePosition: "title", waitImage: true, width: "350"});
		   }
	this.removeStream = function(id) {
		doRemove(id, true);
	}
	function doRemove(id, doPerma) {
				for (i=0; i<streams.length; i++){
		if (streams[i].getId()==id) {
			var page = getPage(id);
		$("#"+id).fadeOut("slow").remove();
		streams.splice(i,1);
		// do some perma stuff like add the stream to the blacklist array:
		// first check its not already in the array
		if (!blacklisted(id) && doPerma) {
		blacklist.push(id);
		// and update the users database entry to reflect the changes
		$.post("lib/setPreferences.php",{addBlacklist: id});
		}
		//then carry on witht the boring old UI stuff :P
		rejigStreams(page);
		setButtons();
		// Check that the page they are on is not empty (and also isnt page 1!)
		if (numPages < activePage && activePage != 1) {
			setPage(activePage-1);
		}
	}
		}
	}
		
	function updateOnlineInfo() {
		if (newStreams > 0) {
		$("#options #refresh").html('<a href="javascript:'+contId+'.addNewStreams();"><img src="images/arrow_refresh.png" /> ('+newStreams + ")</a>");
		$("#options #refresh").fadeIn("fast");
		} else {
		$("#options #refresh").fadeOut("fast");
		}			
	}
	
	this.saveOptions = function() {
		if($(".streamsize:gt(0)").val()!=size) {
		setNewSize($(".streamsize:gt(0)").val());
		}
		var tper = $(".perpage:gt(0)").val();
		if (tper == "All") { tper = 100; }
		if(tper != number) {
		setNewPerPage(tper);
		}
	 if($(".automode:gt(0)").attr("checked") == true) {
										 automode = "1";
									 } else {
										 automode = "0";
									 }
	 if($(".housetoggle:gt(0)").attr("checked") == true) {
										 house = "1";
										 $("#hakhouse").fadeIn("slow");
									 } else {
										 house = "0";
										 $("#hakhouse").fadeOut("slow");
									 }
	 if($(".chattoggle:gt(0)").attr("checked") == true) {
										 chat = "1";
										 $("#stalkerChat").fadeIn("slow");
									 } else {
										 chat = "0";
										 $("#stalkerChat").fadeOut("slow");
									 }
	 /*if($(".headtoggle:gt(0)").attr("checked") == true) {
										 head = "1";
										 $("body").css("margin-top", "0px");
										 $("#header").slideDown("slow");
										 			
									 } else {
										 head = "";
										 $("#header").slideUp("slow");
										 			$("body").css("margin-top", "-12px");
									 }*/
	if($(".clearblacklist:gt(0)").attr("checked") == true) {
		clearBlacklistValue = "doit";
		blacklist  = new Array();
	} else {
		clearBlacklistValue = "";
	}
	$.post("lib/setPreferences.php",{streamsize: size, perpage: number, automode: automode, housemode: house, chatmode: chat, headmode:head, clearBlacklist:clearBlacklistValue});
	$.fn.fancybox.close();
	}
	
	this.setOptions = function() {
				//set the correct size as selected
		$(".clearblacklist:gt(0)").attr("checked", false)		
		$(".streamsize:gt(0)").val(size);
		if (automode == 1) {
		$(".automode:gt(0)").attr("checked", true);
		}
		if (house == 0) {
			$("#hakhouse").hide(); 
		} else {
			$(".housetoggle:gt(0)").attr("checked", true);
		}
		if (chat == 0) {
			$("#stalkerChat").hide(); 
		} else {
			$(".chattoggle:gt(0)").attr("checked", true);
		}
		if (head == 0) {
			$("#header").hide();
			$("body").css("margin-top", "-12px");
		} else {
			$(".headtoggle:gt(0)").attr("checked", true);
			$("body").css("margin-top", "0px");
		}
		$(".perpage:gt(0)").val(number);
		if (number > 10) {
			$(".perpage:gt(0)").val("All");
		}
	}
	function make() {
		$('#Simple_Nav').append('<div id="options"><span style="float:left; margin-bottom:-16px;"><a href="javascript:'+contId+'.prevPage()" id="previousPage">&laquo; Previous</a></span><div id="wallPreferences"><a href="#optionsform" class="fancyLong">Options</a>&nbsp;<div id="refresh"></div></div><span style="float: right; margin-bottom:-16px;"><a href="javascript:'+contId+'.nextPage()" id="nextPage">Next &raquo;</a></span><div class="clear">&nbsp</div></div>');
		
		$(container).append('<div id="optionsform" style="display:none"><div class="pageForm wideLabel"><h1>Options</h1><label for="streamsize">Stream Size:</label><select name="streamsize" class="streamsize"><option value="xs">XS</option><option value="s">S</option><option value="m">M</option><option value="l">L</option><option value="xl">XL</option><option value="xxl">XXL</option></select><br /><label for="perpage">Streams Per Page:</label><select name="perpage" class="perpage"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value=9>9</option><option value="10">10</option><option value="All">All</option></select><br /><label for="automode">Automode:</label><input type="checkbox" class="automode" name="automode" /><br /><label for="clearblacklist">Reset Hidden:</label><input type="checkbox" class="clearblacklist" name="clearblacklist" /><br /><input type="button" name="savepref" class="subbut" onclick="streamWall.saveOptions()" value="Save Options"/></div></div>');
		/* USTREAM */
		//$(container).append('<div class="roundedContent fixed" style="width: 800px" id="hakhouse"><object width="400" height="320" id="utv25536" style="float: left" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value="autoplay=false&amp;brand=embed" name="flashvars"/><param value="true" name="allowfullscreen"/><param value="always" name="allowscriptaccess"/><param value="transparent" name="wmode"/><param value="http://www.ustream.tv/flash/live/1/1825" name="movie"/><embed width="400" height="320" type="application/x-shockwave-flash" wmode="transparent" src="http://www.ustream.tv/flash/live/1/1825" name="utv_n_3412" id="utv25536" allowscriptaccess="always" allowfullscreen="true" flashvars="autoplay=false&amp;brand=embed"/></object><object width="400" height="320" id="utv828598" style="float: right" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value="autoplay=false&amp;brand=embed" name="flashvars"/><param value="transparent" name="wmode"/><param value="true" name="allowfullscreen"/><param value="always" name="allowscriptaccess"/><param value="http://www.ustream.tv/flash/live/1/8316" name="movie"/><embed width="400" height="320" wmode="transparent" type="application/x-shockwave-flash" src="http://www.ustream.tv/flash/live/1/8316" name="utv_n_705000" id="utv828598" allowscriptaccess="always" allowfullscreen="true" flashvars="autoplay=false&amp;brand=embed"/></object><div class="clear"></div><div class="clear"></div></div>');
		
		/*$(container).append('<div class="roundedContent fixed" style="width: 800px" id="hakhouse"><object width="400" height="330" bgcolor="#000000" data="http://www.justin.tv/widgets/jtv_player.swf?channel=hakhouse2" id="jtv_player_flash" type="application/x-shockwave-flash" wmode="transparent"><param value="true" name="allowFullScreen"/><param value="always" name="allowscriptaccess"/><param value="http://www.justin.tv/widgets/jtv_player.swf" name="movie"/><param value="channel=hakhouse2&amp;auto_play=false&amp;start_volume=0" name="flashvars"/></object><object width="400" height="330" bgcolor="#000000" data="http://www.justin.tv/widgets/jtv_player.swf?channel=hakhouse" id="jtv_player_flash" type="application/x-shockwave-flash" wmode="transparent"><param value="true" name="allowFullScreen"/><param value="always" name="allowscriptaccess"/><param value="http://www.justin.tv/widgets/jtv_player.swf" name="movie"/><param value="channel=hakhouse&amp;auto_play=false&amp;start_volume=25" name="flashvars"/></object><div class="clear"></div></div>');*/
		
		// Chuck up a loading message
		$(container).append('<div class="wallPage" id="page1">Loading...</div>');
		//update options link
		$(".fancyLong").fancybox({ 'hideOnContentClick': false, 'frameWidth': 350, 'frameHeight': 170});
		streamWall.setOptions();
		//set it to call the function on change
		$.get("lib/gs.php", function(data){
			$("#page1").fadeOut("fast").remove();
			var temp = data.split(",");
			count = 0;
			page = 1;
			numPages = 1;
			
			$.each(temp, function(i, streamzors){
				var peoples = streamzors.split(":");
				theirid = peoples[1];
				theirname = peoples[0];
				if(!blacklisted(theirid)) {
					count++;
					if (count > number) {
						page++;
						numPages++;
						count = 1;
					}
					addStream(theirname, theirid, 2000*i, page);		   
				}
		  });
		  
		 if (count == 0 && numPages == 1) {
   			$(container).append('<div class="wallPage" id="page1"></div>');
			$("#page1").append("<div id=\"noStreams\" class=\"roundedContent\">No streams are available</div>");
		  }
		  setPage(1);
		  $('.wallPage').sortable({revert: true, opacity: 0.5, handle: '.name'});
		  
		 });
	}

	this.draw = function() {
		make();
	}
	this.prevPage = function() {
		if (activePage != 1) {
		setPage(activePage-1);
		}
	}
	this.nextPage = function() {
		if (activePage < numPages) {
		setPage(activePage+1);
		}
	}
	this.checkNewStreams = function() {
		newStreams = 0;
		$.getJSON("lib/getStreams.php",
        function(data){
			setOnline(data);
			$.each(data, function(i, stream){
			if(!displayed(stream.id) && !blacklisted(stream.id)) {
     	    incrementNew();
			}
		});
		if (automode == 1) {
		doStreamUpdate();
		} else {
		updateOnlineInfo();
}

		});
	}
	function setOnline(data) {
		onlineStreams = data;
	}
	function doStreamUpdate() {
				// Add new streams to the page
	$(".stream").removeClass("online");
	$("#noStreams").remove();
	$.each(onlineStreams, function(i, stream) {
		$("#"+stream.id).addClass("online");
		if(!displayed(stream.id) && !blacklisted(stream.id)) {	
			page = numPages;
			if (((getStreams().length+1)/numPages) > number) {
				page++;
				numPages++;
			}
           addStream(stream.name, stream.id, i*1000, page);
		}
	});
		  setButtons();
  		  $('.wallPage').sortable({revert: true, opacity: 0.5, handle:'.name'});
 		$("#options #refresh").fadeOut("fast");
		pruneStreams();
		if ($("#page1"+" div").length <= 0) {
			if ($("#page1").length <= 0) {
		$(container).append('<div class="wallPage" id="page1"></div>');
			}
		$("#page1").append("<div id=\"noStreams\" class=\"roundedContent\">No streams are available</div>");
	}
}
	this.addNewStreams = function() {
	doStreamUpdate()
	}
	
	function blacklisted(id) {
		var blackd = false;
		for(i=0; i<blacklist.length; i++) {
			if (blacklist[i] == id) {
				blackd = true;
				break;
			}
		}
		return blackd;
	}
	
	function displayed(id){
		// check if stream id 'id' is curently being displayed
		var there = false;
	for (i=0; i<streams.length; i++){
	if (streams[i].getId()==id) {
		there =  true;
		break;
	}
	}
	return there;
} 
}
