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

function updateArticle() {
return;
}
// Figure out the relative upload time
function makeUploadAge(time_value) {
	if (!time_value) {
		return "error";
	}
	var values = time_value.split(" "); // split up the incoming date format
	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;
	}
	switch(v2[1]) {
		case "1": v2[1] = "Jan"; break;
		case "2": v2[1] = "Feb"; break;
		case "3": v2[1] = "Mar"; break;
		case "4": v2[1] = "Apr"; break;
		case "5": v2[1] = "May"; break;
		case "6": v2[1] = "Jun"; break;
		case "7": v2[1] = "Jul"; break;
		case "8": v2[1] = "Aug"; break;
		case "9": v2[1] = "Sep"; break;
	}
	
	time_value = v2[1]+" "+v2[2]+", "+v2[0]+" "+values[1]; // recreate the date
	var parsed_date = Date.parse(time_value); // turn it into a date object
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date(); // find out the time right now
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000); // get the difference between the two
	// 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)) {  r = translate[0][4]; }  // 2* because sometimes read 1 hours ago
	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;
	}
}

// Change the relative upload time
function updateDateTime() {
	$('#fmCommentsWrapper abbr').each(function() {	// grab all the <abbr> tags
		$(this).html(makeUploadAge($(this).attr('title'))); // update the value with the new time
	});
}


// Get the current date and time
function getDateTime() {	
	
	var t = new Date();
	var hours = t.getHours();
	var minutes = t.getMinutes();
	var seconds = t.getSeconds();
	var month = t.getMonth()+1;
	var date = t.getDate();
	var year = t.getFullYear();
	
	if (hours < 10){
		hours = "0" + hours;
	}
	
	if (minutes < 10){
		minutes = "0" + minutes;
	}
	
	if (seconds < 10){
		seconds = "0" + seconds;
	}
	
	if (month < 10){
		month = "0" + month;
	}
	
	if (date < 10){
		date = "0" + date;
	}
	
	var d = year+"-"+month+"-"+date+" "+hours+":"+minutes+":"+seconds; // format it in the correct way
	return d;
}


// jQuery template plugin - http://andrew.hedges.name/blog/2008/09/03/introducing-jquery-simple-templates

(function($) {
    $.extend({
    	// public interface: $.tmpl
    	tmpl : function(tmpl, vals) {
    		var rgxp, repr;
    		
			// default to doing no harm
			tmpl = tmpl   || '';
			vals = vals || {};
    		
    		// regular expression for matching our placeholders; e.g., #{my-cLaSs_name77}
    		rgxp = /#\{([^{}]*)}/g;
    		
    		// function to making replacements
    		repr = function (str, match) {
				return typeof vals[match] === 'string' || typeof vals[match] === 'number' ? vals[match] : str;
			};
			
			return tmpl.replace(rgxp, repr);
		}
	});
})(jQuery);


// jQuery Cookie plugin - http://plugins.jquery.com/project/cookie
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};



// Limit comment length
function limitCommentLength() {
	$('#fmCommentText').keydown(function(e) {
		str = $(this).val();
		if (str.length > commentLength && (e.keyCode != 8 || e.keyCode != 46)) {
			$(this).val(str.substr(0,commentLength));
		}
	});
	$('#fmCommentText').keyup(function(e) {
		str = $(this).val();
		if (str.length > commentLength && (e.keyCode != 8 || e.keyCode != 46)) {
			$(this).val(str.substr(0,commentLength));
		}
		var len = str.length;
		if (len > commentLength) {
			len = commentLength;
		}
		$('#fmCommentLength span').text(len+'/'+commentLength);

	});
};

var lengthBlock = "";
if (commentLength >= 1 && displayRemaining === true) {
	lengthBlock = '<span id="fmCommentLength">'+translate[2][8]+' <span>0/'+commentLength+'</span></span>';
}

function submitAnonComment(e,id) {

	if (!ValidatorForm.submit(e)) {
		return false;
	} else {
		postanoncomment(id, $('#fmCommentAuthor'), $('#fmCommentEmail'), $('#fmCommentText'), e);
	}
	return false;
}

// Containers

var loginForm = '<div id="loginformContainer" class="fmFormbox"><form action="http://filemobile.com/services/json" method="post" id="loginform" onsubmit="dologin(); return false;"><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(); return false;" class="fmButton"></li></ul></form></div>';

var commentForm = '<div id="uploadFormWrapper" class="fmFormbox"><form id="uploadForm" action=""><ul><li class="label"><label for="fmCommentText">Comment</label></li><li><textarea class="fmTextarea required" id="fmCommentText" name="message" title="Comment"></textarea></li></ul><input type="hidden" name="parent" id="fmParent" value="#{parentId}"><input type="hidden" name="username" id="fmUsername" value="#{username}" /><input type="hidden" name="userid" id="fmUserId" value="#{userid}" /><input type="hidden" name="avatarid" id="fmAvatarId" value="#{avatarid}" /></form><br/><div id="fmUploadStatus"><ul><li class="label">'+translate[3][4]+'</li></ul><a id="uploadBtn" class="fmButton" href="#" onclick="return false;"><div id="fmFlashSelectFile" style="display:block; position: absolute;"></div> '+translate[3][1]+' <span id="fmSelectFileBtn"></span></a><div id="fileList"></div><div class="fmClearfix"></div><div class="fmButtonWrapper fmClearfix"><a class="fmButton" onclick="this.blur(); Uploader.startUpload(); return false;">'+translate[2][4]+'</a></div></div><div id="postUpload"></div><div class="fmClear"></div><div id="loader" style="display:none">'+translate[3][3]+'</div></div>';

var anonCommentForm = '<div class="fmFormbox" id="anonCommentformContainer"><form method="POST" action="#" id="fmPostAnonComment" class="fmClearFix" onsubmit="return submitAnonComment(this,#{parentId});"><ul><li class="label"><label for="fmCommentAuthor">'+translate[2][1]+'</label></li> <li><input type="text" name="author" title="'+translate[2][1]+'"id="fmCommentAuthor" class="fmTextInput fmInput required" title="'+translate[2][1]+'"/></li><li class="label"><label for="fmCommentEmail">'+translate[2][2]+'</label></li> <li><input type="text" name="email" id="fmCommentEmail" class="fmTextInput fmEmail fmInput required" title="'+translate[2][2]+'"/></li><li class="label"><label for="fmCommentText">'+translate[2][3]+' '+lengthBlock+'</label></li> <li><textarea name="message" id="fmCommentText" class="fmTextArea fmTextarea required" title="'+translate[2][3]+'"></textarea></li><li class="label"><br/><input type="button" value="'+translate[2][4]+'" class="fmButton" onClick="return submitAnonComment($(\'#fmPostAnonComment\'),#{parentId});"/></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>';
	
	
// set profile code, links if profiles are enabled, spans if profiles are disabled	
var profileBlockAvatar = '';
var profileBlockLink = '';

// set the liking button and number block and CSS class name
var likingBlock = '';
var likingClass = '';

// set the reporting button and CSS class name
var reportBlock = '';
var reportClass = '';

if (profiles !== false) {
	profileBlockAvatar = '<a href="'+profiles+'#{profileid}" class="fmAvatar"> <img src="#{avatar}" /> </a>';
	profileBlockLink = '<a href="'+profiles+'#{profileid}" class="fmName">#{username}</a>';
} else {
	profileBlockAvatar = '<span class="fmAvatar"> <img src="#{avatar}" /> </span>';
	profileBlockLink = '<span class="fmName">#{username}</span>';
}

if (liking) {
	likingBlock = '<div class="fmRating"> <div class="fmValue" id="vote#{mid}">#{votecount}</div><span class="fmLike" onclick="fmLike(#{mid}, #{uinid})">'+translate[1][9]+'</span></div>';
}

if (report) {
	reportClass = ' fmReportComment';
	reportBlock = '<span class="fmReport" onclick="fmReport(#{mid}, #{uinid}, this)">'+translate[1][10]+'</span>';
}

var commentClass = reportClass;

// comment blocks
var commentBlock = '<div class="fmComment'+commentClass+' fmClearfix"><div class="fmUser fmClearfix"> '+profileBlockAvatar+' <div class="fmInfo fmClearfix"> '+profileBlockLink+' <abbr title="#{upload}" class="fmTimestamp">#{uploadage}</abbr> </div> </div><div class="fmContent">#{comment}</div>'+likingBlock+reportBlock+'</div>';
	
	
var commentBlockWithImage = '<div class="fmComment'+commentClass+' fmClearfix"><div class="fmUser fmClearfix">  '+profileBlockAvatar+' <div class="fmInfo fmClearfix"> '+profileBlockLink+' <abbr title="#{upload}" class="fmTimestamp">#{uploadage}</abbr> </div> </div><div class="fmContent"><img src="#{image}/14" />#{comment}</div>'+likingBlock+reportBlock+'</div>';


var commentBlockWithVideo = '<div class="fmComment'+commentClass+' fmClearfix"><div class="fmUser fmClearfix">  '+profileBlockAvatar+' <div class="fmInfo fmClearfix"> '+profileBlockLink+' <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}';

if (wid > 0) { commentBlockWithVideo += '&amp;wid='+wid; }

commentBlockWithVideo += '&amp;sessionToken='+$.cookie('SABRE_ID')+'" name="FlashVars"/> </object><br/>#{comment}</div>'+likingBlock+reportBlock+'</div>';


// Global vars
var externalid;
if(externalid == null) { externalid = location.href.substr(7,location.href.length); }

var external_title;
if(external_title == null) { external_title = location.href.substr(7,location.href.length); }

var external_url = location.href;

var channel;
if(!channel) { channel = 0; }

var env;
if(!env) { env = 'live'; }

var parentId = 0;

var code = '';

var moderationStatus = 1;
if (moderation == 'post') { moderationStatus = 3; }

var start = 0;

if (pagesize > 500) { pagesize = 500; }

var injector = 'FM-MMC-v1';

var loadingIcon;
if (loadingIcon == null) { loadingIcon = 'http://www.filemobile.com/static/mmc/images/loading.gif'; }

var commentLength;
if (commentLength == null) { commentLength = false; }

var displayRemaining;
if (displayRemaining == null) { displayRemaining = false; }

var maxLengthDisplay;
if (maxLengthDisplay == null) { maxLengthDisplay = false; }

var reportFade;
if (reportFade == null) { reportFade = true; }

var rating;
if (rating == null) { rating = false; }

var ratingEmptyStar;
if (ratingEmptyStar == null) { ratingEmptyStar = "http://www.filemobile.com/static/mmc/images/empty.png"; }

var ratingFullStar;
if (ratingFullStar == null) { ratingFullStar = "http://www.filemobile.com/static/mmc/images/full.png"; }

function fmUpdateUrl(id) {
	jsonPRequest('media.updateFile',{'id':id,'newProperties':{"message":location.href}},function(result){},function(exception){},true );
}

function initApp(userIn) {
	// Get parent media and get its comments
	jsonPRequest('media.getFiles', {"filters":{ 'externalid' : externalid, "moderationStatus":'notdenied' }, "noCache":true },
    	function(result) {
    		if(result.totalCount > 0) {
    			parentId = result.data[0].id;
    			if (result.data[0].message.substr(0,7) != 'http://' && parentId > 0) {
    				fmUpdateUrl(parentId);
    			}
    			if (!avatar) { $('#fmComments').addClass('fmNoAvatar'); } // if avatars are turned off, hide them by adding the 'fmNoAvatar'
    			renderComments(userIn.id, start);
			  	initHeader(userIn, parentId, start);
			  	fmLogHit(parentId);
			  	if (rating) {
			  		var Rate = new rateArticle();
					Rate.getRating(result.data[0]);
				}
    		} else {
    			// if there isn't a parent media for this URL, tell the user there is no comments then create the parent media
    			$('#fmComments').html('<div id="fmNoComments">'+translate[1][5]+'</div>');
    			var params = {"fileData" : {'title':external_title, 'message':external_url, 'externalid':externalid, 'metadata':{'external_title':external_title, 'external_url':external_url}  } }
				//console.log(params);
				jsonPRequest('media.insertTextFile', params,
					function(result4) {
						initHeader(userIn, result4, start);
						fmLogHit(result4);
						$('#fmCommentCount').html("0 "+translate[1][0]);
						if (rating) {
							var Rate = new rateArticle();
							Rate.getRating(result4);
						}
					},
					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 = sort } else { sort = sortOpt };
	if(sortted == true) start = 0;
	// swap the text on the 'more comments' button with a loading image
	if ($('#fmMoreCommentsBtn')) {
		$('#fmMoreCommentsBtn').html('<img src="'+loadingIcon+'" alt="'+translate[3][3]+'" />');
	}
	//
	jsonPRequest('media.getFiles', {"sort":sort, 'limit':pagesize, 'start':start, 
	"filters":{"parentid":parentId, "context":"comment", "moderationStatus":moderationStatus }, 
	"fields":{"0":"filetype", "1":"uid", "2":"user_name", "3":"votecount", "4":"author", "5":"upload", "6":"message", "7":"publicUrl", "8":"status", "9":"avatar"},
	"noCache":true},
		function(result2) {
			// find out how many total comments there are
			//if (moderation == "post") { x = result.totalCount; } 
			var commentCount = result2.totalCount;
			$('#fmCommentCount').html(commentCount+" "+translate[1][0]); // display the comment count
			// 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').html("");
				}
				for (i=0;i<data.length;i++) {
					currentComment = data[i];
					//need to get the file data to get the author
					if(currentComment.uid == 1) {
						avatar = defaultAvatar;
						var comment = {'username':stripHTML(currentComment.author), 'comment':currentComment.message, 'votecount':currentComment.votecount, 'upload':currentComment.upload, 'uploadage':makeUploadAge(currentComment.upload), 'mid':currentComment.id, 'uinid':uid, 'profileid':currentComment.uid, 'avatar':avatar};
						var renderedComment = $.tmpl(commentBlock, comment); 
					}
					else {
						var avatar = '';
						if(currentComment.avatar != 0) {
							if (env == 'dev') avatar = 'http://fmdev.s3.amazonaws.com/storage/' + currentComment.avatar + '/12';
							else avatar = 'http://rstorage.filemobile.com/storage/' + currentComment.avatar + '/12';
						}
						else avatar = defaultAvatar;
														
						// 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, 'avatar':avatar};
							var renderedComment = $.tmpl(commentBlock, 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, 'avatar':avatar};
							var renderedComment = $.tmpl(commentBlockWithImage, 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, 'avatar':avatar};
							var renderedComment = $.tmpl(commentBlockWithVideo, comment); 
						}
					}
					// insert the comment into the list
					$('#fmComments').append(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').html(translate[1][4]);
				}
			} else {
				// display the message that there are no comments yet
				$('#fmComments').html('<div id="fmNoComments">'+translate[1][5]+'</div>');
			}
		},
		function(exception2) {	
			// something went wrong, tell us
			//console.log(exception2);
		},
		true
	);
}

// 
function tabs(e) {
	// get all <li> elements
	$($(e).parent()[0]).children().each(function(i) {
		if (e==this) {
			// show the tab the user just clicked on
			if ($('#fmTab'+i)) {
				$('#fmTab'+i).show();
				$(e).addClass('fmActive');
			}
		} else {
			// hide all the other tabs
			if ($('#fmTab'+i)) {
				$('#fmTab'+i).hide();
				$(this).removeClass('fmActive');
			}
		}	
	});	
}

function updateCount() {
	if ($("#fmNoComments")) {
		$("#fmNoComments").remove();	
	}
	// update the count 
	var x = $('#fmCommentCount').html();
	var matches;
	if (x) {
		matches = x.match(/^(\d+)/);
	} else {
		matches = ['0'];
	}
	$('#fmCommentCount').html((parseInt(matches[0])+1)+" "+translate[1][0]);
}

function initHeader(userIn, parent) {
	if(userIn.id > 1){
		// logged in user
		var commentFormParams = {parentId : parent, username : userIn.user, userid : userIn.id, avatarid:userIn.avatar};
		var renderedCommentForm = $.tmpl(commentForm, 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+'&channel='+channel+'&injector='+injector+'&recordingLength=20&sessiontoken='+$.cookie('SABRE_ID')+'" name="FlashVars"/></object></div>';
	} else {
		if (disableComments) {
			code += '<div id="fmCommentsDisabled">'+translate[1][6]+'</div>';
		} else {
			//anonymous user
			var anonCommentFormParams = {parentId : parent};
			renderedAnonCommentForm = $.tmpl(anonCommentForm, anonCommentFormParams);
			// create tabs
			if (login) {
				
				if (anonymous == false && login == false) { } else { code += '<ul class="fmTabs fmClearfix">'; }
				
				if (anonymous != false) {
					code +='<li onClick="tabs(this);" class="fmActive">'+translate[2][0]+'</li>';
					last = "fmLast";
					tab = "fmTab1";
					style = ' style="display:none;"'
				} else {
					last = "fmActive";
					tab = "fmTab0"
					style = '';
				}
				
				if (login == true) {
					code +='<li class="'+last+'" onClick="tabs(this);">Login</li>';
				} else if (login != false) {
					code +='<li class="'+last+'">'+login+'</li>';
				}
				
				if (anonymous == false && login == false) { } else { code += '</ul>'; }
				
			} else {
				
				var showHeader = true;
				
			}
			
			// create tab containers
			
			if (anonymous != false) {
			
				code += '<div id="fmTab0" class="fmTab fmClearfix">';
				
				if (showHeader) {
					code += '<h6>'+translate[2][0]+'</h6>';	
				}
				
				if (anonymous != true && anonymous != false) {
					code += anonymous;
				} else {
					code += renderedAnonCommentForm;
				}
				
				code += '</div>';
				
			}
			
			if (login == true) {
			
				code += '<div id="'+tab+'" class="fmTab fmClearfix"'+style+'>'+loginForm+'</div>';
				
			}
		}
	}
	
	// create sort options and show the number of total comments
	links = '<div id="fmCommentCount" class="fmLeft"></div>';
	links += '<select class="fmRight" onChange="if($(this).val() != \'\'){ sort = $(this).val(); renderComments('+userIn.id+', $(this).val(), true); }">';
	
	// place the default sort option at the top of the list (works better then selected="selected")
	if (sort == "upload DESC") {
		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>';	
	} else if (sort == "upload ASC"){
		links += '<option value="upload ASC">'+translate[1][2]+'</option>';
		links += '<option value="upload DESC">'+translate[1][1]+'</option>';
		links += '<option value="votecount DESC, upload ASC">'+translate[1][3]+'</option>';			
	} else {
		links += '<option value="votecount DESC, upload ASC">'+translate[1][3]+'</option>';	
		links += '<option value="upload DESC">'+translate[1][2]+'</option>';
		links += '<option value="upload ASC">'+translate[1][1]+'</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').html(code);
	$('#fmCommentsHeader').html(links);
	$('#fmCommentsMore').html(more);
	
	// update the upload times every 15 seconds
	setInterval(updateDateTime,15000);
	
	// start the uploader
	//Uploader.init($('#fmFlashSelectFile'));
	
	// turn on the comment length limiter
	if (commentLength !== false && commentLength > 0) {
		limitCommentLength();
	}
}

function fmLike(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 {	
		if (!$('#vote'+mid).next().hasClass("fmDisabled")) {	
			$('#vote'+mid).next().addClass("fmDisabled");
			$('#vote'+mid).html(parseInt($('#vote'+mid).html())+1);
			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 fmLogHit(id) {
	var params = {"fileId":id,"fileType":4,"fileSize":0};	
	jsonPRequest('media.logHit', params,
		function(results) {},
		function(exception) {}
	);	
}

function fmSendReport(mid,reason) {
	if (reason === '' || !reason) {
		$('#fmReportReason').addClass('errorField');
		$('#fmReportReason').change(function() {
			$(this).removeClass('errorField');
		});
	} else {	
		// find the report button
		var btn = $($('#fmReportBox .fmButton')[0]);	
		// stop the ninja clicking
		if (btn.attr("disabled") != "disabled") {
			btn.attr("disabled","disabled");
			// add the loading image to the 'report' button
			btn.css({'width':btn.width()-1+"px"});
			btn.html('<img src="'+loadingIcon+'" class="fmLoading"/>');
			// send the request
			args = 'reason='+reason+'&mid='+mid;
			var ajax = $.ajax({
				type: 'POST',
				url: report,
		        data: args,
		        dataType: 'html',
				success: function(data) {
					// hide the buttons and the select element
					$('#fmReportBox').find('select').remove();
					$('#fmReportBox').find('.fmButton').remove();
					data = jQuery.parseJSON(jQuery.trim(data));
				    if (data.result) {
				    	// remove the 'report' link from the comment 
				   		$('#fmReportBox').prev('.fmReport').remove();
				    	$('#fmReportBox').find('p').text(translate[6][4]);
				    	$('#fmReportBox').remove();
				    } else {
				    	btn.removeAttr("disabled");
				    	$('#fmReportBox').find('p').text(translate[6][5]);
				    }
				}
			});
		}
	}
}

function fmReport(mid, uid, e) {
	if (uid == 11) {
		alert(translate[1][7]);
	} else {
		if ($('#fmReportBox')) { $('#fmReportBox').remove() }
		var selectBox = '<option value="">---</option>';
		for (i=0;i<translate[4].length;i++) {
			selectBox += '<option value="'+translate[4][i]+'">'+translate[5][i]+'</option>';
		}
		$(e).after('<div id="fmReportBox" class="fmClearfix"><div class="fmTitle">'+translate[6][0]+'</div><span class="fmReport" onclick="$(\'#fmReportBox\').remove();">close</span> <p>'+translate[6][1]+'</p><select name="reason" id="fmReportReason" style="width:100%;">'+selectBox+'</select><span class="fmButton" onclick="fmSendReport('+mid+',$(\'#fmReportReason\').val());">'+translate[6][2]+'</span><span class="fmButton" onclick="$(\'#fmReportBox\').remove();">'+translate[6][3]+'</span></div>');
	}
}

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').val();
	var password = $('#fmLoginPassword').val();
	confirmCredentials(username, password);
}

function stripHTML(html){
	html = html.replace(/\r\n/g, "#{fmLineBreak}").replace(/\n/g, "#{fmLineBreak}").replace(/\r/g, "#{fmLineBreak}");
	html = $('<div>' + html + '</div>').text();
	html = html.replace(/#{fmLineBreak}/g, "<br/>");
	return html;
}

function postanoncomment(parentId, author, email, comment, e) {
	author = stripHTML(author.val());
	email = stripHTML(email.val());
	comment = stripHTML(comment.val());
	//
	var x = $(e).attr("id");
	// disable the text inputs and submit button
	$(x+' input').each(function(f) {
		f.disabled = true;
	});
	// disable the comment text area
	$(x+' textarea').each(function(f) {
		f.disabled = true;
	});
	// add the error overlay
	$($(e).parents()[0]).prepend('<div id="fmErrorOverlay"></div>');
	// set the variables for the template
	var commentBody = {'username': author, 'avatar': defaultAvatar, 'comment':comment, 'votecount':'0', 'upload':getDateTime(), 'uploadage':translate[0][0], 'mid':'0', 'uinid':'0', 'profileid':'0'};	
	// create the template
	var renderedComment = '<div id="fmNewPost">'+$.tmpl(commentBlock, commentBody)+'</div>';
	// send the comment to the DB
	jsonPRequest('media.insertTextFile', {"fileData":{'parentid':parentId,'context':'comment', 'author':author, 'sender':email, 'message':comment, 'channel':channel, 'injector':injector}},
    	function(result) {
    		updateCount();
			// insert the new comment
			if (sort == "upload DESC") {
				$('#fmComments').prepend(renderedComment);
			} else {
    			$('#fmComments').append(renderedComment);
    		}
    		$('#fmErrorOverlay').addClass('fmNoBackground');
    		// show the moderation message id needed
    		if (moderation == 'pre') {
    			var out = translate[2][5];
    		} else {
    			var out = translate[2][6];
    		}
    		//
    		$("#fmNewPost .fmReport").remove();
    		// display the message
    		$('#fmErrorOverlay').html('<span class="fmSuccess">'+out+'</span>');
    		//
    		$('#fmPostAnonComment').removeAttr('onsubmit');
    		//
			$('#fmNewPost').animate({scrollTop:0}, 'slow');
    	},
    	function(exception) {
/*     		console.log(exception); */
    		// remove the loader image and show the error and ok button
    		$('#fmErrorOverlay').addClass('fmNoBackground');
    		$('#fmErrorOverlay').html('<span class="fmError">'+translate[1][8]+'</span><a onclick="this.parents()[0].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() {
	jQuery.cookie("SABRE_ID",null);
	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;
    
	$.getJSON(
		proxy+"?"+$.param(args)+"&jsoncallback=?",
		function(data){
			if (data.status === true) {
				resultHandler(data.result);
			} else {
				if (data.result.reason.length > 0) {
					if ($('#fmLoading').length > 0) {
/* console.log */(data.result.reason);
						$('#fmComments').html(translate[8][0]);
						$('.Ratings_Container').html(translate[8][1]);
					} else {
						//alert(translate[8][2]);
					}
				} else {
					if (exceptionHandler) {
						exceptionHandler(data);
					} else {
						//alert('Uncaught exception: ' + data["result"]);
					}
				}
			}
		}
	);

}

function rateArticle() {
	
	this.getRating = function(data) {
		$('#fmRatingPeople').html(data.votecount);
		if(data.votecount == 1) $('#fmRatingPeopleText').text("person");
		else $('#fmRatingPeopleText').text("people");
		
		this.rating = data.rating;
		this.mid = data.id;
		this.out = '';
		
		if (this.mid == undefined) {
			this.mid = data;
		}
		
		if (this.rating == undefined) {
			for(i=0;i<5;i++) { this.out += '<img src="'+ratingEmptyStar+'" alt="Empty Star">'; }
		} else {
			for(i=0;i<this.rating;i++) { this.out += '<img src="'+ratingFullStar+'" alt="Star">';}
			for(i=4;i>=this.rating;i--) { this.out += '<img src="'+ratingEmptyStar+'" alt="Empty Star">'; }		
		}
		
		$('#fmRatingStars').html(this.out);
		
		this.out = "";
		for(i=0;i<5;i++) { this.out += '<img border="0" id="fmRate_'+i+'" src="'+ratingEmptyStar+'" alt="">'; }
		
		if($.cookie('rated'+externalid) != null) {
			this.rating = $.cookie('rated'+externalid);
			this.out = "";
			for(i=0;i<this.rating;i++) { this.out += '<img src="'+ratingFullStar+'" alt="Star">'; }
			for(i=4;i>=this.rating;i--) { this.out += '<img src="'+ratingEmptyStar+'" alt="Empty Star">';}		
			$('#fmUserRating').html(this.out);
			$('#fmUserRating').addClass("disabled");
			$('#fmRatingWord').text(translate[7][parseInt(this.rating)]);		
		}
		else {
			$('#fmUserRating').html(this.out);
			var mid = this.mid;
			$('#fmUserRating').children().each(function() {
				$(this).mouseenter(function(){
					$(this).attr('src',ratingFullStar);
					$(this).prevAll().each(function(e) {
						$(this).attr('src',ratingFullStar);
					});
					$('#fmRatingWord').text(translate[7][$(this).index()+1]);
				});
				$(this).mouseleave(function(){
					$(this).attr('src',ratingEmptyStar);
					$(this).prevAll().each(function(e) {
						$(this).attr('src',ratingEmptyStar);
					});
					$('#fmRatingWord').text(translate[7][0]);
				});
				$(this).click(function() {
					$($(this).parent()[0]).addClass("disabled");
					$($(this).parent()[0]).children().unbind();
					myRating = $(this).index()+1;
					
					var newRating = parseInt($('#fmRatingPeople').html())+1;
					if(newRating == 1) $('#fmRatingPeopleText').text("person");
					else $('#fmRatingPeopleText').text("people");
					$('#fmRatingPeople').html(newRating);
					
					jsonPRequest('media.rate', {"mid":mid,"rating":myRating,"uid":1,"returnData":true},
						function(result2) { $.cookie('rated'+externalid, myRating, {path:"/", expires:1});},
						function(exception) { 
/* 							console.log(exception);  */
						}
					);
				});
			});	
		}	
	}
}

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

