var currentlyPlaying = null;
var currentlyRecording = null;
var currentlyStreaming = null;
var lastMessageID=0;
var owner_id=null;

function closeTBAndRefresh (user_id){
	tb_remove();
	$('#add_contents').hide();
	$('#spinner').show();
	if (user_id==null) user_id="";
}

function showAddContents(){
	$('#add_contents').show();
}

function checkForThumbs(id) {
	interval = setInterval( function () { 
					$.get ('/images/checkThumbStatus/' + id,null, function (data, textStatus) {
						if (data != 0) {
							$('.thumb_profile' + id).attr("src",data);
							clearInterval(interval);
						}
					}) 
				},  
				60000); 
}

function chatServer(id) {
	owner_id=id;
	interval = setInterval(
					function () {
						$.ajax ({
							type: "GET",
							url: '/chats/latest/' + id + '/' + lastMessageID,
							dataType: "json",
							success: function(data, textStatus){
								$.each(data, function(i,item){
									$('#chat_window').append ('<div id="message_' + item.Chat.id + '"><span id="name">' + item.Chat.name + '</span>: <span id="message">' + item.Chat.message + '</span></div>')
									lastMessageID = item.Chat.id;
								});
								
							},
							error: function(XMLHttpRequest, textStatus, errorThrown){
								
							}
						})	
					}, 3000);
}

function addChat(){
	var data = new Object();
	data.owner_id = owner_id;
	data.message=$('#chat_message').val();
	$('#chat_message').val("");
	$.ajax({
		type: "POST",
		url: '/chats/add/',
		dataType: "json",
		data: data,
		success: function(data, textStatus){
			
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
		
		}
	})
}									
									

function streamVideo (event) {
	if (currentlyStreaming) removeFlash(currentlyRecording, "stream");
	insertFlash (this,"stream", 320,240);
	return false;
}
function recVideo (event) {
	if (currentlyRecording) removeFlash(currentlyRecording, "rec");
	//insertFlash (this,"rec",200,150);
	insertFlash (this,"rec", 320,240);
	return false;
}
function playVideo (event) {
	if (currentlyPlaying) removeFlash(currentlyPlaying, "play");
	//insertFlashPlayer (this,"play",200,150);
	insertFlashPlayer (this,"play",320,240);
	return false;
}
function playSmallVideo (event) {
	if (currentlyPlaying) removeFlash(currentlyPlaying, "play");
	//insertFlashPlayer (this,"play",200,150);
	insertFlashPlayer (this,"play",160,120);
	return false;
}
function viewStream (event) {
	if (currentlyPlaying) removeFlash(currentlyPlaying, "play");
	insertFlashPlayer (this,"play_stream",320,240);
	return false;
}
function viewSmallStream (event) {
	if (currentlyPlaying) removeFlash(currentlyPlaying, "play");
	//insertFlashPlayer (this,"play_stream",150,88);
	insertFlashPlayer (this,"play_stream",160,120);
	return false;
}
function insertFlash(player, flash_mode, w,h){
	$(player).children(".videoThumb").hide();
	$(player).children(".smallVideoThumb").hide();
	if (flash_mode=="play") $(player).children(".playButtonOver").hide();
	else $(player).children(".recButtonOver").hide();
	$(player).children(".flashMovieHolder").flash(
			{ 
	          src: '/flash/FlashRecorder.swf',
	          width: w,
	          height: h,
	          backgroundColor: "#ffffff",
	          flashvars: { filename: $(player).attr ('href'), width : w, height: h, mode: flash_mode }
	        },
	        { version: 8 }
	);
	if (flash_mode=="play") currentlyPlaying = player;
	else if (flash_mode=="record") currentlyRecording = player;
	else currentlyStreaming = player;
	$(player).unbind();
	return false;
}
function insertFlashPlayer(player,flash_mode,w,h){
	$(player).children(".videoThumb").hide();
	$(player).children(".smallVideoThumb").hide();
	$(player).children(".playButtonOver").hide();
	$(player).children(".flashMovieHolder").flash(
			{ 
	          src: '/flash/FlashRecorder.swf',
	          width: w,
	          height: h,
			  backgroundColor: "#ffffff",
	          flashvars: { filename: $(player).attr ('href') , width : w, height: h, mode: flash_mode}
	        },
	        { version: 8 }
	);
	currentlyPlaying = player;
	$(player).unbind();
	return false;
}
function clearRecording () {
	if (currentlyRecording) removeFlash(currentlyRecording, "rec");
}
function removeFlash (player, mode){
	$(player).children(".flashMovieHolder").children("embed").remove();
	$(player).children(".flashMovieHolder").removeClass ("flash-replaced");
	$(player).children(".videoThumb").show();
	$(player).children(".smallVideoThumb").show();
	$(player).children(".playButtonOver").show();
	if (mode=="rec") {
		$(player).bind ("click", recVideo);
		currentlyRecording=null;
	} else {
		$(player).bind ("click", playVideo);
		currentlyPlaying=null;
	}
}

function showThumbPreview (id) {
	$.get ('/images/getThumb/' + id,null, function (data, textStatus) {
		if (data != 0) {
			$('.thumb_profile' + id).attr("src",data);
			$('#preview.thumb').attr("src",data);
			$('#closeAndRefresh').show();
			clearInterval(interval);
		}
	}) 
}
function closeAndRefreshLink () {
	tb_remove();
	window.location.reload();
}

function makeThumbs(id) {
 	$('#image.spinner').show();
	$.ajax ({
		type: "GET",
		url: '/images/generate_thumb/' + id,
		dataType: "script",
		success: function(data, textStatus){
			if (data != 0) {
				$('.thumb_profile' + id).attr("src", data);
			}
			$('#image.spinner').hide();
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			$('#image.spinner').hide();
		}
	}); 
}

function openProgressBar() {
	$('#progress').show();
	$('#upload_thumb').show();
	
	/* generate random progress-id */
	uuid = "";
	for (i = 0; i < 32; i++) {
	  uuid += Math.floor(Math.random() * 16).toString(16);
	}
	/* patch the form-action tag to include the progress-id */
	//document.getElementById("ImageAddForm").action=document.getElementById("ImageAddForm").action + "?X-Progress-ID=" + uuid;
	$(".addImageForm")[0].action=$(".addImageForm")[0].action + "?X-Progress-ID=" + uuid;
	
	/* call the progress-updater every 1000ms */
	interval = window.setInterval( function () {  fetch(uuid);  }, 1000 );
}

function fetch(uuid) {
	req = new XMLHttpRequest();
	req.open("GET", "/progress", 1);
	req.setRequestHeader("X-Progress-ID", uuid);
	req.onreadystatechange = function () {
	if (req.readyState == 4) {
	  if (req.status == 200) {
	    /* poor-man JSON parser */
	    var upload = eval(req.responseText);
	
	    //document.getElementById('tp').innerHTML = upload.state;
	
	    /* change the width if the inner progress-bar */
	    if (upload.state == 'done' || upload.state == 'uploading') {
	      bar = document.getElementById('progressbar');
	      w = 200 * upload.received / upload.size;
	      bar.style.width = w + 'px';
	    }
	    /* we are done, stop the interval */
	    if (upload.state == 'done') {
	      window.clearTimeout(interval);
		  $('#progress').hide();
		  //window.location=""; //redirect somewhere
	    }
	  }
	}
	}
	req.send(null);
}

function nextStep () {
	$("#message_submit").show();
}

function validate_message () {
	console.log ($('#text'));
	if ($("#text").val().length > 0) return true;
	else alert ("Please enter a title for this message."); 
	return false;
}

function validate_comment () {
	if ($("#comment").val().length > 0) return true;
	else alert ("Please enter a title for this reply."); 
	return false;
}


$(document).ready(function() {
	$(".videoPlayLink").bind ("click", playVideo);
	$(".smallVideoLink").bind ("click", playSmallVideo);
	$(".streamPlayLink").bind ("click", viewStream);
	$(".smallStreamPlayLink").bind ("click", viewSmallStream);
	$(".videoStreamLink").bind ("click", streamVideo);
	$(".videoRecLink").bind ("click", recVideo);
	//$("#login").load("/users/login/");
});