
function initCodeChannel(token,clientid,codekey,projectkey) {
	
	channel = new goog.appengine.Channel(token);
    socket = channel.open();
	
    
    this.token = token;
    this.clientid = clientid;
    this.projectkey = projectkey;
    this.codekey = codekey;

	onOpen = function() {
		sendMessage({"type":"welcome","msg":"I have arrived!"});
	};
	
	onMessage = function(messageObject){
		
		var obj = $.parseJSON(messageObject.data);

		switch(obj.type){
		
		case 'welcome':
			//do nothing right now
			//alert(obj.msg);
			break;
		case 'save':
			//update the file, there must be a file key associated with it if its the case.
			refreshfile(obj.codekey);
			break;
		case 'edit':
			//Started editing, focus, update the top line above.
			//TODO get the events from bespin about cursor position and line row and selection.
			var username = obj.author;
			$('#filestatus').html(username+' is editing the file right now.');
				
		
		
		}
		
		
	};
	
	//messageCounter.scrollIntoView();
	
	onError = function() {
		alert('error');
	};
	
	onClose = function() {
		alert('closed');
	};
	
	sendMessage = function(jsonobj) {

		var clientparamjson = {msgobj: jsonobj, clientid: clientid,projectkey: projectkey ,codekey: codekey};

		var json = escape($.toJSON(clientparamjson));	
		
		$.ajax({
			url: '/api/channel/sendmessage',
			type: 'POST',
			cache: false,
		    data:'jsonObj='+json,
            contentType: "application/json; charset=utf-8",  
			dataType: 'json',
			success: function(response){			
			
			},
			error: function() {
				
			}
		});
	};
	
	sendButtonClicked = function() {
		if (($("#message").val() == '') || ($("#message").val() == 'message')) {
			alert('Please enter a message');
		} else if (($("#name").val() == '') || ($("#name").val() == 'name')) {
			alert('Please enter a name');
		} else {
			sendMessage('<strong>'+$("#name").val()+'</strong>: '+$("#message").val());
			$("#message").val('');
		}
	};
	
	keyPressed = function() {
		try {
			if (event.keyCode == '13') {
				sendButtonClicked();
			}
		} catch (e) {}
	};
	
	nameOnFocus = function() {
		$("#name").val('');
	};
	
	messageOnFocus = function() {
		$("#message").val('');
	}

	 socket.onopen = onOpen;
	    socket.onmessage = onMessage;
	    socket.onerror = onError;
	    socket.onclose = onClose;

}

function copyToTextarea() {
   $('#editorinandout').val() = _editorComponent.getContent();
}
 
function copyToEditor() {
    _editorComponent.setContent($('#editorinandout').val());
}



function cursorMove(position)
{
	alert(position.toSource());
	$('#filestatus').html(position.toSource());

}

function savefile(filekey) {
	
	
	$('#editor').val();
	
	
	$('#filestatus').html('Saving file');
	var currentcode = editor.getCode();
	$('#editorinandout').fieldSerialize();
	$('#editorinandout').val(currentcode);
	$('#formfile').ajaxForm();

	$('#formfile').ajaxSubmit();
	
	$('#filestatus').html('File saved!');
	setTimeout('$("#filestatus").html("");',5000);
	
	
	
	$.ajax({
		type: "POST",
		url: "/api/file/save",
		data: "filekey=" + filekey +"&editorinandout="+currentcode,
		success: function(msg){
			
			if (msg != null) {
				
	
			$('#filestatus').html('File saved');
			
			
			//refreshfile(filekey);
			
			var jsonObj = {"type": "save", "codekey" : filekey}
			//var json = escape($.toJSON(jsonObj));	
			sendMessage(jsonObj);
								
			}
			else {
				
				$('#filestatus').html('Something went wrong!');
			
				
			}
			
		

			
		}
	});
	
	
}


function refreshfile(filekey) {
	
	$('#filestatus').val('Refreshing file');

	$.ajax({
		type: "POST",
		url: "/api/file/refresh",
		data: "filekey=" + filekey,
		success: function(msg){
			
			if (msg != null) {
				
				var code = $.parseJSON(msg);
				$('#editor').val(code);
				editor.setCode(code);
				$('#filestatus').html('File refreshed!');
				setTimeout('$("#filestatus").html("");',5000);
		
			}
			else {
				
				$('#filestatus').html('w00t! theres a problem!');
			
				
			}
			
		

			
		}
	});
	
	
}

function submitComment(projectkey,divid,status)
{
	
	var commentbody = $('#statusbody').val()
	
	$.ajax({
				type: "POST",
				url: "/api/streamcomment",
				data: "pkey=" + projectkey +"&body="+commentbody+"&status="+status,
				success: function(msg){
					
					if (msg != null) {
						
			
					$('#statusbody').val('');
					
					getStream(projectkey,divid);
										
					}
					else {
						
						$('#statusbody').val('Something went wrong!');
					
						
					}
					
				
	
					
				}
			});	
	
	
	
}

function getStream(projectkey,divid)
{
	
	$('#'+divid).html('Hold on while we fetch the project stream..');

	docheight = $(document).height();

	$.ajax({
		type: "POST",
		url: "/api/getprojectstream",
		data: "pkey=" + projectkey +"",
		success: function(msg){
			
			if (msg != null) {
				
				$('#'+divid).css('height', docheight - 260+'px');
				//$('#'+divid).animate({ scrollTop: $("#"+divid).attr("scrollHeight") }, 3000);
				$('#'+divid).html(msg);
			
				//Set timer to rerun the function for auto refresh
				
				//setInterval("getStream('"+projectkey+"','"+divid+"')", 10000);
								
			}
			else {
				

				
			}
			
		

			
		}
	});		
	
	
}



function googleConnect(siteid){
	
	google.friendconnect.container.setParentUrl('/rpc_relay.html' /* location of rpc_relay.html and canvas.html */);
	google.friendconnect.container.initOpenSocialApi({
	site: siteid, /* put here your site ID */
	onload: function(securityToken) {
	if (!window.timesloaded) {
	window.timesloaded = 1;
	} else {
	window.timesloaded++;
	}
	
		if (window.timesloaded > 1) { /* on the second reload redirect to profile page */

				window.top.location.href = "/api/user/friendconnect";
				
		}
	
	}
	
	});
	
	
}




function initWaveFromDb(codekey)
{
	$('#status').html('Please wait while we do some magic.');
	$.ajax({
			type: "POST",
			url: "/api/checkwaveid",
			data: "codekey=" + codekey +"",
			success: function(msg){
			
			//Check if the wave id is returned
			
			$('#status').html('Got response.');
				
				if (msg != null) {
					
					
				$('#status').html(msg);
				window.top.location.href = '/session/'+codekey+'';
									
				}
				else {
					
					$('#status').html('Checking again...');
			
					
					initWaveFromDb('' + codekey + '');
					
				}
				
			

				
			}
		});
	
}

function FBConnectFront() {

 
 FB.Bootstrap.requireFeatures(["Connect"], function() { 
 //Prod
 FB.init("d8e8e7f3873dcc631dfe72df510e97f2","/fbconnect/xd_receiver.htm");
 //Debug app
 //FB.init("25987af3dce906e42c93b131a52e2dad","/fbconnect/xd_receiver.htm");
 //FB.Connect.requireSession(false);

 //FB.Connect.showPermissionDialog("email"); 
 
 });
  

}


function FBConnect() { 
 

 
 FB.Bootstrap.requireFeatures(["Connect"], function() { 
 //Prod
 FB.init("d8e8e7f3873dcc631dfe72df510e97f2","/fbconnect/xd_receiver.htm");
  //Debug app
  //FB.init("25987af3dce906e42c93b131a52e2dad","/fbconnect/xd_receiver.htm");

 //FB.Connect.showPermissionDialog("email"); 
  FB.Connect.ifUserConnected(update_user_box);

 
 });
 
 
 
 
}

function FBConnectAppReg() {
 
 FB.Bootstrap.requireFeatures(["Connect"], function() { 
 //Prod
 FB.init("d8e8e7f3873dcc631dfe72df510e97f2","/fbconnect/xd_receiver.htm");
  //Debug app
 //FB.init("25987af3dce906e42c93b131a52e2dad","/fbconnect/xd_receiver.htm");

 //FB.Connect.showPermissionDialog("email"); 
 FB.Connect.ifUserConnected(updateAppRegTable);

 
 });
 
 
 
}


function updateAppRegTable() { 

		var user_box = document.getElementById("user"); 
		var firstrow = document.getElementById("firstnamerow");
		var lastrow = document.getElementById("lastnamerow");
		var passwordrow = document.getElementById("passwordrow");
		var emailrow = document.getElementById("emailrow");
		var invitekeyrow = document.getElementById("fbinvitekeyrow");
 		//var uid = FB.Facebook.apiClient.get_session().uid;
 		
 		
 		FB.Bootstrap.requireFeatures(["Connect"], function() { 
		 //Prod
		 FB.init("d8e8e7f3873dcc631dfe72df510e97f2","/fbconnect/xd_receiver.htm");
		  //Debug app
		 //FB.init("25987af3dce906e42c93b131a52e2dad","/fbconnect/xd_receiver.htm");
		
		 //FB.Connect.showPermissionDialog("email"); 
		// FB.Connect.ifUserConnected(updateAppRegTable);
		 		var fbuser = FB.Connect.get_loggedInUser();

		 
		 });
 		
 		
 		var uid = fbuser;
		firstrow.style.display = 'none';
		lastrow.style.display = 'none';
		emailrow.style.display = 'none';
		passwordrow.style.display = 'none';
		invitekeyrow.style.display = 'none';
		$('fbflag').value = 'true';
		//invitekeyrow.style.display = 'none';
		//fbuidinput.value = uid;

		// add in some XFBML. note that we set useyou=false so it doesn't display "you" 
		user_box.innerHTML = "<span style='font-size:18px;color:#4C67A1'>" 
		+ "Welcome, <fb:name uid=loggedinuser useyou=false></fb:name>. You are signed in with your Facebook account for workforoptions.<br>"
		+ '<span style="font-size:18px;color:#4C67A1">'
		+ "</span></span>";
		
		user_box.style.display = '';
		// because this is XFBML, we need to tell Facebook to re-process the document 
		FB.XFBML.Host.parseDomTree();


} 


