// create the upload age ("3 minutes ago")
function makeUploadAge(time_value) {
	// split up the incoming date format
	var values = time_value.split(" ");
	var v2 = values[0].split("-");
	// some browsers won't parse the date if the month is a number
	// so here we swap the number for the short form, plus we can use these later when displaying the date
	switch(v2[1]) {
		case "01": v2[1] = "Jan"; break;
		case "02": v2[1] = "Feb"; break;
		case "03": v2[1] = "Mar"; break;
		case "04": v2[1] = "Apr"; break;
		case "05": v2[1] = "May"; break;
		case "06": v2[1] = "Jun"; break;
		case "07": v2[1] = "Jul"; break;
		case "08": v2[1] = "Aug"; break;
		case "09": v2[1] = "Sep"; break;
		case "10": v2[1] = "Oct"; break;
		case "11": v2[1] = "Nov"; break;
		case "12": v2[1] = "Dec"; break;
	}
	// recreate the date
	time_value = v2[1]+" "+v2[2]+", "+v2[0]+" "+values[1];
	// turn it into a date object
	var parsed_date = Date.parse(time_value);
	// find out the time right now
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	// get the difference between the two
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	// determine what information to show based on the elapsed time
	var r = '';
	if (delta < 2) {
		r = translate[0][0];
	} else if(delta < 60) {
		r = translate[0][1];
	} else if(delta < 120) {
		r = translate[0][2];
	} else if(delta < (45*60)) {
		r = (parseInt(delta / 60)).toString() + ' '+translate[0][3];
	} else if(delta < (2*90*60)) { // 2* because sometimes read 1 hours ago
		r = translate[0][4];
	} else if(delta < (24*60*60)) {
		r = (parseInt(delta / 3600)).toString() + ' ' + translate[0][5];
	} else if(delta < (48*60*60)) {
		r = '1 '+translate[0][6];
	} else if(delta < (6*24*60*60)) {
		r = (parseInt(delta / 86400)).toString() + ' '+translate[0][7];
	} else {
		r = v2[1]+" "+v2[2]+", "+v2[0];
	} 
	// return the upload age
	if (exactDate == true) {
		var time = values[1].split(':');
		if (time[0] > 12) {
			time[0] = time[0]-12;
			time[2] = "pm";
		} else {
			time[2] = "am";
		}
		var dt = v2[1]+" "+v2[2]+", "+v2[0]+" "+time[0]+":"+time[1]+time[2];
		return dt;
	} else {
		return r;
	}
}

// update the upload times
function updateDateTime() {
	// grab all the <abbr> tags
	$$('#fmCommentsWrapper abbr').each(function(e) {	
		// update the value with the new time
		e.innerHTML = makeUploadAge(e.title);
	});
}

function getDateTime() {	
	// create the date object
	var t = new Date();
	// format it in the correct way
	t = t.getFullYear()+"-"+(t.getMonth()+1)+"-"+t.getDate()+" "+t.getHours()+":"+t.getMinutes()+":"+t.getSeconds();
	// return the date and time
	return t;
}

// create the form validator
var ValidatorForm = new FMFormValidate();
ValidatorForm.addValidationErrorListener(function(element, message) {
	handleValidation(element,message); return false;
});


function getCommentCount(id) {	
	var params = { "id" : id }
	jsonPRequest('media.getFileInfo', params,
		function(result){
			// get the correct number of comments based on the moderation setting
			if (moderation == "post") {
				x = result.notdeniedcomments;
			} else {
				x= result.approvedcomments;
			}
			// display the comment count
			$('fmCommentCount').innerHTML = x+" "+translate[1][0];
		}
	);
}


// Containers

var loginForm = '<div id="loginformContainer" class="fmFormbox"><form action="http://mf.staging.filemobile.com/services/json" method="post" id="loginform" onSubmit="dologin()"><ul><li class="label">Username</li><li><input type="text" name="username"  id="fmLoginUsername" class="fmTextInput fmInput required"></li><li class="label">Password</li><li><input type="password" name="password" id="fmLoginPassword" class="fmTextInput fmInput required"></li><li class="label"><br/><input type="button" value="Login" onclick="dologin()" class="fmButton"></li></ul></form></div>';

var commentForm = new Template('<div id="uploadFormWrapper" class="fmFormbox"><form id="uploadForm" action=""><ul><li class="label"><label for="description">Comment</label></li><li><textarea class="fmTextarea required" id="description" name="message" title="Comment"></textarea></li></ul><input type="hidden" name="parent" id="parent" value="#{parentId}"><input type="hidden" name="username" id="username" value="#{username}" /><input type="hidden" name="userid" id="userid" value="#{userid}" /></form><br/><div id="uploadStatus"><ul><li class="label">'+translate[3][4]+'</li></ul><a id="uploadBtn" class="fmButton select_file" href="#" onclick="return false;"><div id="flashSelectFile" style="display:block; position: absolute;"></div> '+translate[3][1]+' <span id="selectFileBtn"></span></a><div id="fileList"></div><br style="clear:both"/><div style="margin-top:20px;"><a class="fmButton" onclick="this.blur(); Uploader.startUpload(); return false;">'+translate[2][4]+'</a> <a class="fmButton" id="fmCancelUpload">'+translate[3][2]+'</a></div></div><div id="postUpload"></div><div class="fmClear"></div><div id="loader" style="display:none">'+translate[3][3]+'</div></div>');

var anonCommentForm = new Template('<div class="fmFormbox" id="anonCommentformContainer"><form id="fmPostAnonComment" onsubmit="if (!ValidatorForm.submit(this)) { return false; } else { postanoncomment(#{parentId}, $(\'comment_author\').value, $(\'comment_email\').value, $(\'comment_comment\').value, this); return false;};"><ul><li class="label"><label for="comment_author">'+translate[2][1]+'</label></li> <li><input type="text" name="author" id="comment_author" class="fmTextInput fmInput required"/></li><li class="label"><label for="comment_email">'+translate[2][2]+'</label></li> <li><input type="text" name="email" id="comment_email" class="fmTextInput fmEmail fmInput required"/></li><li class="label"><label for="message">'+translate[2][3]+'</label></li> <li><textarea name="message" id="comment_comment" class="fmTextArea fmTextarea required"></textarea></li><li class="label"><br/><input type="submit" value="'+translate[2][4]+'" class="fmButton"/></li></ul></form></div>');

var registerForm = '<div style="display:none" id="fmCommentRegister" class="fmFormbox"><form><h2>Register</h2><ul><li class="label"><label for="username">Username *</label></li><li><input type="text" class="fmTextInput fmUsername fmInput required checkUnique" id="username" name="user" title="Username" /></li><li class="label"><label for="firstname">First name *</label></li><li><input type="text" class="fmTextInput fmInput required" id="firstname" name="firstname" title="First name" /></li><li class="label"><label for="lastname">Last name *</label></li><li><input type="text" class="fmTextInput fmInput required" id="lastname" name="lastname" title="Last name" /></li><li class="label"><label for="email">Email *</label></li><li><input type="text" class="fmTextInput fmEmail fmInput required checkUnique" id="email" name="email" title="Email" /></li><li class="label"><label for="password">Password *</label></li><li><input type="password" class="fmTextInput fmPassword fmInput required" id="password" name="password" title="Password" /></li><li class="label"><label for="confirmpassword">Confirm password *</label></li><li><input type="password" class="fmTextInput fmPasswordConfirm fmInput" id="confirmpassword" /></li><li class="label"><label for="captcha">Captcha</label></li> <li><span id="captcha_captcha"><img alt="captcha" src="http://www.filemobile.com/services/captcha?rand=891932b2f0bff0b1b7800f6f79436e80"/></span> <input type="text" name="captcha" class="fmCaptcha fmCaptcha" id="captcha"/></li><li class="label"><br/><input type="submit" class="fmButtonSm" value="Create"/></li> </ul></form></div>';

var formInfo = '<div class="fmCommentRight" id="fmFormInfo"> <div class="inside"> <h4>Want to quickly add a comment?</h4><a class="fbcbutton" href="#"><img src="http://wiki.developers.facebook.com/images/5/55/Connect_white_medium_long.gif" alt="" facebook="" connect=""/></a> Why use Facebook Connect? <ul> <li>No need to create another account</li> <li>Quickly post comments on all of our stories</li> <li>Allow your Facebook friends to see the comments you make on your wall</li> </ul> </div> </div>';

if (profiles) {

	var commentBlock = new Template('<div class="fmComment fmClearfix"><div class="fmUser fmClearfix"> <a href="'+translate[4][0]+'#{profileid}" class="fmAvatar"> <img src="http://mediafactory.fm/static/1/images/global/male.gif" /> </a> <div class="fmInfo fmClearfix"> <a href="'+translate[4][0]+'#{profileid}" class="fmName">#{username}</a> <abbr title="#{upload}" class="fmTimestamp">#{uploadage}</abbr> </div> </div><div class="fmContent">#{comment}</div><div class="fmRating"> <div class="fmValue" id="vote#{mid}">#{votecount}</div><a class="fmLike" onclick="like(#{mid}, #{uinid} )">'+translate[1][9]+'</a> </div></div>');
	
	var commentBlockWithImage = new Template('<div class="fmComment fmClearfix"><div class="fmUser fmClearfix"> <a href="'+translate[4][0]+'#{profileid}" class="fmAvatar"> <img src="http://mediafactory.fm/static/1/images/global/male.gif" /> </a> <div class="fmInfo fmClearfix"> <a href="'+translate[4][0]+'#{profileid}" class="fmName">#{username}</a> <abbr title="#{upload}" class="fmTimestamp">#{uploadage}</abbr> </div> </div><div class="fmContent"><img src="#{image}/14">#{comment}</div><div class="fmRating"> <div class="fmValue" id="vote#{mid}">#{votecount}</div><a class="fmLike"  onclick="like(#{mid}, #{uinid} )">'+translate[1][9]+'</a> </div></div>');

	var commentBlockWithVideo = new Template('<div class="fmComment fmClearfix"><div class="fmUser fmClearfix"> <a href="'+translate[4][0]+'#{profileid}" class="fmAvatar"> <img src="http://mediafactory.fm/static/1/images/global/male.gif" /> </a> <div class="fmInfo fmClearfix"> <a href="'+translate[4][0]+'#{profileid}" class="fmName">#{username}</a> <abbr title="#{upload}" class="fmTimestamp">#{uploadage}</abbr> </div> </div><div class="fmContent"><object style="width: 320px; height: 240px;" id="null" class="null" data="http://www.filemobile.com/static/widgets/videoplayerv2/videoplayer_v2.swf" type="application/x-shockwave-flash" allowscriptaccess="always"><param value="http://www.filemobile.com/static/widgets/videoplayerv2/videoplayer_v2.swf" name="movie"/><param value="true" name="allowFullScreen"/><param value="always" name="allowScriptAccess"/><param value="mid=#{mid}&sessiontoken='+fm.cookies.getCookie('SABRE_ID')+'" name="FlashVars"/></object><br/>#{comment}</div><div class="fmRating"> <div class="fmValue" id="vote#{mid}">#{votecount}</div><a class="fmLike"  onclick="like(#{mid}, #{uinid} )">'+translate[1][9]+'</a> </div></div>');

} else {
	
	var commentBlock = new Template('<div class="fmComment fmClearfix"><div class="fmUser fmClearfix"> <span class="fmAvatar"> <img src="http://mediafactory.fm/static/1/images/global/male.gif" /> </span> <div class="fmInfo fmClearfix"> <span class="fmName">#{username}</span> <abbr title="#{upload}" class="fmTimestamp">#{uploadage}</abbr> </div> </div><div class="fmContent">#{comment}</div><div class="fmRating"> <div class="fmValue" id="vote#{mid}">#{votecount}</div><a class="fmLike" onclick="like(#{mid}, #{uinid} )">'+translate[1][9]+'</a> </div></div>');
	
	var commentBlockWithImage = new Template('<div class="fmComment fmClearfix"><div class="fmUser fmClearfix"> <span class="fmAvatar"><img src="http://mediafactory.fm/static/1/images/global/male.gif" /> </span> <div class="fmInfo fmClearfix"> <span class="fmName">#{username}</span> <abbr title="#{upload}" class="fmTimestamp">#{uploadage}</abbr> </div> </div><div class="fmContent"><img src="#{image}/14">#{comment}</div><div class="fmRating"> <div class="fmValue" id="vote#{mid}">#{votecount}</div><a class="fmLike"  onclick="like(#{mid}, #{uinid} )">'+translate[1][9]+'</a> </div></div>');
	
	var commentBlockWithVideo = new Template('<div class="fmComment fmClearfix"><div class="fmUser fmClearfix"> <span class="fmAvatar"><img src="http://mediafactory.fm/static/1/images/global/male.gif" /> </span> <div class="fmInfo fmClearfix"> <span class="fmName">#{username}</span> <abbr title="#{upload}" class="fmTimestamp">#{uploadage}</abbr> </div> </div><div class="fmContent"><object style="width: 320px; height: 240px;" id="null" class="null" data="http://www.filemobile.com/static/widgets/videoplayerv2/videoplayer_v228.swf" type="application/x-shockwave-flash" allowscriptaccess="always"> <param value="http://www.filemobile.com/static/widgets/videoplayerv2/videoplayer_v228.swf" name="movie"/> <param value="true" name="allowFullScreen"/> <param value="always" name="allowScriptAccess"/> <param value="mid=#{mid}&amp;sessionToken='+fm.cookies.getCookie('SABRE_ID')+'" name="FlashVars"/> </object><br/>#{comment}</div><div class="fmRating"> <div class="fmValue" id="vote#{mid}">#{votecount}</div><a class="fmLike"  onclick="like(#{mid}, #{uinid} )">'+translate[1][9]+'</a> </div></div>');

}

// Global vars

var externalid = location.href.substr(7,location.href.length);
var parentId = 0;
var code = '';
var moderationStatus = 1;
if(moderation == 'post') moderationStatus = 3;
var start = 0;
var sort = 'upload DESC';
if (translate[4][1]) sort = translate[4][1];
if (pagesize > 500) pagesize = 500;

function initApp(userIn) {
	// Get parent media and get its comments
	jsonPRequest('media.getFiles', {"filters":{ 'externalid' : externalid }, "noCache":true},
    	function(result) {
    		if(result.totalCount > 0) {
    			parentId = result.data[0].id;
    			// if avatars are turned off, hide them in the list by adding the 'fmNoAvatar' CSS class
    			if (!avatar) {
    				$('fmComments').addClassName('fmNoAvatar');
    			}
    			// create the list of comments
			  	renderComments(userIn.id, start);
			  	// create the elements around the comments list
			  	initHeader(userIn, parentId, start);
    		} else {
    			// if there isn't a parent media for this URL, tell the user there is no comments then create the parent media
    			$('fmComments').innerHTML = '<div id="nocomments">'+translate[1][5]+'</div>';
    			var params = {"fileData" : {'title':externalid, 'message':'Parent media for comments on ' + externalid, 'externalid':externalid } }
				jsonPRequest('media.insertTextFile', params,
					function(result4) { initHeader(userIn, result4, start);},
					function(exception)  { console.log('Error: Unable to create a new parent, reload the app');},
					true
				);
    		}
    	},
    	function(exception)  {
    		// oops, something went wrong
    		console.log(exception);
    	},
    	true
  	);
}


function renderComments(uid, sortOpt, sortted) {
	if(!sortOpt){ sort = window.sort } else { sort = sortOpt };
	if(sortted == true) start = 0;
	// swap the text on the 'more comments' button with a loading image
	if ($('fmMoreCommentsBtn')) {
		$('fmMoreCommentsBtn').innerHTML = '<img src="images/loading.gif" alt="'+translate[3][3]+'" />';
	}
	jsonPRequest('media.getFiles', {"sort":sort, 'limit':pagesize, 'start':start, 
	"filters":{'parentid':parentId, 'context':'comment', 'moderationStatus':moderationStatus }, 
	'fields':['filetype', 'uid', 'user_name', 'votecount', 'author', 'upload', 'message', 'publicUrl', 'status'],
	"noCache":true},
		function(result2) {
			// up the counter
			start = start + pagesize;
			// there are comments
			if(result2.totalCount > 0) { 
				var data = result2.data;
				// if the page is new or the person has changed the sort options, remove all the old comments from the list
				if (start <= pagesize) {
					$('fmComments').innerHTML = "";
				}
				data.each( 
					function (currentComment) { 
						//build a comment from the template
						if(currentComment.status) {
							//need to get the file data to get the author
							if(currentComment.uid == 1) {
								var comment = {'username':currentComment.author, 'comment':currentComment.message, 'votecount':currentComment.votecount, 'upload':currentComment.upload, 'uploadage':makeUploadAge(currentComment.upload), 'mid':currentComment.id, 'uinid':uid, 'profileid':currentComment.uid};
					   			var renderedComment = commentBlock.evaluate(comment); 
							}
							else {
								// if the comment is a text only comment, use the text comment template
								// else, use the media comment template
								if (currentComment.filetype == 4) {
									var comment = {'username':currentComment.user_name, 'comment':currentComment.message, 'votecount':currentComment.votecount, 'upload':currentComment.upload, 'uploadage':makeUploadAge(currentComment.upload), 'mid':currentComment.id, 'uinid':uid, 'profileid':currentComment.uid};
					   				var renderedComment = commentBlock.evaluate(comment); 
								} else if (currentComment.filetype == 1) {
									var comment = {'username':currentComment.user_name, 'comment':currentComment.message, 'image':currentComment.publicUrl, 'votecount':currentComment.votecount, 'upload':currentComment.upload, 'uploadage':makeUploadAge(currentComment.upload), 'mid':currentComment.id, 'uinid':uid, 'profileid':currentComment.uid};
					   				var renderedComment = commentBlockWithImage.evaluate(comment); 
								} else {
									var comment = {'username':currentComment.user_name, 'comment':currentComment.message, 'image':currentComment.publicUrl, 'votecount':currentComment.votecount, 'upload':currentComment.upload, 'uploadage':makeUploadAge(currentComment.upload), 'mid':currentComment.id, 'uinid':uid, 'profileid':currentComment.uid};
					   				var renderedComment = commentBlockWithVideo.evaluate(comment); 
								}
							}
							// insert the comment into the list
							$('fmComments').insert(renderedComment);
					   	}
					}
				);
				// hide the more comments button if there aren't any more comments to load
				if (data.length < pagesize || start == result2.totalCount ) {
					$('fmMoreCommentsBtn').hide();
				} else {
					$('fmMoreCommentsBtn').show();
				}
				// replace the text on the more comments button
				if ($('fmMoreCommentsBtn')) {
					$('fmMoreCommentsBtn').innerHTML = translate[1][4];
				}
			} else {
				// display the message that there are no comments yet
				$('fmComments').innerHTML = '<div id="nocomments">'+translate[1][5]+'</div>';
			}
		},
		function(exception2) {	
			// something went wrong, tell us
			console.log(exception2);
		},
		true
	);
}

// 
function tabs(e) {
	// get all <li> elements
	$(e).up(0).childElements().each(function(t,i) {
		if (e==t) {
			// show the tab the user just clicked on
			if ($('fmTab'+i)) {
				$('fmTab'+i).show();
				$(e).addClassName('fmActive');
			}
		} else {
			// hide all the other tabs
			if ($('fmTab'+i)) {
				$('fmTab'+i).hide();
				$(t).removeClassName('fmActive');
			}
		}	
	});	
}

function initHeader(userIn, parent) {
	if(userIn.id > 1){
		// logged in user
		var commentFormParams = {parentId : parent, username : userIn.user, userid : userIn.id};
		var renderedCommentForm = commentForm.evaluate(commentFormParams);
		// create tabs
		code += '<ul class="fmTabs fmClearfix"><li onClick="tabs(this);" class="fmActive">'+translate[2][3]+'</li><li class="fmLast" onClick="tabs(this);">'+translate[3][0]+'</li><li style="float:right; border:none; background:none; cursor:auto; padding-right:0px;">Welcome, ' + userIn.user + ' | <a href="javascript:logout()">logout</a></li></ul>';
		// create tab containers
		code += '<div id="fmTab0" class="fmTab fmClearfix">'+renderedCommentForm+'</div>';
		code += '<div id="fmTab1" class="fmTab fmClearfix" style="display:none;"><object id="" class="" style="width: 420px; height: 316px;" data="http://filemobile.com/static/widgets/mmc_uploader/mmc_app.swf" type="application/x-shockwave-flash" allowscriptaccess="always"><param value="http://filemobile.com/static/widgets/mmc_uploader/mmc_app.swf" name="movie"/><param value="true" name="allowFullScreen"/><param value="always" name="allowScriptAccess"/><param value="vhost='+vhost+'&parentid='+parent+'&recordingLength=20&sessiontoken='+fm.cookies.getCookie('SABRE_ID')+'" name="FlashVars"/></object></div>';
	} else {
		if (commentsOff) {
			code += '<div id="fmCommentsDisabled">'+translate[1][6]+'</div>';
		} else {
			//anonymous user
			var anonCommentFormParams = {parentId : parent};
			var renderedAnonCommentForm = anonCommentForm.evaluate(anonCommentFormParams);
			// create tabs
			code += '<ul class="fmTabs fmClearfix"><li onClick="tabs(this);" class="fmActive">'+translate[2][0]+'</li><li class="fmLast" onClick="tabs(this);">Login</li></ul>';
			// create tab containers
			code += '<div id="fmTab0" class="fmTab fmClearfix">'+renderedAnonCommentForm+'</div>'; 
			code += '<div id="fmTab1" class="fmTab fmClearfix" style="display:none;">'+loginForm+'</div>';
			//code += formInfo;
		}
	}
	// create sort options and show the number of total comments
	links = '<div id="fmCommentCount" class="fmLeft"></div>';
	links += '<select class="fmRight" onChange="if(this.value != \'\'){ window.sort = this.value; renderComments('+userIn.id+', this.value, true); }">';
	links += '<option value="upload DESC">'+translate[1][1]+'</option>';
	links += '<option value="upload ASC">'+translate[1][2]+'</option>';
	links += '<option value="votecount DESC, upload ASC">'+translate[1][3]+'</option>';
	links += '</select>';
	// create button to load more comments
	more = '<a class="fmButton" id="fmMoreCommentsBtn" style="display:none;" href="javascript:renderComments('+userIn.id+')">'+translate[1][4]+'</a>';
	// write all info into their containers
	$('fmCommentsBox').innerHTML = code;
	$('fmCommentsHeader').innerHTML = links;
	$('fmCommentsMore').innerHTML = more;
	// update the upload times every 15 seconds
	setInterval(updateDateTime,15000);
	// find out how many total comments there are
	getCommentCount(parent);
	// start the uploader
	Uploader.init($('flashSelectFile'));
}

function like(mid, uid) {
	// if the user isn't logged in display the error message asking them to log in
	if (uid == 1) {
		alert(translate[1][7]);
	} else {
		jsonPRequest('media.rateFile', {"id":mid,"rating":10,"returnData":true},
    		function(result) {
    			// change the number after the action has been successful
    			$('vote'+mid).innerHTML = result.votecount;
    		},
    		function(exception) { console.log(exception); }
  		);
	}
}

function confirmCredentials(username, password) {
 	jsonPRequest('users.confirmCredentials', {"username":username, "password":password, "returnUserInfo":true, "login":true},
    	function(result) { 
    		if(result.id > 1) {  window.location.reload(); }
			else { alert("Wrong login, please try again"); }
		},
		function(exception) { console.log(exception); },
		true
  	);
}

function dologin() {
	var username = $('fmLoginUsername').value;
	var password = $('fmLoginPassword').value;
	confirmCredentials(username, password);
}

function postanoncomment(parentId, author, email, comment, e) {
	// disable the text inputs and submit button
	$$('#'+e.id+' input').each(function(f) {
		f.disabled = true;
	});
	// disable the comment text area
	$$('#'+e.id+' textarea').each(function(f) {
		f.disabled = true;
	});
	// add the error overlay
	$(e).up(0).insert({top: '<div id="fmErrorOverlay"></div>'});
	// set the variables for the template
	var commentBody = {username: author, email: email, comment:comment, votecount:'0', upload:getDateTime(), uploadage:makeUploadAge(getDateTime())};
	// create the template
	var renderedComment = commentBlock.evaluate(commentBody);
	// send the comment to the DB
	jsonPRequest('media.insertTextFile', {"fileData":{'parentid':parentId,'context':'comment', 'author':author, 'sender':email, 'message':comment}},
    	function(result) {
			// insert the new comment
    		$('fmComments').insert({bottom: renderedComment});
    		$('fmErrorOverlay').addClassName('fmNoBackground');
    		// show the moderation message id needed
    		if (moderation == 'pre') {
    			var out = translate[2][5];
    		} else {
    			var out = translate[2][6];
    		}
    		// display the message
    		$('fmErrorOverlay').innerHTML = '<span class="fmSuccess">'+out+'</span>';
    	},
    	function(exception) {
    		console.log(exception);
    		// remove the loader image and show the error and ok button
    		$('fmErrorOverlay').addClassName('fmNoBackground');
    		$('fmErrorOverlay').innerHTML = '<span class="fmError">'+translate[1][8]+'</span><a onclick="this.up().remove();" class="fmButton">Ok</a>';
		    // re-enable the text inputs and submit button
			$$('#fmPostAnonComment input').each(function(f) {
				f.disabled = false;
			});
			// re-enable the comment text area
			$$('#fmPostAnonComment textarea').each(function(f) {
				f.disabled = false;
			});
    	},
    	true
  	);
}


function logout() {
	document.cookie = "SABRE_ID" + "=" + ";path=" + ";domain=" + "" + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	window.location = window.location;
}



function jsonPRequest(method,args,resultHandler,exceptionHandler,realJSON) {
    // Fix for IE bug where a 0 value passed as a number gets output from Prototype's Ajax.Request as undefined
    for ( var fieldName in args )
        if ( ( typeof ( args [ fieldName ] ) == 'number' ) && ( args [ fieldName ] == 0 ) )
            args [ fieldName ] = args [ fieldName ].toString ();

    args.method = method;
    
    if(realJSON) args = { 'jsonArgs': Object.toJSON ( args ) };


 	var ajax = new Ajax.Request(
        proxy,
        {
            method: 'post',
            parameters: args,
            onComplete: function(transport) {
                data = eval("(" + transport.responseText + ")");
                if (data["status"]) {
                    resultHandler(data["result"]);
                } else {
    				if (exceptionHandler) {
    					exceptionHandler(data);
    				} else {
    					alert('Uncaught exception: ' + data["result"]);
    				}
                }
            }
        });
}

Event.observe(window, 'load', function() {
	jsonPRequest('users.getLoggedInUser', {},
		function(result){ initApp(result); },
		function(result) { alert('Init failed, reload the page'); },
		false
	);
	
	if (!avatar) { $('fmComments').addClassName('fmNoAvatar');}
});



// Flash uploader

var Uploader = { 

	swf : null,
    fileMap : [],

	init : function(element) {

		var swf = new fm.flash.Object({
		  src : 'http://filemobile.com/static/widgets/swfupload.swf',
		  width : $('uploadBtn').getWidth(),
		  height : $('uploadBtn').getHeight(),
		  wmode : 'transparent',
		  id : 'uploaderSwf',
		  flashVars : { 
			 buttonText     : '',
			 callbackObject : 'Uploader',
			 debugEnabled   : 'true',
			 uploadURL      : 'http://filemobile.com/services/upload2',
			 buttonImageURL : '',
			 fileSizeLimit  : '250 MB',
			 fileQueueLimit : 1,
			 fileUploadLimit: 1,
			 httpSuccess    : '',
			 fileTypes		: "*.eps; *.jpg; *.jpeg; *.bmp; *.gif; *.pdf; *.png; *.3g2; *.3gp; *.ac3; *.aac; *.aiff; *.amr; *.asf; *.au; *.avi; *.dirac; *.dv; *.flav; *.flv; *.mkv; *.mov; *.mp4; *.m4a; *.mj2; *.mp2; *.mp3; *.mpeg; *.mpg; *.ogg; *.wav; ",
			 filePostName   : 'fmupload',
			 cancelButtonId : "fmCancelUpload",
			 movieName      : 'file',
			 useQueryString : 'false',
			 requeueOnError : 'false',
			 assumeSuccessTimeout : 0
		  }
		});

		swf.embed(element);
		this.swf = element.firstChild;

	},

	debug : function(str) {
		fm.util.log(str);
	},

	testExternalInterface : function() {
		return true;
	},

	flashReady : function() {
		fm.util.log('flash ready');
	},

	fileDialogStart : function() {  },
	fileDialogComplete : function() {  },
	fileQueueError : function(errorCode,file,message) { 
		alert(message); 
	},

	fileQueued : function(fileObj) { 
    	$('fileList').innerHTML+='<div id="uploadFile' + (this.fileMap.length) + '" class="queuedUploadItem"><img class="progressBar" src="http://filemobile.com/static/2/images/blank.gif" width="0px"  height="20px" /><div class="filename">' + fileObj.name + '</div><div class="percHolder">(<span class="percCount">0</span>%)</div></div>'; 
    	this.fileMap[this.fileMap.length] = fileObj;
	},

    fetchFileElem : function(fileObj) {
    	for(i=0;i<this.fileMap.length;i++) {
    		if (this.fileMap[i].name == fileObj.name) {
    			return $('uploadFile'+i); 
    		}
    	}
    },

	uploadStart : function() { 
		this.swf.ReturnUploadStart(true);
	},

    updateProgressBar : function (elem, percent){
    	if(percent < 1){
    		elem.getElementsByTagName('img')[0].setAttribute('width', 0);
    	} else {
    		elem.getElementsByTagName('img')[0].setAttribute('width' , (Math.round(percent)) + "%") ;
    	}	
    },

    uploadProgress : function(fileObj,bytesLoaded) {
		fm.util.log(fileObj);
		fm.util.log(bytesLoaded);
    	elem = this.fetchFileElem(fileObj);
    	var perc = bytesLoaded / fileObj.size * 100;
    	elem.getElementsByTagName('span')[0].innerHTML = Math.round(perc,2);
    	Uploader.updateProgressBar(elem, perc);
    	
    	progress = elem.getElementsByClassName('progressBar')[0];
    	progress.style.backgroundImage = 'url(http://filemobile.com/static/vidcom/images/progressbar/active.gif)';
    },

    uploadComplete : function(fileObj) {
    	elem = this.fetchFileElem(fileObj);
    	elem.getElementsByTagName('span')[0].innerHTML = '100';
    	Uploader.updateProgressBar(elem, 100);
    	progress = elem.getElementsByClassName('progressBar')[0];
    	progress.style.backgroundImage = 'url(http://filemobile.com/static/vidcom/images/progressbar/complete.gif)';
		if(this.swf.GetStats().files_queued > 0) {
			this.swf.StartUpload();			
		} else {
			// disable the comment text area
			$$('#uploadForm textarea').each(function(f) {
				f.disabled = true;
			});
			// insert the overlay
			$('uploadForm').up(0).insert({top: '<div id="fmErrorOverlay"></div>'});
			// create the new comment
			var commentBody = {username: $('username').value, userid: $('userid').value, comment:$('description').value, votecount:'0', upload:getDateTime(), uploadage:makeUploadAge(getDateTime())};
			//
			var renderedComment = '<div id="fmNewPost">'+commentBlockWithImage.evaluate(commentBody)+'</div>';
			// place the new comment below the other comments
			$('fmComments').insert({bottom: renderedComment});
			// remove the ajax image
			$('fmErrorOverlay').addClassName('fmNoBackground');
    		// show the moderation message id needed
    		if (moderation == 'pre') {
    			var out = translate[2][5];
    		} else {
    			var out = translate[2][6];
    		}
    		// display the message
    		$('fmErrorOverlay').innerHTML = '<span class="fmSuccess">'+out+'</span>';
			// make sure the user can see their new comment
			window.scrollTo('fmNewPost');

		}
    },

    startUpload : function() {
		
		// form validation	
		var validator = new FMFormValidate();
		validator.addValidationErrorListener( function(element,message) {
			handleValidation(element,message); return false;
		});
		
		// check to make sure the user is uploading a file or has a text comment
		if (this.fileMap.length < 1 && $('description').value == ''){
			$('selectFileBtn').innerHTML =  ' is required';
			$('uploadBtn').style.color = "#CC0000";
			return false;	
		} else {
			$('selectFileBtn').innerHTML =  '';
			$('uploadBtn').style.color = "#333333";
		}
		
		this.swf.SetPostParams({
			sessiontoken : fm.cookies.getCookie('SABRE_ID'), 
			vhost: vhost,
			message : $('description').value,
			parentid : $('parent').value,
			context : 'comment'
		});
		
		
		if(this.fileMap.length < 1){
			// if the form validation fails dont do anything						
			if (!validator.submit($('uploadForm'))){
				return false;
			// if the form validation passes create and send the comment
			} else if(validator.submit($('uploadForm'))) {
				// toss up the overlay
				$('uploadForm').up(0).insert({top: '<div id="fmErrorOverlay"></div>'});
				// disable the comment text area
				$$('#uploadForm textarea').each(function(f) {
					f.disabled = true;
				});
				// send the text commment
				jsonPRequest('media.insertTextFile', {"fileData":{'parentid':$('parent').value,'context':'comment', 'author':$('username').value, 'sender':$('userid').value, 'message':$('description').value, 'contenttype':'text/plain'}},
			    	function(result) {
			    		// create the new comment
			    		var commentBody = {username: $('username').value, userid: $('userid').value, comment:$('description').value, votecount:'0', upload:getDateTime(), uploadage:makeUploadAge(getDateTime())};
						var renderedComment = '<div id="fmNewPost">'+commentBlock.evaluate(commentBody)+'</div>';
						// insert the new comment
			    		$('fmComments').insert({bottom: renderedComment});
			    		$('fmErrorOverlay').addClassName('fmNoBackground');
			    		// show the moderation message id needed
			    		if (moderation == 'pre') {
			    			var out = translate[2][5];
			    		} else {
			    			var out = translate[2][6];
			    		}
			    		// display the message
			    		$('fmErrorOverlay').innerHTML = '<span class="fmSuccess">'+out+'</span>';
			    	},
			    	function(exception) {
			    		// remove the loader image and show the error and ok button
			    		$('fmErrorOverlay').addClassName('fmNoBackground');
			    		$('fmErrorOverlay').innerHTML = '<span class="fmError">'+translate[1][8]+'</span><a onclick="this.up().remove();" class="fmButton">Ok</a>';
						// re-enable the comment text area
						$$('#uploadForm textarea').each(function(f) {
							f.disabled = false;
						});
			    	},
			    	true
			  	);	
			  	return false;
			}
		}

						
		if(!validator.submit($('uploadForm'))) {
			return false;
		} else if (validator.submit($('uploadForm'))) {
			this.swf.StartUpload();
		}	
    }
}		
