/*

Multimedia Comments powered by Filemobile
Version 2.3
Built by Adam Shutsa, Evert Pot and Oleg Gustol
Last update: February 14th 2010

documentation - docs.comments.projects.fm/
demo - comments.filemobile.com/
product - filemobile.com/products/multimediacomments	

*/

if (typeof fm == 'undefined') {
	fm = function() { }
} 

// Build the comments object
fm.comments = {} 

// Default settings
fm.comments.defaults = { 
	externalId : location.href.substr(7,location.href.length), 
	externalTitle : location.href.substr(7,location.href.length), 
	externalUrl : location.href,
	injector : 'FM-MMC-v2.3',
	proxy : '',
	vhost : '',
	env : 'live',
	wid : '',
	disableComments : false,
	enableUpload : true, 
	style : 2,
	pageSize : 10,
	profiles : false, 
	avatar : true, 
	defaultAvatar : 'http://www.filemobile.com/static/mmc2/images/avatar.gif',
	loadingIcon : 'http://www.filemobile.com/static/mmc2/images/loading.gif',
	exactDate : false,
	longDate : true,
	liking : true, 
	likingInline : true,
	likingShowValue : true,
	sort : 'upload DESC',
	sortSelect : true,
	report : false, 
	reportFade : true, 
	maxLengthNumber : false, 
	maxLengthDisplay : true, 
	maxLengthCountdown : false, 
	pager : false, 
	pagerAjax : true, 
	pagerLimit : 2, 
	pagerShowPrevNext : true, 
	pagerShowFirstLast : true, 
	pagerShowNumbers : true, 
	pagerCenter : true, 
	webcam : false,
	scroll : true,
	scrollDuration : 0, 
	rating : true,
	logHit : true,
	showUsername : true,
	showFirstName : false,
	showLastName : false,
	imageTranscoder : '14',
	imageHeight : '240',
	videoTranscoder : '21',
	videoPlayerWidth : '320',
	videoPlayerHeight : '240',
	autoUpdate : false,
	autoUpdateTime : 60,
	layout : ['header','comments','more','add'],
	translate : {
		justNow : 'just now',
		momentsAgo : 'moments ago',
		minuteAgo : 'a minute ago',
		minutesAgo : 'minutes ago',
		hourAgo : 'about an hour ago',
		hoursAgo : 'hours ago',
		dayAgo : 'day ago',
		daysAgo : 'days ago',
		yesterday : 'yesterday',
		sunday : "Sun",
		monday : "Mon",
		tuesday : "Tue",
		wednesday : "Wed",
		thursday : "Thu",
		friday : "Fri",
		saturday : "Sat",
		january : "Jan",
		february : "Feb",
		march : "Mar",
		april : "Apr",
		may : "May",
		june : "Jun",
		july : "Jul",
		august : "Aug",
		september : "Sept",
		october : "Oct",
		november : "Nov",
		december : "Dec",
		comments : 'Comments',
		newToOld : 'Newest to oldest',
		oldToNew : 'Oldest to newest',
		mostLikes : 'Most thumbs up',
		moreComments : 'More comments',
		newComments : ' new comments',
		noComments : 'No comments. Be the first!',
		commentsDisabled : 'Comments have been disabled.',
		loginRequired : 'You must login to like a comment.',
		error : 'An error has occurred. Please try again.',
		close : 'Close',
		like : 'Like',
		report : 'Report',
		guestComment : 'Guest Comment',
		name : 'Name',
		comment : 'Comment',
		postComment : 'Post Comment',
		moderationMessagePost : 'Thank you for your comment.',
		moderationMessagePre : 'Thank you for your comment. It will first have to be checked by our moderators before showing up on the site.',
		moderationMediaMessage : '<br/>Your media is being transcoded and will appear on the site shortly.',
		characterCount : 'character count',
		createAccount : 'Create Account',
		login : 'Login',
		register : 'Register',
		incorrectLogin : 'Your username and/or password was incorrect. Please try again.',
		username : 'Username',
		firstName : 'First name',
		lastName : 'Last name',
		email : 'Email',
		password : 'Password',
		confirmPassword : 'Confirm password',
		webcam : 'Webcam',
		browse : 'Browse',
		cancel : 'Cancel',
		wait : 'Please wait...',
		attach : 'Attach an image or video <span>(optional)</span>',
		removeFromQueue : 'cancel',
		reason1 : 'Offensive',
		reason2 : 'Spam',
		reason3 : 'Off topic',
		frontReason1 : 'Offensive (rude, obscene, NSFW)',
		frontReason2 : 'Spam (ads, self-promotion)',
		frontReason3 : 'Off topic (trolling)',
		reportComment : 'Report this comment',
		reportDescription : 'Please tell us why you feel this comment should be flagged.',
		report : 'Report',
		reportSent : 'The comment has been reported. Our moderators will now review its content.',
		reportError : 'An error has occurred on one of our servers causing you to see this message. Please try again.',
		ratingRateArticle : 'Rate this article:',
		ratingAverageRating : 'Average rating:',
		ratingBy : ' by ',
		ratingPeople : 'people',
		ratingUnrated : ' Not rated',
		rating1 : ' Horrible!',
		rating2 : ' Not for me.',
		rating3 : ' It\'s alright',
		rating4 : ' I like it.',
		rating5 : ' I love it!',
		pagerNext : 'Next',
		pagerPrev : 'Prev',
		pagerFirst : 'First',
		pagerLast : 'Last',
		welcome : 'Welcome, ', 
		logout : 'Logout',
		loading : 'Loading Comments',
		validateRequired : ' is a required field',
		validateDate : ' does not have a valid date',
		validatePhone : ' does not contain a valid phone number',
		validatePasswordLength : 'Your password needs to be at least 6 characters long',
		validatePasswordMatch : 'The passwords did not match',
		validateEmail : ' does not contain a valid email address',
		validateEmailMatch : 'The email fields do not match',
		validatePostalCode : ' does not contain a valid Canadian postal code',
		validateUsernameLength : 'A username has to be a minimum of 6 characters, can only contain A-Z 0-9 and _ (underscore) and has to start with a letter',
		validateEmailUnique : 'The email address supplied is already registered. Did you forget your login information?',
		validateUsernameUnique : 'The username you picked was already taken. Please try another name.'
	}
}

// This property will contain html with information about the user's comment length
fm.comments.lengthBlock = '';

// This property will contain the commentForm template
fm.comments.commentForm = '';

// This property contains the comment form for anonymous users
fm.comments.anonymousCommentForm = '';

// This property contains the register form
fm.comments.registerForm = '';

// This property contains the HTML code for the login form
fm.comments.loginForm = '';

// Profile HTML code
fm.comments.profileBlockAvatar = '';
fm.comments.profileBlockLink = '';

// Set the liking button and number block and CSS class name
fm.comments.likingBlock = '';
fm.comments.likingClass = '';

// Set the reporting button and CSS class name
fm.comments.reportBlock = '';
fm.comments.reportClass = '';

// Per-comment css class
fm.comments.commentClass = '';

// Comment-html block
fm.comments.commentBlock = '';
fm.comments.commentBlockWithImage = '';
fm.comments.commentBlockWithVideo = '';

// This is the current comment offset. If we have to load more comments it will be increased
fm.comments.startOffset = 0;

// This will hold the currently logged in users' information
fm.comments.currentUser = null;

// This will be true if the user is logged in
fm.comments.isLoggedIn = false;

// Parent id of the comments
fm.comments.parentId = 0;

// The number of times the auto update request as been made with no new media + 1
fm.comments.autoUpdateCount = 1;

// Queued comments waiting to be displayed
fm.comments.queue = '';

// Get the page title
fm.comments.title = jQuery('title').text();

// The default layout function thats called first thing in the initialization fuction.=
fm.comments.writeDom = function() {
	var divs = [];
	divs['header'] = '<div id="fmCommentsHeader" class="fmClearfix"></div>';
	divs['comments'] = '<div id="fmComments" class="fmStyle'+fm.comments.settings.style+'"> <div id="fmLoading">Loading Comments</div> </div>';
	divs['more'] = '<div id="fmCommentsMore" class="fmClearfix"></div>';
	divs['add'] = '<div id="fmCommentsBox" class="fmClearfix"></div>';
	
	var html = '';
	
	for(i=0;i<fm.comments.settings.layout.length;i++) {
		html += divs[fm.comments.settings.layout[i]];
	}
	
	html += '<div class="fmPowered">' +
		    '	<a href="http://www.filemobile.com/products/multimediacomments" target="_blank">Multimedia Comments</a> are powered by <a href="http://www.filemobile.com" target="_blank">Filemobile</a>' +
		    '</div>';
			    
	return html;
}

// Setting up all the messages for the errors that prevent the app from displaying comments
fm.comments.displayError = function(nr) {
	var error = 'Comment Error: ';
	switch(nr){
		case 1: error += 'There was not element specified in the initialization settings.'; break;
		case 2: error += 'The element specified in the initialization settings is not allowed.'; break;
		case 3: error += 'The element specified in the initialization settings does not exist.'; break;
	}
	alert(error);
}

fm.comments.init = function(settings) { 

	fm.comments.settings = {};
	fm.comments.settings = jQuery.extend(fm.comments.settings, fm.comments.defaults, settings);

	fm.comments.settings.translate = {}
	fm.comments.settings.translate = jQuery.extend(fm.comments.settings.translate, fm.comments.defaults.translate, settings.translate);
    
    if (!fm.comments.settings.element || fm.comments.settings.element === 'undefined') {
    	fm.comments.displayError(1);
    	return false;
    } else if (fm.comments.settings.element.substr(0,2) === 'fm') {
    	fm.comments.displayError(2);
    	return false;
    } else if (jQuery('#'+fm.comments.settings.element).length < 1) {
    	fm.comments.displayError(3);
    	return false;
    }
    
    jQuery('#'+fm.comments.settings.element).addClass('fmCommentsWrapper fmClearFix').html(fm.comments.writeDom());
    
    // Build the rest of the rating elements
    if (fm.comments.settings.rating === true) {
    	jQuery('#fmRatingUser').html('<span class="fmRatingHeader">'+fm.comments.settings.translate.ratingRateArticle+' </span><span id="fmRatingUserStars" class="fmClearfix"></span><span id="fmRatingWord"> '+fm.comments.settings.translate.ratingUnrated+'</span>');
    	jQuery('#fmRatingAverage').html('<span class="fmRatingHeader">'+fm.comments.settings.translate.ratingAverageRating+' </span><span id="fmRatingStars" class="fmClearfix"></span><span>'+fm.comments.settings.translate.ratingBy+'</span><span id="fmRatingPeople">0</span> <span id="fmRatingPeopleText">'+fm.comments.settings.translate.ratingPeople+'</span>');
    }

	// Determining if we need to show the maximum comment length
	if (fm.comments.settings.maxLengthNumber >= 1 && fm.comments.settings.maxLengthDisplay === true) {
		if (fm.comments.settings.maxLengthCountdown == true) {
			var fmDisplayMaxLength = fm.comments.settings.maxLengthNumber;
		} else {
			var fmDisplayMaxLength = '0/'+fm.comments.settings.maxLengthNumber;
		}
		fm.comments.lengthBlock = '<span id="fmCommentLength">'+fm.comments.settings.translate.characterCount+' <span>'+fmDisplayMaxLength+'</span></span>';
	}
	
	if (fm.comments.settings.enableUpload === false) {
		fm.comments.showUpload = ' class="disable"';
	} else {
		fm.comments.showUpload = '';
	}
	
	fm.comments.commentForm = 
		'<div id="fmUploadFormContainer" class="fmFormbox fmClearfix">\n' +
		'  <form id="uploadForm" action="">\n' +
		'    <ul>\n' +
		'      <li class="label"><label for="fmCommentText">'+fm.comments.settings.translate.comment+' '+fm.comments.lengthBlock+'</label></li>' +
		'      <li><textarea class="fmTextarea required" id="fmCommentText" name="message" title="'+fm.comments.settings.translate.comment+'"></textarea></li>' +
		'    </ul>' +
		'    <input type="hidden" name="parent" id="fmParent" value="#{parent}">' +
		'    <input type="hidden" name="username" id="fmUsername" value="#{username}" />' +
		'    <input type="hidden" name="firstname" id="fmFirstName" value="#{firstname}" />' +
		'    <input type="hidden" name="lastname" id="fmLastName" value="#{lastname}" />' +
		'    <input type="hidden" name="userid" id="fmUserId" value="#{userid}" />' +
		'    <input type="hidden" name="avatarid" id="fmAvatarId" value="#{avatarid}" />' +
		'  </form><br/>' +
		'  <div id="fmUploadStatus"'+fm.comments.showUpload+'>' +
		'    <ul>' +
		'      <li class="label">'+fm.comments.settings.translate.attach+'</li>' +
		'    </ul>' +
		'    <a id="uploadBtn" class="fmButton" href="#" onclick="return false;">' +
		'      <div id="fmFlashSelectFile" style="display:block; position: absolute;"></div> ' + 
		       fm.comments.settings.translate.browse + 
		'      <span id="fmSelectFileBtn"></span>' +
		'    </a>' +
		'    <div id="fileList" class="fmClearfix"></div>' +
		'    <div class="fmClearfix"></div>' +
		'    <div class="fmButtonWrapper fmClearfix"><a class="fmButton" onclick="this.blur(); fm.swfuploader.startUpload(); return false;">'+fm.comments.settings.translate.postComment+'</a></div>' +
		'  </div>' + 
		'  <div id="postUpload"></div>' +
		'  <div class="fmClear"></div>' +
		'  <div id="loader" style="display:none">'+fm.comments.settings.translate.comment+'</div>' +
		'</div>';
	
	if (fm.comments.settings.enableUpload === false) {
		fm.comments.commentForm = 
			'<div class="fmFormbox fmClearfix" id="textOnlyCommentformContainer">' +
			'  <form method="POST" action="#" id="fmPostTextComment" class="fmClearFix" onsubmit="return fm.comments.submitTextComment(this);">'+
			'    <input type="hidden" name="parent" id="fmParent" value="#{parent}" />' +
			'    <input type="hidden" name="username" id="fmUsername" value="#{username}" />' +
			'    <input type="hidden" name="firstname" id="fmFirstName" value="#{firstname}" />' +
			'    <input type="hidden" name="lastname" id="fmLastName" value="#{lastname}" />' +
			'    <input type="hidden" name="userid" id="fmUserId" value="#{userid}" />' +
			'    <input type="hidden" name="avatarid" id="fmAvatarId" value="#{avatarid}" />' +
			'    <ul>' +
			'      <li class="label"><label for="fmCommentText">'+fm.comments.settings.translate.comment+' '+fm.comments.lengthBlock+'</label></li>' +
			'      <li><textarea name="message" id="fmCommentText" class="fmTextArea fmTextarea required" title="'+fm.comments.settings.translate.comment+'"></textarea></li>' +
			'      <li class="label"><br/><input type="button" value="'+fm.comments.settings.translate.postComment+'" class="fmButton" onClick="return fm.comments.submitTextComment(jQuery(\'#fmPostAnonComment\'));"/></li>' +
			'    </ul>' +
			'  </form>' +
			'</div>';	
	}
	
	fm.comments.anonymousCommentForm = 
		'<div class="fmFormbox fmClearfix" id="anonCommentformContainer">' +
		'  <form method="POST" action="#" id="fmPostAnonComment" class="fmClearFix" onsubmit="return fm.comments.submitAnonComment(this);">' +
		'    <ul>' +
		'      <li class="label"><label for="fmCommentAuthor">'+fm.comments.settings.translate.name+'</label></li>' +
		'      <li><input type="text" name="author" title="'+fm.comments.settings.translate.name+'"id="fmCommentAuthor" class="fmTextInput fmInput required" /></li>' +
		'      <li class="label"><label for="fmCommentEmail">'+fm.comments.settings.translate.email+'</label></li>' +
		'      <li><input type="text" name="email" id="fmCommentEmail" class="fmTextInput fmEmail fmInput required" title="'+fm.comments.settings.translate.email+'"/></li>' + 
		'      <li class="label"><label for="fmCommentText">'+fm.comments.settings.translate.comment+' '+fm.comments.lengthBlock+'</label></li>' +
		'      <li><textarea name="message" id="fmCommentText" class="fmTextArea fmTextarea required" title="'+fm.comments.settings.translate.comment+'"></textarea></li>' +
		'      <li class="label"><br/><input type="submit" value="'+fm.comments.settings.translate.postComment+'" class="fmButton" /></li>' +
		'    </ul>' +
		'  </form>' +
		'</div>';

	fm.comments.registerForm = 
		'<div id="fmCommentRegister" class="fmFormbox">' +
		'  <form method="post" id="fmRegisterForm" onsubmit="fm.comments.register(this); return false;">' + 
		'    <ul>' +
		'      <li class="label"><label for="fmRegisterUsername">'+fm.comments.settings.translate.username+'</label></li>' +
		'      <li><input type="text" class="fmTextInput fmInput fmUsername checkUnique required" id="fmRegisterUsername" name="user" title="'+fm.comments.settings.translate.username+'" value="" /></li>' +
		'      <li class="label"><label for="fmFirstname">'+fm.comments.settings.translate.firstName+'</label></li>' +
		'      <li><input type="text" class="fmTextInput fmInput required" id="fmFirstname" name="firstname" title="'+fm.comments.settings.translate.firstName+'" value="" /></li>' +
		'      <li class="label"><label for="lastname">'+fm.comments.settings.translate.lastName+'</label></li>' +
		'      <li><input type="text" class="fmTextInput fmInput required" id="lastname" name="lastname" title="'+fm.comments.settings.translate.lastName+'" value="" /></li>' +
		'      <li class="label"><label for="email">'+fm.comments.settings.translate.email+'</label></li>' +
		'      <li><input type="text" class="fmTextInput fmEmail fmInput checkUnique required" id="email" name="email" title="'+fm.comments.settings.translate.email+'" value="" /></li>' +
		'      <li class="label"><label for="password">'+fm.comments.settings.translate.password+'</label></li>' +
		'      <li><input type="password" class="fmTextInput fmPassword fmInput required" id="password" name="password" title="'+fm.comments.settings.translate.password+'" /></li>' +
		'      <li class="label"><label for="confirmpassword">'+fm.comments.settings.translate.confirmPassword+'</label></li>' + 
		'      <li><input type="password" class="fmTextInput fmPasswordConfirm fmInput" id="confirmpassword" title="'+fm.comments.settings.translate.confirmPassword+'" /></li>' +
		'      <li class="label"><br/><input type="submit" class="fmButton" value="'+fm.comments.settings.translate.createAccount+'"/></li>' + 
		'    </ul>' + 
		'  </form>' + 
		'</div>';

	// Containers
	fm.comments.loginForm = 
		'<div id="fmLoginFormContainer" class="fmFormbox fmClearfix">' + 
		'  <form action="http://filemobile.com/services/json" method="post" id="fmLoginForm" onSubmit="fm.comments.login(); return false;">' +
		'  <ul>';
		
	fm.comments.settings.usernameForm = true;
		
	if (fm.comments.settings.usernameForm === true) {
		fm.comments.loginForm += '    <li class="label">Username</li>' +
			'    <li><input type="text" name="username" id="fmLoginUsername" class="fmTextInput fmInput required"></li>';
	} else {
		fm.comments.loginForm += '    <li class="label">Email</li>' +
			'    <li><input type="text" name="email" id="fmLoginEmail" class="fmTextInput fmInput required"></li>';
	}
	
	fm.comments.loginForm += '    <li class="label">Password</li>' + 
		'    <li><input type="password" name="password" id="fmLoginPassword" class="fmTextInput fmInput required"></li>' +
		'    <li class="label"><br/><input type="submit" value="Login" onclick="fm.comments.login(); return false;" class="fmButton"></li>' +
		'  </ul>' + 
		'  </form>' + 
		'</div>';

	// If profiles are enabled we generate links, otherwise simple <span> tags
	if (fm.comments.settings.avatar === false) {
		fm.comments.profileBlockAvatar = '';
		fm.comments.profileBlockLink = '<span class="fmName">#{username}</span>';
	} else if (fm.comments.settings.profiles !== false) {
		fm.comments.profileBlockAvatar = '<a href="'+fm.comments.settings.profiles+'#{profileid}" class="fmAvatar"><img src="#{avatar}" /></a>';
		fm.comments.profileBlockLink = '<a href="'+fm.comments.settings.profiles+'#{profileid}" class="fmName">#{username}</a>';
	} else {
		fm.comments.profileBlockAvatar = '<span class="fmAvatar"><img src="#{avatar}" /></span>';
		fm.comments.profileBlockLink = '<span class="fmName">#{username}</span>';
	}

	if (fm.comments.settings.liking) {
		fm.comments.likingBlock = '<div class="fmRating"> <div class="fmValue" id="vote#{mid}">#{votecount}</div><span class="fmLike" onclick="fm.comments.like(#{mid})">'+fm.comments.settings.translate.like+'</span></div>';
	}

	if (fm.comments.settings.report) {
		fm.comments.reportClass = ' fmReportComment';
		fm.comments.reportBlock = '<span class="fmReport" onclick="fm.comments.openReportBox(#{mid}, this)">'+fm.comments.settings.translate.report+'</span>';
	}

	fm.comments.commentClass = fm.comments.reportClass;

	// Comment templates
	fm.comments.commentBlock = 
		'<div class="fmComment'+fm.comments.commentClass+' fmClearfix" id="comment_#{mid}">' + 
		'  <div class="fmUser fmClearfix"> '+
		     fm.comments.profileBlockAvatar+
		'    <div class="fmInfo fmClearfix"> '+fm.comments.profileBlockLink+' <abbr title="#{upload}" class="fmTimestamp">#{uploadage}</abbr> </div>' +
		'  </div>' + 
		'  <div class="fmContent">#{comment}</div>'+fm.comments.reportBlock+fm.comments.likingBlock+
		'</div>';

	fm.comments.commentBlockWithImage = 
		'<div class="fmComment'+fm.comments.commentClass+' fmClearfix" id="comment_#{mid}">' + 
		'  <div class="fmUser fmClearfix"> '+
		     fm.comments.profileBlockAvatar+
		'    <div class="fmInfo fmClearfix"> '+fm.comments.profileBlockLink+' <abbr title="#{upload}" class="fmTimestamp">#{uploadage}</abbr></div>' +
		'  </div>' + 
		'  <div class="fmContent"><img src="#{image}/'+fm.comments.settings.imageTranscoder+'" />#{comment}</div>'+fm.comments.reportBlock+fm.comments.likingBlock+
		'</div>';

	fm.comments.commentBlockWithVideo = 
		'<div class="fmComment'+fm.comments.commentClass+' fmClearfix" id="comment_#{mid}">' + 
		'  <div class="fmUser fmClearfix">  ' +
		     fm.comments.profileBlockAvatar + 
		'    <div class="fmInfo fmClearfix"> '+fm.comments.profileBlockLink+' <abbr title="#{upload}" class="fmTimestamp">#{uploadage}</abbr></div>' +
		'  </div>' + 
		'  <div class="fmContent">' + 
		'    <object width="'+fm.comments.settings.videoPlayerWidth+'" height="'+fm.comments.settings.videoPlayerHeight+'" id="fmVideo#{mid}" 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}&amp;ext='+fm.comments.settings.videoTranscoder;

    if (fm.comments.settings.wid > 0) { 
        fm.comments.commentBlockWithVideo += '&amp;wid='+fm.comments.settings.wid; 
    }

    fm.comments.commentBlockWithVideo += '&amp;sessionToken='+fm.cookies.getCookie('SABRE_ID')+'" name="FlashVars"/> </object><br/>#{comment}</div>'+fm.comments.reportBlock+fm.comments.likingBlock+'</div>';

    fm.comments.startOffset = 0;

    fm.comments.fetchUserInfo(function() { fm.comments.initPhase2() });

	if (fm.comments.settings.avatar === false) jQuery('#fmComments').addClass('fmNoAvatar');
	if (fm.comments.settings.liking === false) jQuery('#fmComments').addClass('fmNoLike');
	if (fm.comments.settings.likingInline === true) jQuery('#fmComments').addClass('fmInlineLike');
	
}

/**
 * This is the second phase for initialization.
 *
 * This can only be run if we have retrieved the current user' information.
 */
fm.comments.initPhase2 = function() {

	// Create the form validator and add the default error handler.
	fm.comments.formValidator = new FMFormValidate();
	fm.comments.formValidator.addValidationErrorListener(fm.comments.handleValidation);

    var args = {
        externalid    : fm.comments.settings.externalId,
        externaltitle : fm.comments.settings.externalTitle,
        externalurl   : fm.comments.settings.externalUrl
    }

    fm.comments.proxyRequest('media.retrieveCommentsForExternalId', args,

        function(result) {
        
        	fm.comments.settings.moderation = result.settings.moderation;
        	fm.comments.settings.anonymous = result.settings.anonymous;
        	fm.comments.settings.login = result.settings.login;
        	fm.comments.settings.register = result.settings.register;
    		
    		jQuery(fm.comments.settings.element).show();
    		
            fm.comments.parentId = result.parent.id;

            if (!fm.comments.settings.avatar) { jQuery('#fmComments').addClass('fmNoAvatar'); }
            
            fm.comments.renderComments();
            fm.comments.generateHeader();
                        
            if (fm.comments.settings.rating == true) {
                var Rate = new fm.comments.rateArticle();
                Rate.getRating(result.parent);
            }
            
            if (fm.comments.settings.logHit == true) {
                fm.comments.logHit(fm.comments.parentId);
            }
    	},
    	function(exception)  {
    		// oops, something went wrong
    		console.log(exception);
    	},
    	true
  	);

}

/**
 * This method fetches information about the currently logged in
 * user. If we already retrieved the information, it won't be called again.
 * 
 * When the user information is fetched, the resultHandler is called.
 */
fm.comments.fetchUserInfo = function(resultHandler) {

    // If we already have the info, we abort
    if (fm.comments.currentUser) {
        resultHandler();
        return;
    }

    fm.comments.proxyRequest('users.getLoggedInUser', {},
        function(result) {

            fm.comments.currentUser = result;
            fm.comments.isLoggedIn = parseInt(result.id) > 1;
            resultHandler(); 

        },
        function(result) {

            alert('While attempting to fetch the current users\' info we receive an error. Comments could not be loaded.');

        },
        false
    );

}

/**
 * This method makes an ajax request to the proxy file on the server
 */
fm.comments.proxyRequest = function(method, args, resultHandler, exceptionHandler, async) {

    // 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 (async == null) {
    	async = true;
    }
       
	var ajax = jQuery.ajax({
 		type: 'POST',
        url: fm.comments.settings.proxy,
        data: args,
		dataType: 'html',
		async: async,
        success: function(data) {
        	var obj = jQuery.parseJSON(jQuery.trim(data));
            if (obj.status) {
                resultHandler(obj.result);
            } else {
				if (exceptionHandler) {
					exceptionHandler(obj);
				} else {
					alert('Uncaught exception: ' + obj["result"]);
				}
            }
        },
        error: function(data) {
        	console.log(data);
        }
    });

}

/**
 * This method handles any form validation errors, and attempts to display an appropriate
 * message to the user.
 */
fm.comments.handleValidation = function(element,message) {

	// we check if it already has the error class to prevent multiple messages appearing on the same jQuery(element)	
	if (!jQuery(element).hasClass('errorField')) {
	
		// the name of the jQuery(element)
		var name = message.substr(0,message.indexOf(' '));
		
		// the actually error message
		var originalMessage = message;
		var message = message.substr(message.indexOf(' '));
		
		// if its a checkbox, don't highlight the jQuery(element) but highlight the text beside it
		if (jQuery(element).type == "checkbox") {
			var label = jQuery(jQuery(element)).next();
		} else {
			var label = jQuery(jQuery(element).parent()[0]).prev().children();
		}
		
		// the title we're going to use
		var title = jQuery(element).attr("title");
		
		// the title without an asterisk
		var titlesub = title;
		if (title.indexOf('*') >= 0) {
			titlesub = title.substr(0,title.indexOf('*'));
		}
		
		// the output
		var out = '';
		
		// check the message and output the right title and message combo
		if (name == jQuery(element).attr('name') && title) {
			if (message != "The email address supplied is already registered. Did you forget your login information?" && message.substr(1,8) != "username" && message.substr(0,11) != "The captcha") {
				if (title.indexOf('*') > -1) {
					out = titlesub+" "+message;
				} else {
					out = title+message;
				}
			} else if (message == "The email address supplied is already registered. Did you forget your login information?") {
				out = "The email address supplied is already registered.";
			} else {
				out = titlesub+" "+message;
			}
		} else {
		
			if (message.substr(1,8) === "username" && message.substr(14,6) !== "picked") {
				out = titlesub+" "+message.substr(10);
			} else	if (message.substr(1) === "passwords did not match") {
				out = "P"+message.substr(2);
			} else if (jQuery(element).type == "checkbox") {
				out = titlesub+message;
			} else {
				out = title+" "+originalMessage;
			}
		}
		
		// get all the labels in this from
		var labels = jQuery('label');
		for(var i=0;i<labels.length;i++) {
			// check all the labels for the one that matches the failed form jQuery(element)
			if (labels[i].htmlFor == jQuery(element).attr('id')) {
				// put the message inside the label
				//if (jQuery(element).type != "checkbox") {
				jQuery(labels[i]).html(out);
				//}
				// make the label stand out
				jQuery(labels[i]).addClass('error');
				// make the input stand out
				jQuery(element).addClass('errorField');
				// scroll the browser to that jQuery(element).
			}
		}
	
		// remove the styles from the failed form jQuery(element) and the label
		function removeStyles(t) {
			// search though all the labels again
			for(var i=0;i<labels.length;i++) {
				// find the label that matches the failed form jQuery(element)
				if (labels[i].htmlFor == jQuery(element).attr('id')) {
					// return everything to normal
					jQuery(labels[i]).html(t);
					jQuery(labels[i]).removeClass('error');
					jQuery(element).removeClass('errorField');
				}
			}
		}

	}

	// we want the jQuery(element) and label to retrun to normal when the user relizes the error.
	jQuery(element).focusin(function() {
		removeStyles(title);
	});
}

/**
 * This function generates the comments interface
 */
fm.comments.generateHeader = function() {
	
	var code = '';

	if(fm.comments.currentUser.id > 1){
		// logged in user
		var fmCommentFormParams = {
            parent    : fm.comments.parentId, 
            username  : fm.comments.currentUser.user, 
            userid    : fm.comments.currentUser.id, 
            avatarid  : fm.comments.currentUser.avatar,
            firstname : fm.comments.currentUser.firstname,
            lastname  : fm.comments.currentUser.lastname
        };
		var renderedCommentForm = jQuery.tmpl(fm.comments.commentForm, fmCommentFormParams);
		// create tabs
		
		var last = '';		
		code += '<ul class="fmTabs fmClearfix">';
		
		if (fm.comments.settings.webcam != false) {
			code += '<li onclick="fm.comments.tabs(this);" class="fmActive">'+fm.comments.settings.translate.comment+'</li><li class="fmLast" onclick="fm.comments.tabs(this);">'+fm.comments.settings.translate.webcam+'</li>';
		}
		
		code += '<li class="fmStyleless">'+fm.comments.settings.translate.welcome+''+fm.comments.stripHTML(fm.comments.currentUser.user)+' / <a href="javascript:fm.comments.logout()">'+fm.comments.settings.translate.logout+'</a></li></ul>';
		// create tab containers
		code += '<div id="fmTab0" class="fmTab fmClearfix">'+renderedCommentForm+'</div>';
		if (fm.comments.settings.webcam != false) {
			code += '<div id="fmTab1" class="fmTab fmClearfix" style="display:none;"><object id="" class="fmWebcam" 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='+fm.comments.settings.vhost+'&parentid='+fm.comments.parentId+'&injector='+fm.comments.settings.injector+'&recordingLength=20&sessiontoken='+fm.cookies.getCookie('SABRE_ID')+'" name="FlashVars"/></object></div>';
		}
	} else {
	
		if (fm.comments.settings.disableComments) {
			code += '<div id="fmCommentsDisabled">'+fm.comments.settings.translate.commentsDisabled+'</div>';
		} else {
			//anonymous user
			var fmAnonCommentFormParams = {parent : fm.comments.parentId};
			renderedAnonCommentForm = jQuery.tmpl(fm.comments.anonymousCommentForm, fmAnonCommentFormParams);
			// create tabs
			
			var tabCount = 0;
			
			if (fm.comments.settings.login || fm.comments.settings.register ) {
				
				if (fm.comments.settings.anonymous == false && fm.comments.settings.login == false && fm.comments.settings.register == false ) { } else { code += '<ul class="fmTabs fmClearfix">'; }
				
				if (tabCount == 0) {
					last = 'fmActive';
				} else {
					last = 'fmLast';
				}
				
				if (fm.comments.settings.anonymous != false) {
					tabCount++;
					code +='<li onClick="fm.comments.tabs(this);" class="fmActive">'+fm.comments.settings.translate.guestComment+'</li>';
				}
				
				if (tabCount == 0) {
					last = 'fmActive';
				} else {
					last = 'fmLast';
				}
				
				if (fm.comments.settings.login == true) {
					tabCount++;
					code +='<li class="'+last+'" onClick="fm.comments.tabs(this);">'+fm.comments.settings.translate.login+'</li>';
				} else if (fm.comments.settings.login != false) {
					code +='<li class="'+last+'">'+fm.comments.settings.login+'</li>';
				}
				
				if (tabCount == 0) {
					last = 'fmActive';
				} else {
					last = 'fmLast';
				}
				
				if (fm.comments.settings.register == true) {
					tabCount++;
					code +='<li class="'+last+'" onClick="fm.comments.tabs(this);">'+fm.comments.settings.translate.register+'</li>';
				} else if (fm.comments.settings.register != false) {
					code +='<li class="'+last+'">'+fm.comments.settings.register+'</li>';
				}
				
				if (fm.comments.settings.anonymous == false && fm.comments.settings.login == false && fm.comments.settings.register == false ) { } else { code += '</ul>'; }
				
			} else {
				
				var showHeader = true;
				
			}
			
			tabCount = -1;
			
			// create tab containers
			
			if (fm.comments.settings.anonymous != false) {
				
				tabCount++;
			
				code += '<div id="fmTab'+tabCount+'" class="fmTab fmClearfix">';
				
				if (showHeader) {
					code += '<h6>'+fm.comments.settings.translate.guestComment+'</h6>';	
				}
				
				if (fm.comments.settings.anonymous != true && fm.comments.settings.anonymous != false) {
					code += fm.comments.settings.anonymous;
				} else {
					code += renderedAnonCommentForm;
				}
				
				code += '</div>';
				
			}
			
			if (fm.comments.settings.login == true) {
			
				tabCount++;
				
				if (tabCount != 0) {
					style = ' style="display:none;"'
				} else {
					style = '';
				}
			
				code += '<div id="fmTab'+tabCount+'" class="fmTab fmClearfix"'+style+'>'+fm.comments.loginForm+'</div>';
				
			}
			
			if (fm.comments.settings.register == true) {
				
				tabCount++;
				
				if (tabCount != 0) {
					style = ' style="display:none;"'
				} else {
					style = '';
				}
				
				code += '<div id="fmTab'+tabCount+'" class="fmTab fmClearfix"'+style+'>'+fm.comments.registerForm+'</div>';
				
			}
		}
	}
	
	// create sort options and show the number of total comments
	links = '<div id="fmCommentCount" class="fmLeft"></div>';
	
	if (fm.comments.settings.sortSelect === true) {
	
		links += '<select class="fmRight fmSelect">';
		
		// place the default sort option at the top of the list (works better then selected="selected")
		if (fm.comments.settings.sort == "upload DESC") {
			links += '<option value="upload DESC">'+fm.comments.settings.translate.newToOld+'</option>';
			links += '<option value="upload ASC">'+fm.comments.settings.translate.oldToNew+'</option>';
			if (fm.comments.settings.liking) {
				links += '<option value="votecount DESC, upload ASC">'+fm.comments.settings.translate.mostLikes+'</option>';	
			}
		} else if (fm.comments.settings.sort == "upload ASC"){
			links += '<option value="upload ASC">'+fm.comments.settings.translate.oldToNew+'</option>';
			links += '<option value="upload DESC">'+fm.comments.settings.translate.newToOld+'</option>';
			if (fm.comments.settings.liking) {
				links += '<option value="votecount DESC, upload ASC">'+fm.comments.settings.translate.mostLikes+'</option>';
			}	
		} else {
			if (fm.comments.settings.liking) {
				links += '<option value="votecount DESC, upload ASC">'+fm.comments.settings.translate.mostLikes+'</option>';	
			}
			links += '<option value="upload DESC">'+fm.comments.settings.translate.newToOld+'</option>';
			links += '<option value="upload ASC">'+fm.comments.settings.translate.oldToNew+'</option>';		
		}
		
		links += '</select>';
	
	}
	
	// create button to load more comments
	if (!fm.comments.settings.pager) {
		more = '<a class="fmButton" id="fmMoreCommentsBtn" style="display:none;">'+fm.comments.settings.translate.moreComments+'</a>';
	} else {
		more = '';
	}
	
	// write all info into their containers
	jQuery('#fmCommentsBox').html(code);
	jQuery('#fmCommentsHeader').html(links);
	jQuery('#fmCommentsMore').html(more);
	
	jQuery('#fmCommentsHeader .fmSelect').change(function() {
		if(jQuery(this).val() != ''){
			var sort = jQuery(this).val();
			fm.comments.renderComments({sort:jQuery(this).val(),newSort:true});
		}
	});
	
	jQuery('#fmMoreCommentsBtn').click(function() {
		fm.comments.renderComments();
	});

	// update the upload times every 15 seconds
	setInterval(fm.comments.updateDateTime,15000);
	
	// turn on auto update
	if (fm.comments.settings.autoUpdate === true && fm.comments.settings.pager !== true) {
		setInterval("fm.comments.autoUpdate()",fm.comments.settings.autoUpdateTime*1000);
	}
	
	// turn on the comment length limiter
	if (fm.comments.settings.maxLengthNumber !== false && fm.comments.settings.maxLengthNumber > 0) {
		fm.comments.limitCommentLength();
	}
	
	// Start the uploader if required
	if (jQuery('#fmFlashSelectFile').length > 0) {
		fm.swfuploader.init(jQuery('#fmFlashSelectFile'));
	}
}

fm.comments.renderComments = function(settings) {

	if (typeof settings == 'undefined') {
		settings = {};
	} 

	if(settings.sort){ fm.comments.settings.sort = settings.sort };
	if(settings.newSort == true) { fm.comments.startOffset = 0; }
	// swap the text on the 'more comments' button with a loading image
	if (jQuery('#fmMoreCommentsBtn')) {
		jQuery('#fmMoreCommentsBtn').html('<div class="fmLoadingIcon"></div>');
		
	}
	//
	if (fm.comments.settings.pager && fm.comments.getQueryVariable('fmPage')) {
		fm.comments.startOffset = (parseInt(fm.comments.getQueryVariable('fmPage'))-1)*fm.comments.settings.pageSize;
	}
	
	if (parseInt(settings.ajaxPage) >= 0) {
		fm.comments.startOffset = ajaxPage*fm.comments.settings.pageSize-fm.comments.settings.pageSize;
	}
	//
	if (fm.comments.settings.moderation == 'pre'){
		moderationStatus = 'approved';
	} else {
		moderationStatus = 'notdenied'
	}
	
	if (settings.offset != null) {
		fm.comments.startOffset = settings.offset*fm.comments.settings.pageSize-fm.comments.settings.pageSize;
	}
	
	var fields = ['filetype','uid','user_name','votecount','author','upload','message','publicUrl','status','avatar'];

	if (fm.comments.settings.showFirstName === true){
		fields.push('user_firstname');
	}
	
	if (fm.comments.settings.showLastName === true){
		fields.push('user_lastname');
	}
		
	var args = {
		sort     : fm.comments.settings.sort,
		limit    : fm.comments.settings.pageSize,
		start    : fm.comments.startOffset,
		parentid : fm.comments.parentId,
		context  : "comment",
		includeChildren : 1,
		channel  : 0,
		fields   : fields
	}
	
	fm.comments.proxyRequest('media.getFiles', args,
		function(result2) {
			// find out how many total comments there are
			fm.comments.commentCount = result2.totalCount;
			jQuery('#fmCommentCount').html(fm.comments.commentCount+" "+fm.comments.settings.translate.comments); // display the comment count

			if (fm.comments.settings.pager && (fm.comments.settings.externalId || fm.comments.settings.externalTitle) || fm.comments.settings.pager && fm.comments.settings.pagerAjax) {
				fm.comments.pager(fm.comments.startOffset,fm.comments.settings.pageSize,fm.comments.commentCount);
			}
			
			// increase the counter
			fm.comments.startOffset = fm.comments.startOffset + fm.comments.settings.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 (fm.comments.startOffset <= fm.comments.settings.pageSize || fm.comments.settings.pager) {
					jQuery('#fmComments').html("");
				}
				for (i=0;i<data.length;i++) {
					
					var renderedComment = fm.comments.displayComment(data[i]);
					
					// insert the comment into the list
					jQuery('#fmComments').append(renderedComment);
					
				};
				// hide the more comments button if there aren't any more comments to load
				if (data.length < fm.comments.settings.pageSize || fm.comments.startOffset == result2.totalCount ) {
					jQuery('#fmMoreCommentsBtn').hide();
				} else {
					jQuery('#fmMoreCommentsBtn').show();
				}
				// replace the text on the more comments button
				if (jQuery('#fmMoreCommentsBtn')) {
					jQuery('#fmMoreCommentsBtn').html(fm.comments.settings.translate.moreComments);
				}
				
			} else {
				// display the message that there are no comments yet
				jQuery('#fmComments').html('<div id="fmNoComments">'+fm.comments.settings.translate.noComments+'</div>');
			}
		},
		function(exception2) {	
			// oops, something went wrong
			console.log(exception2);
		},
		true
	);
}

fm.comments.like = function(mid) {
	// if the user isn't logged in display the error message asking them to log in
	if (!fm.comments.isLoggedIn) {
		alert(fm.comments.settings.translate.loginRequired);
        return;
    }
    if (!jQuery('#vote'+mid).next().hasClass("fmDisabled")) {	
        jQuery('#vote'+mid).next().addClass("fmDisabled");
        jQuery('#vote'+mid).html(parseInt(jQuery('#vote'+mid).html())+1);
        fm.comments.proxyRequest('media.rate', {"mid":parseInt(mid),"uid":fm.comments.currentUser.id,"rating":10,"returnData":true},
            function(result) {
                // change the number after the action has been successful
                // jQuery('#vote'+mid).innerHTML = result.votecount;
            },
            function(exception) { console.log(exception); }
        );
    }
}

fm.comments.openReportBox = function(mid, e) {
	if (jQuery('#fmReportBox')) { jQuery('#fmReportBox').remove() }
	
	var selectBox = '<option value="">---</option>';
	selectBox += '<option value="'+fm.comments.settings.translate.reason1+'">'+fm.comments.settings.translate.frontReason1+'</option>';
	if (fm.comments.settings.translate.reason2.length > 0) {
		selectBox += '<option value="'+fm.comments.settings.translate.reason2+'">'+fm.comments.settings.translate.frontReason2+'</option>';
	}
	if (fm.comments.settings.translate.reason3.length > 0) {
		selectBox += '<option value="'+fm.comments.settings.translate.reason3+'">'+fm.comments.settings.translate.frontReason3+'</option>';
	}
	
	jQuery(e).after('<div id="fmReportBox" class="fmClearfix"><div class="fmTitle">'+fm.comments.settings.translate.reportComment+'</div><span class="fmReport" onclick="jQuery(\'#fmReportBox\').remove();">'+fm.comments.settings.translate.close+'</span> <p>'+fm.comments.settings.translate.reportDescription+'</p><select name="reason" class="fmSelect" id="fmReportReason">'+selectBox+'</select><span class="fmButton" onclick="fm.comments.sendReport('+mid+',jQuery(\'#fmReportReason\').val());">'+fm.comments.settings.translate.report+'</span><span class="fmButton" onclick="jQuery(\'#fmReportBox\').remove();">'+fm.comments.settings.translate.cancel+'</span></div>');
}


// Figure out the relative upload time
fm.comments.makeUploadAge = function(time_value) {
	if (!time_value) {
		return "error";
	}
	var values = time_value.split(" "); // split up the incoming date format
	var v2 = values[0].split("-");

	v2[5] = v2[1];

	switch(v2[1]) {
		case "01": case "1": v2[1] = "Jan"; v2[3] = fm.comments.settings.translate.january; break;
		case "02": case "2": v2[1] = "Feb"; v2[3] = fm.comments.settings.translate.february; break;
		case "03": case "3": v2[1] = "Mar"; v2[3] = fm.comments.settings.translate.march; break;
		case "04": case "4": v2[1] = "Apr"; v2[3] = fm.comments.settings.translate.april; break;
		case "05": case "5": v2[1] = "May"; v2[3] = fm.comments.settings.translate.may; break;
		case "06": case "6": v2[1] = "Jun"; v2[3] = fm.comments.settings.translate.june; break;
		case "07": case "7": v2[1] = "Jul"; v2[3] = fm.comments.settings.translate.july; break;
		case "08": case "8": v2[1] = "Aug"; v2[3] = fm.comments.settings.translate.august; break;
		case "09": case "9": v2[1] = "Sep"; v2[3] = fm.comments.settings.translate.september; break;
		case "10": v2[1] = "Oct"; v2[3] = fm.comments.settings.translate.october; break;
		case "11": v2[1] = "Nov"; v2[3] = fm.comments.settings.translate.november; break;
		case "12": v2[1] = "Dec"; v2[3] = fm.comments.settings.translate.december; 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);
	
	var dayOfWeek = new Date(time_value).getDay()+'';
	
	switch(dayOfWeek) {
		case "0": dayOfWeek = fm.comments.settings.translate.sunday; break;
		case "1": dayOfWeek = fm.comments.settings.translate.monday; break;
		case "2": dayOfWeek = fm.comments.settings.translate.tuesday; break;
		case "3": dayOfWeek = fm.comments.settings.translate.wednesday; break;
		case "4": dayOfWeek = fm.comments.settings.translate.thursday; break;
		case "5": dayOfWeek = fm.comments.settings.translate.friday; break;
		case "6": dayOfWeek = fm.comments.settings.translate.saturday; break;
	}
	
	// determine what information to show based on the elapsed time
	var r = '';
	
	var time = values[1].split(':');
	if (time[0] > 12) {
		time[0] = time[0]-12;
		time[2] = "pm";
	} else {
		time[2] = "am";
	}

	v2[6] = v2[2];

	if (v2[2].substr(0,1) == '0') {
		v2[2] = v2[2].substr(1);
	}

	if (delta < 2) { r = fm.comments.settings.translate.justNow;} 
	else if(delta < 60) { r = fm.comments.settings.translate.momentsAgo; } 
	else if(delta < 120) { r = fm.comments.settings.translate.minuteAgo;} 
	else if(delta < (45*60)) { r = (parseInt(delta / 60)).toString() + ' '+fm.comments.settings.translate.minutesAgo; } 
	else if(delta < (2*90*60)) {  r = fm.comments.settings.translate.hourAgo; }  // 2* because sometimes read 1 hours ago
	else if(delta < (24*60*60)) { r = (parseInt(delta / 3600)).toString() + ' ' + fm.comments.settings.translate.hoursAgo; } 
	else if(delta < (48*60*60)) { r = '1 '+fm.comments.settings.translate.dayAgo } 
	else if(delta < (6*24*60*60)) { r = (parseInt(delta / 86400)).toString() + ' '+fm.comments.settings.translate.daysAgo; } 
	else if(fm.comments.settings.longDate === false) { r = v2[5]+'/'+v2[6]+'/'+v2[0]+" "+time[0]+":"+time[1]+time[2]; }
	else { r = dayOfWeek+", "+v2[3]+" "+v2[2]+", "+v2[0]+" "+time[0]+":"+time[1]+time[2]; } 
	// return the upload age
	if (fm.comments.settings.exactDate == true) {
		return dayOfWeek+", "+v2[3]+" "+v2[2]+", "+v2[0]+" "+time[0]+":"+time[1]+time[2];
	} else {
		return r;
	}
}

// Change the relative upload time
fm.comments.updateDateTime = function() {
	jQuery('#fmComments abbr').each(function() {	// grab all the <abbr> tags
		jQuery(this).html(fm.comments.makeUploadAge(jQuery(this).attr('title'))); // update the value with the new time
	});
}

// Get the current date and time
fm.comments.getDateTime = function() {	
	
	// Initialize the variables
	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();
	
	// Prepend a zero when needed
	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; }
	
	// Create the date
	var d = year+"-"+month+"-"+date+" "+hours+":"+minutes+":"+seconds;
	return d;
}

// Limit comment length
fm.comments.limitCommentLength = function() {

	jQuery('#fmCommentText').keydown(function(e) {
		str = jQuery(this).val();
		if (str.length > fm.comments.settings.maxLengthNumber && (e.keyCode != 8 || e.keyCode != 46)) {
			jQuery(this).val(str.substr(0,fm.comments.settings.maxLengthNumber));
		}
	});
	
	jQuery('#fmCommentText').keyup(function(e) {
	
		if (jQuery('#uploadForm label[for="fmCommentText"] span').length < 1) {
			jQuery('#uploadForm label[for="fmCommentText"]').append(' '+fm.comments.lengthBlock);
		}

		var str = jQuery(this).val();
		var out;
		
		if (str.length > fm.comments.settings.maxLengthNumber && (e.keyCode != 8 || e.keyCode != 46)) {
			jQuery(this).val(str.substr(0,fm.comments.settings.maxLengthNumber));
		}
		
		var len = str.length;
				
		if (len > fm.comments.settings.maxLengthNumber) {
			len = fm.comments.settings.maxLengthNumber;
		}
		
		if (fm.comments.settings.maxLengthCountdown === true) {
			if (len/fm.comments.settings.maxLengthNumber*100 >= 75) {
				out = '<span class="fmError">'+(fm.comments.settings.maxLengthNumber - len)+'</span>';
			} else {
				out = fm.comments.settings.maxLengthNumber - len;
			}
		} else {
			if (len/fm.comments.settings.maxLengthNumber*100 >= 75) {
				out = '<span class="fmError">'+len+'</span>/'+fm.comments.settings.maxLengthNumber+'';
			} else {
				out = len+'/'+fm.comments.settings.maxLengthNumber;
			}
		}
		
		jQuery('#fmCommentLength span').html(out);

	});
	
};

fm.comments.submitTextComment = function(e) {
	if (!fm.comments.formValidator.submit(e)) {
		return false;
	} else {
	
		// if the form validation fails dont do anything						
			if (!fm.comments.formValidator.submit(jQuery('#uploadForm'))){
				return false;
			// if the form validation passes create and send the comment
			} else if(fm.comments.formValidator.submit(jQuery('#uploadForm'))) {
				// toss up the overlay
				jQuery(jQuery('#uploadForm').parents()[0]).prepend('<div id="fmFormOverlay"></div>');
				// disable the comment text area
				jQuery('#uploadForm textarea').each(function(f) {
					f.disabled = true;
				});
				var comment = fm.comments.stripHTML(jQuery('#fmCommentText').val()).replace(/(\r\n|\r|\n)/g, "<br/>");
				
				// send the text commment
				var args = {
					parentid : jQuery('#fmParent').val(),
                    context  : 'comment',
                    author   : jQuery('#fmUsername').val(),
                    uid      : jQuery('#fmUserId').val(),
                    message  : comment,
                    injector : fm.comments.settings.injector
				}
				
				fm.comments.proxyRequest('media.insertTextFile', args,
			    	function(result) {
			    	
			    		var avatar = '';
						if(jQuery('#fmAvatarId').val() != 0) {
							if (fm.comments.settings.env == 'dev') avatar = 'http://fmdev.s3.amazonaws.com/storage/' + jQuery('#fmAvatarId').val() + '/12';
							else avatar = 'http://rstorage.filemobile.com/storage/' + jQuery('#fmAvatarId').val() + '/12';
						}
						else avatar = fm.comments.settings.defaultAvatar;
			    	
			    		// create the new comment
			    		var commentBody = {username: jQuery('#fmUsername').val(), userid: jQuery('#fmUserId').val(), avatar:avatar, comment:comment, votecount:'0', upload:fm.comments.getDateTime(), uploadage:fm.comments.settings.translate.justNow};
						var renderedComment = '<div id="fmNewPost">'+jQuery.tmpl(fm.comments.commentBlock,commentBody)+'</div>';
						// insert the new comment
						if (fm.comments.settings.sort == "upload DESC") {
							jQuery('#fmComments').prepend(renderedComment);
						} else {
			    			jQuery('#fmComments').append(renderedComment);
			    		}
			    		jQuery('#fmFormOverlay').addClass('fmNoBackground');
			    		// show the moderation message id needed
			    		if (fm.comments.settings.moderation == 'pre') {
			    			var out = fm.comments.settings.translate.moderationMessagePre;
			    		} else {
			    			var out = fm.comments.settings.translate.moderationMessagePost;
			    		}
			    		// display the message
			    		jQuery('#fmFormOverlay').html('<span class="fmSuccess">'+out+'</span>');
			    		fm.comments.updateCount();			    		
			    	},
			    	function(exception) {
			    		// remove the loader image and show the error and ok button
			    		jQuery('#fmFormOverlay').addClass('fmNoBackground');
			    		jQuery('#fmFormOverlay').html('<span class="fmError">'+fm.comments.settings.translate.error+'</span><a onclick="this.parents()[0].remove();" class="fmButton">'+fm.comments.settings.translate.close+'</a>');
						// re-enable the comment text area
						jQuery('#uploadForm textarea').each(function(f) {
							f.disabled = false;
						});
			    	},
			    	true
			  	);	
			  	return false;
			}

	
	}
	return false;
}

fm.comments.submitAnonComment = function(e) {
	if (!fm.comments.formValidator.submit(e)) {
		return false;
	} else {
		fm.comments.postAnonComment(jQuery('#fmCommentAuthor'), jQuery('#fmCommentEmail'), jQuery('#fmCommentText'), e);
	}
	return false;
}


fm.comments.getQueryVariable = function(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
} 

fm.comments.scroll = function(){
	jQuery('html,body').animate({scrollTop:(jQuery('#fmComments').offset().top)},fm.comments.settings.scrollDuration);
}

// Build the pager that sits below the comments where there are more then
fm.comments.pager = function(start,size,total) {

	var out = '';
	var pager = '';
	var first = '';
	var prev = '';
	var next = '';
	var last = '';
	var numbers = '';
	var url = document.location.href;
	var active = '';
	var current = 1;
	var limit = fm.comments.settings.pagerLimit;
	var button;
	var span = '<span class="fmButton fmDisabled#{css}">#{text}</span>';
	var scroll = '';
	var numberButton = 0;
	
	// scroll to the top of the comments on page change (if applicable)
	if (fm.comments.settings.scroll) {
		scroll = 'fm.comments.scroll();'
	}

	// set the button jQuery.tmpls
	if (fm.comments.settings.pagerAjax === true) {
		button = '<a class="fmButton#{css}" onclick="'+scroll+'fm.comments.renderComments({sort:0,newSort:false,ajaxPage:false,offset:#{page}});">#{text}</a>';
	} else {
		button = '<a class="fmButton#{css}" href="#{url}fmPage=#{page}">#{text}</a>';
	}
	
	// check the document for a query string
	if (url.indexOf("fmPage=") >= 0 || fm.comments.settings.pagerAjax) {
				
		// find out the current page
		if (fm.comments.settings.pagerAjax) {
			current = start/size+1;
		} else {
			current = parseInt(fm.comments.getQueryVariable('fmPage'));
		}
		
		// remove the fmPage variable from the URL
		url = url.substr(0,url.lastIndexOf('fmPage')-1);
		
		// add to or create the url query string
		if (url.indexOf("?") < 0) {
			url += "?";
		} else {
			url += "&";
		}
		
		// if this isn't the first page, add a previous link
		if (current > 1) {
			prev = jQuery.tmpl(button, {'url':url, page:(current-1), text:fm.comments.settings.translate.pagerPrev, css: ' fmPrev'});
			first = jQuery.tmpl(button, {'url':url, page:1, text:fm.comments.settings.translate.pagerFirst, css: ''});
		} else {
			prev = jQuery.tmpl(span, {text:fm.comments.settings.translate.pagerPrev, css: ' fmPrev'});
			first = jQuery.tmpl(span, {text:fm.comments.settings.translate.pagerFirst, css: ''});
		}
		
		
		// if this isn't the last page, add a next link
		if (current*size < total) {
			next = jQuery.tmpl(button, {'url':url, page:(current+1), text:fm.comments.settings.translate.pagerNext, css: ' fmNext'});
			last = jQuery.tmpl(button, {'url':url, page:(Math.ceil(total/size)), text:fm.comments.settings.translate.pagerLast, css: ''});
		} else {
			next = jQuery.tmpl(span, {text:fm.comments.settings.translate.pagerNext, css: ' fmNext'});
			last = jQuery.tmpl(span, {text:fm.comments.settings.translate.pagerLast, css: ''});
		}
		
	} else {
	
		// if theres no fmPage, show the first page of results
		var current = 1;
		
		// add to or create the query string
		if (url.indexOf("?") < 0) {
			url += "?";
		} else {
			url += "&";
		}
		
		// create the next button
		first = jQuery.tmpl(span, {text:fm.comments.settings.translate.pagerFirst, css: ''});
		prev = jQuery.tmpl(span, {text:fm.comments.settings.translate.pagerPrev, css: ' fmPrev'});
		next = jQuery.tmpl(button, {'url':url, page:(current+1), text:fm.comments.settings.translate.pagerNext, css: ' fmNext'});
		last = jQuery.tmpl(button, {'url':url, page:(Math.ceil(total/size)), text:fm.comments.settings.translate.pagerLast, css: ''});
		
	}
	
	// set how many numbers appear before and after the current page
	if (fm.comments.settings.pagerShowNumbers) {
	
		var firstNum = current - limit;
		var lastNum = current + limit;
		
		for (i=0;i<limit;i++) {
			if (firstNum < 1 && current > 0) {
				firstNum++;
				if (lastNum <= total/size) {
					lastNum++;
				}
			} else {
				break;
			}
		}
		
		for (i=0;i<limit;i++) {
			if (lastNum > total/size) {
				lastNum++;
				if (lastNum - limit >= Math.ceil(total/size)+1) {
					if (firstNum-1 > 0) {
						firstNum--;
					}
				}
			} else {
				break;
			}
		}
		
		numberButton = firstNum;
		
		var end = lastNum*size;
		if (end > total) {
			end = total;
		}
		
		// create the numbers buttons
		for (i=(numberButton-1)*size;i<end;i=i+size) {
			if (numberButton == current) {
			 	numbers += jQuery.tmpl(button, {'url':url, page:numberButton, text:numberButton, css: ' fmActive'});
			} else {
				numbers += jQuery.tmpl(button, {'url':url, page:numberButton, text:numberButton, css: ''});
			}
			numberButton++;
		}
		
	}
	
	// build the pager
	var addClass = '';
	if (fm.comments.settings.pagerShowFirstLast === false) {
		addClass += ' fmNoFirstLast';
	}
	if (fm.comments.settings.pagerShowPrevNext === false) {
		addClass += ' fmNoPrevNext';
	}
	if (fm.comments.settings.pagerShowNumbers === false) {
		addClass += ' fmNoNumbers';
	}
	
	pager += '<div class="fmPager fmClearfix'+addClass+'">';
	
	if (fm.comments.settings.pagerShowFirstLast === true) {
		pager += first;
	}
	if (fm.comments.settings.pagerShowPrevNext === true) {
		pager += prev;
	}
	if (fm.comments.settings.pagerShowNumbers === true) {
		pager += numbers;
	}
	if (fm.comments.settings.pagerShowPrevNext === true) {
		pager += next;
	}
	if (fm.comments.settings.pagerShowFirstLast === true) {
		pager += last;
	}
	
	pager += '</div>';
		
	// display the pager
	jQuery('#fmCommentsMore').html(pager);
	
	// center the pager (if applicable)
	if (fm.comments.settings.pagerCenter === true) {
		var pagerWidth = 0;
		jQuery('.fmPager').children().each(function(){
			pagerWidth += parseInt(jQuery(this).outerWidth(true));
		});
		
		jQuery('.fmPager').width(pagerWidth+'px');
		jQuery('.fmPager').css({'margin':'0px auto'});
	}
}

// 
fm.comments.tabs = function(e) {

	// get all list elements which will be our tabs
	jQuery(jQuery(e).parent()[0]).children().each(function(i) {
		if (e==this) {
		
			// show the tab the user just clicked
			if (jQuery('#fmTab'+i)) {
				jQuery('#fmTab'+i).show();
				jQuery(e).addClass('fmActive');
			}
			
		} else {
		
			// hide all the other tabs
			if (jQuery('#fmTab'+i)) {
				jQuery('#fmTab'+i).hide();
				jQuery(this).removeClass('fmActive');
			}
			
		}	
	});	
}

fm.comments.updateCount = function() {

	if (jQuery("#fmNoComments")) {
		jQuery("#fmNoComments").remove();	
	}
	
	// update the count 
	var x = jQuery('#fmCommentCount').html();
	var matches;
	
	// parse the number from the header and increment
	if (x) {
		matches = x.match(/^(\d+)/);
	} else {
		matches = ['0'];
	}
	
	jQuery('#fmCommentCount').html((parseInt(matches[0])+1)+" "+fm.comments.settings.translate.comments);
	
}

fm.comments.sendReport = function(mid,reason) {
	// display error if the user hasn't selected a reason.
	if (reason === '' || !reason) {
		jQuery('#fmReportReason').addClass('errorField');
		jQuery('#fmReportReason').change(function() {
			jQuery(this).removeClass('errorField');
		});
	} else {	
		// find the report button
		var btn = jQuery(jQuery('#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="'+fm.comments.settings.loadingIcon+'" class="fmLoading"/>');
			// send the request
			args = 'reason='+reason+'&mid='+mid;
			var ajax = jQuery.ajax({
				type: 'POST',
				url: fm.comments.settings.report,
		        data: args,
		        dataType: 'html',
				success: function(data) {
					// hide the buttons and the select element
					jQuery('#fmReportBox').find('select').remove();
					jQuery('#fmReportBox').find('.fmButton').remove();
					data = jQuery.parseJSON(jQuery.trim(data));
				    if (data.result) {
				    	// remove the 'report' link from the comment 
				   		jQuery('#fmReportBox').prev('.fmReport').remove();
				    	jQuery('#fmReportBox').find('p').text(fm.comments.settings.translate.reportSent);
				    	if (fm.comments.settings.reportFade == true) {
				    		jQuery('#fmReportBox').delay(5000).fadeOut(500);
				    	} else {
				    		jQuery('#fmReportBox').remove();
				    	}
				    } else {
				    	btn.removeAttr("disabled");
				    	jQuery('#fmReportBox').find('p').text(fm.comments.settings.translate.reportError);
				    }
				}
			});
		}
	}
}


fm.comments.confirmCredentials = function(username, password) {
 	fm.comments.proxyRequest('users.confirmCredentials', {"username":username, "password":password, "returnUserInfo":true, "login":true},
    	function(result) { 
    		if(result.id > 1) {
    			window.location.reload();
    		}
			else {
				alert(fm.comments.settings.translate.incorrectLogin);
				jQuery('#fmFormOverlay').remove();
			}
		},
		function(exception) { console.log(exception); },
		true
  	);
}

fm.comments.login = function() {

	// add the overlay to show the user something is happening
	jQuery(jQuery('#fmLoginForm').parents()[0]).prepend('<div id="fmFormOverlay"></div>');

	// get the form values
	var username = jQuery('#fmLoginUsername').val();
	var password = jQuery('#fmLoginPassword').val();
	
	fm.comments.confirmCredentials(username, password);
}

fm.comments.register = function(e) {

	jQuery(jQuery('#fmRegisterForm').parents()[0]).prepend('<div id="fmFormOverlay"></div>');

	if (!fm.comments.formValidator.submit(e)) {
		jQuery('#fmFormOverlay').remove();
		return false;
	} else {	
		var obj = jQuery(e).serializeArray();
	}
	
	jQuery('#fmRegisterForm input').each(function() {
		jQuery(this).attr("disabled", "disabled");
	});

	var name = [];
	var value = [];
	var params;
	
	for(key in obj) {
		for(keytwo in obj[key]) {
			if (keytwo == "name") {
				name.push(obj[key][keytwo]);
			} else {
				value.push(obj[key][keytwo]);
			}
		}
	}
	
	function toObject(names, values) {
	    var result = {};
	    for (var i = 0; i < names.length; i++)
	         result[names[i]] = values[i];
	    return result;
	}
	
	params = toObject(name, value);

	fm.comments.proxyRequest('users.register', params,  
    	function(result) {
    		fm.comments.confirmCredentials(params.user,params.password);
    		return false;
   		},
		function(exception) {
			jQuery('#fmFormOverlay').addClass("fmNoBackground");
			jQuery('#fmFormOverlay').html('<span class="fmError">'+fm.comments.settings.translate.error+'</span><a onclick="jQuery(jQuery(this).parents()[0]).remove();" class="fmButton">'+fm.comments.settings.translate.close+'</a>');
			jQuery('#fmRegisterForm input').each(function() {
				jQuery(this).attr("disabled",'');
			});
			return false;
		},
		true
  	);
	return false;

}

fm.comments.stripHTML = function(html){

	// replace line breaks with a placeholder
	html = html.replace(/\r\n/g, "#{fmLineBreak}").replace(/\n/g, "#{fmLineBreak}").replace(/\r/g, "#{fmLineBreak}");
	
	// strip the HTML
	html = jQuery('<div>' + html + '</div>').text();
	
	// replace the line breaks with HTML tags
	return html.replace(/#{fmLineBreak}/g, "<br/>");
	
}

fm.comments.postAnonComment = function(author, email, comment, e) {
	author = fm.comments.stripHTML(author.val());
	email = fm.comments.stripHTML(email.val());
	comment = fm.comments.stripHTML(comment.val());
	//
	var x = jQuery(e).attr("id");
	// disable the text inputs and submit button
	jQuery(x+' input').each(function(f) {
		f.disabled = true;
	});
	// disable the comment text area
	jQuery(x+' textarea').each(function(f) {
		f.disabled = true;
	});
	// add the error overlay
	jQuery(jQuery(e).parents()[0]).prepend('<div id="fmFormOverlay"></div>');
	// set the variables for the jQuery.tmpl
	
	var args = {
		parentid : fm.comments.parentId,
		context  : 'comment',
		author   : author,
		sender   : email,
		message  : comment,
	    injector : fm.comments.settings.injector
	}

	fm.comments.proxyRequest('media.insertTextFile', args,
    	function(result) {
    	    	
    		var commentBody = {
		        'username'  : author, 
		        'avatar'    : fm.comments.settings.defaultAvatar, 
		        'comment'   : comment, 
		        'votecount' : '0', 
		        'upload'    : fm.comments.getDateTime(), 
		        'uploadage' : fm.comments.settings.translate.justNow, 
		        'mid'       : result, 
		        'profileid' : '0'
		    };
		    
			var renderedComment = '<div id="fmNewPost">'+jQuery.tmpl(fm.comments.commentBlock, commentBody)+'</div>';
    	
    		fm.comments.updateCount();
			// insert the new comment
			if (fm.comments.settings.sort == "upload DESC") {
				jQuery('#fmComments').prepend(renderedComment);
			} else {
    			jQuery('#fmComments').append(renderedComment);
    		}
    		jQuery('#fmFormOverlay').addClass('fmNoBackground');
    		// show the moderation message id needed
    		if (fm.comments.settings.moderation == 'pre') {
    			var out = fm.comments.settings.translate.moderationMessagePre;
    		} else {
    			var out = fm.comments.settings.translate.moderationMessagePost;
    		}
    		//
    		jQuery("#fmNewPost .fmReport").remove();
    		// display the message
    		jQuery('#fmFormOverlay').height(jQuery(jQuery('#fmFormOverlay').parents()[0]).height()+20);
    		jQuery('#fmFormOverlay').html('<span class="fmSuccess">'+out+'</span>');
    		//
    		jQuery('#fm.comments.postAnonComment').removeAttr('onsubmit');
    	},
    	function(exception) {
    		console.log(exception);
    		// remove the loader image and show the error and ok button
    		jQuery('#fmFormOverlay').addClass('fmNoBackground');
    		jQuery('#fmFormOverlay').html('<span class="fmError">'+fm.comments.settings.translate.error+'</span><a onclick="jQuery(this.parents()[0]).remove();" class="fmButton">'+fm.comments.settings.translate.close+'</a>');
		    // re-enable the text inputs and submit button
			jQuery('#fm.comments.postAnonComment input').each(function(f) {
				f.disabled = false;
			});
			// re-enable the comment text area
			jQuery('#fm.comments.postAnonComment textarea').each(function(f) {
				f.disabled = false;
			});
    	},
    	true
  	);
}

// Logout the user
fm.comments.logout = function() {
	// remove the cookie and refresh the page
	fm.cookies.addCookie("SABRE_ID",null);
	window.location = window.location;
}

// Log a hit in Media Factory
fm.comments.logHit = function(id) {
	var params = { "fileId" : id }		
	fm.comments.proxyRequest('media.logHit', params,
		function(results) { },
		function(exception) { console.log('Error'); }
	);	
}

fm.comments.rateArticle = function() {
	
	this.getRating = function(data) {

		jQuery('#fmRatingPeople').html(data.votecount);
		if(data.votecount == 1) jQuery('#fmRatingPeopleText').text("person");
		else jQuery('#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 += '<div class="fmStar"></div>'; }
		} else {
			for(i=0;i<this.rating;i++) { this.out += '<div class="fmStar fmFull"></div>';}
			for(i=4;i>=this.rating;i--) { this.out += '<div class="fmStar"></div>'; }		
		}
		
		jQuery('#fmRatingStars').html(this.out);
		
		this.out = "";
		for(i=0;i<5;i++) { this.out += '<div id="fmRate_'+i+'" class="fmStar"></div>'; }
		
		var ratingWord = [fm.comments.settings.translate.rating1,fm.comments.settings.translate.rating2,fm.comments.settings.translate.rating3,fm.comments.settings.translate.rating4,fm.comments.settings.translate.rating5]
		
		if(fm.cookies.getCookie('rated'+fm.comments.settings.externalId) != null) {
			this.rating = fm.cookies.getCookie('rated'+fm.comments.settings.externalId);
			this.out = "";
			for(i=0;i<this.rating;i++) { this.out += '<div class="fmStar fmFull"></div>';}
			for(i=4;i>=this.rating;i--) { this.out += '<div class="fmStar"></div>'; }			
			jQuery('#fmRatingUserStars').addClass("disabled").html(this.out);
			jQuery('#fmRatingWord').text(ratingWord[parseInt(this.rating-1)]);		
		} else {
			jQuery('#fmRatingUserStars').html(this.out);
			var mid = this.mid;
			jQuery('#fmRatingUserStars').children().each(function() {
				jQuery(this).mouseenter(function(){
					jQuery(this).addClass('fmFull');
					jQuery(this).prevAll().each(function(e) {
						jQuery(this).addClass('fmFull');
					});
					jQuery('#fmRatingWord').text(ratingWord[jQuery(this).index()]);
				});
				jQuery(this).mouseleave(function(){
					jQuery(this).removeClass('fmFull');
					jQuery(this).prevAll().each(function(e) {
						jQuery(this).removeClass('fmFull');
					});
					jQuery('#fmRatingWord').text(fm.comments.settings.translate.ratingUnrated);
				});
				jQuery(this).click(function() {
					jQuery(jQuery(this).parent()[0]).addClass("disabled");
					jQuery(jQuery(this).parent()[0]).children().unbind();
					myRating = jQuery(this).index()+1;
					
					var newRating = parseInt(jQuery('#fmRatingPeople').html())+1;
					if(newRating == 1) jQuery('#fmRatingPeopleText').text("person");
					else jQuery('#fmRatingPeopleText').text("people");
					jQuery('#fmRatingPeople').html(newRating);
					
					fm.comments.proxyRequest('media.rate', {"mid":mid,"rating":myRating,"uid":1,"returnData":true},
						function(result2) { fm.cookies.addCookie('rated'+fm.comments.settings.externalId, myRating, {path:"/", expires:1});},
						function(exception) { console.log(exception); }
					);
				});
			});	
		}	
	}
	
}

fm.comments.displayComment = function(currentComment) {
	if(currentComment.uid == 1) {
		avatar = fm.comments.settings.defaultAvatar;						
		var comment = { 
	        'username'  : fm.comments.stripHTML(currentComment.author), 
	        'comment'   : currentComment.message, 
	        'votecount' : currentComment.votecount, 
	        'upload'    : currentComment.upload, 
	        'uploadage' : fm.comments.makeUploadAge(currentComment.upload), 
	        'mid'       : currentComment.id, 
	        'profileid' : currentComment.uid, 
	        'avatar'    : avatar
	    };
		var renderedComment = jQuery.tmpl(fm.comments.commentBlock, comment); 
	} else {
		var avatar = '';
		if(currentComment.avatar != 0) {
			if (fm.comments.settings.env == 'dev') avatar = 'http://fmdev.s3.amazonaws.com/storage/' + currentComment.avatar + '/12';
			else avatar = 'http://rstorage.filemobile.com/storage/' + currentComment.avatar + '/12';
		}
		else avatar = fm.comments.settings.defaultAvatar;
										
		// if the comment is a text only comment, use the text comment template
		// else, use the media comment template
		
		var displayName = '';
		if (fm.comments.settings.showUsername !== true && fm.comments.settings.showFirstName === true || fm.comments.settings.showLastName === true) {
			if (fm.comments.settings.showFirstName === true) {
				displayName += currentComment.user_firstname;
			}
			if (fm.comments.settings.showFirstName === true && fm.comments.settings.showLastName === true) {
				displayName += ' ';
			}
			if (fm.comments.settings.showLastName === true) {
				displayName += currentComment.user_lastname;
			}
		} else {
			displayName += currentComment.user_name;
		}
								
		if (currentComment.filetype == 4) {
			var comment = {
	            'username' : displayName, 
	            'comment'  : currentComment.message, 
	            'votecount': currentComment.votecount, 
	            'upload'   : currentComment.upload, 
	            'uploadage': fm.comments.makeUploadAge(currentComment.upload), 
	            'mid'      : currentComment.id, 
	            'profileid': currentComment.uid, 
	            'avatar'   : avatar
	        };
			var renderedComment = jQuery.tmpl(fm.comments.commentBlock, comment); 
		} else if (currentComment.filetype == 1) {
			var comment = {
	            'username' : displayName, 
	            'comment'  : currentComment.message, 
	            'image'    : currentComment.publicUrl, 
	            'votecount': currentComment.votecount, 
	            'upload'   : currentComment.upload, 
	            'uploadage': fm.comments.makeUploadAge(currentComment.upload), 
	            'mid'      : currentComment.id, 
	            'profileid': currentComment.uid, 
	            'avatar'   : avatar
	        };
			var renderedComment = jQuery.tmpl(fm.comments.commentBlockWithImage, comment); 
		} else {
			var comment = {
	            'username' : currentComment.user_name, 
	            'comment'  : currentComment.message, 
	            'image'    : currentComment.publicUrl, 
	            'votecount': currentComment.votecount, 
	            'upload'   : currentComment.upload, 
	            'uploadage': fm.comments.makeUploadAge(currentComment.upload), 
	            'mid'      : currentComment.id, 
	            'profileid': currentComment.uid, 
	            'avatar'   : avatar
	        };
			var renderedComment = jQuery.tmpl(fm.comments.commentBlockWithVideo, comment); 
		}
	}
	
	return renderedComment;
}

fm.comments.autoUpdate = function() {
	
	var fields = ['filetype','uid','user_name','votecount','author','upload','message','publicUrl','status','avatar'];
	
	if (fm.comments.settings.showFirstName === true){
		fields.push('user_firstname');
	}
	
	if (fm.comments.settings.showLastName === true){
		fields.push('user_lastname');
	}
	
	var args = {
		sort      : fm.comments.settings.sort,
		limit     : 100,
		start     : 0,
		parentid  : fm.comments.parentId,
		context   : "comment",
		includeChildren : 1,
		channel   : 0,
		fields    : fields,
		timeLimit : fm.comments.settings.autoUpdateTime*fm.comments.autoUpdateCount
	}
	
	fm.comments.proxyRequest('media.getFiles', args,
		function(result) {
			// there are comments
			if(result.totalCount > 0) {
			
				fm.comments.startOffset += result.totalCount;
				fm.comments.autoUpdateCount = 1;
				
				// find out how many total comments there are
				fm.comments.commentCount = parseInt(jQuery('#fmCommentCount').text().substr(0,jQuery('#fmCommentCount').text().indexOf(' ')))+parseInt(result.totalCount);
				jQuery('#fmCommentCount').html(fm.comments.commentCount+" "+fm.comments.settings.translate.comments); // display the comment count
				
				var data = result.data;
			
				for (i=0;i<data.length;i++) {
					
					var renderedComment = fm.comments.displayComment(data[i]);
					
					if (jQuery('#comment_'+data[i].id).length === 0) {
						fm.comments.queue += renderedComment;
					}
										
				};
				
				if (fm.comments.queue.length > 0) {
				
					jQuery('title').text('('+result.totalCount+') '+fm.comments.title);
					
					if (jQuery('#fmAutoUpdateComments').length) {
						jQuery('#fmAutoUpdateComments').text(result.totalCount+' New Comments');
					} else {
						jQuery('#fmComments').prepend('<a class="fmUpdateComments" id="fmAutoUpdateComments">'+result.totalCount+fm.comments.settings.translate.newComments+'</a>');
						jQuery('#fmAutoUpdateComments').click(function() {
							jQuery('#fmAutoUpdateComments').remove();	
							if (fm.comments.settings.sort == "upload DESC") {
								jQuery('#fmComments').prepend(fm.comments.queue);
							} else {
								jQuery('#fmComments').append(fm.comments.queue);
							}	
							jQuery('title').text(fm.comments.title);		
							fm.comments.queue = '';
						});
					}
				
				}
			
			} else {
			
				fm.comments.autoUpdateCount++;
				
			}
		},
		function(exception) {	
			// oops, something went wrong
			console.log(exception);
		},
		true
	);
	
}

/*
fm.comments.lightbox = function(path) {

	// require the element that is going to appear in the lightbox
	if (path === null) {
		// remind the developer they need the element
		alert("Invalid Lightbox Parameter: Please pass element you wish to appear in the lightbox.");
		return false;
	} else {
		// create the element variable
		var element = '<img src="'+path+'"/>';
	}
	// remove the lightbox if it already exists for some reason
	if (jQuery('#fmLightboxBackground')) {
		jQuery('#fmLightboxBackground').remove();
		jQuery('#fmLightboxInside').remove();
	}

	jQuery('html').addClass('fmLightbox');
	
	// add a placeholder to the current position of the element
	jQuery(element).after('<div id="fmLightboxPlaceholder"></div>');
	
	// add the lightbox at the end of the page
	jQuery('body').append('<div class="background" id="fmLightboxBackground"></div><div id="fmLightboxInside" class="inside"></div>');
	
	// resize and position the lightbox, add the element to the lightbox and make sure it's visible and add the close button
	jQuery('#fmLightboxInside').prepend(element).append('<div class="close" id="fmLightboxClose"></div>').find('img').hide();
	
	jQuery('#fmLightboxInside img').load(function() {
		jQuery(this).show();
		// get the width and height of the element so we can resize the lightbox window to that size
		var height = jQuery(this).height();
		var width = jQuery(this).width();
		jQuery('#fmLightboxInside').css({'width':width+'px','height':height+'px','margin-top':-(height/2)+'px','margin-left':-(width/2)+'px'});
	})
	
	// close the lightbox
	fm.comments.lightboxClose = function() {
		jQuery('html').removeClass('fmLightbox');				
		jQuery('#fmLightboxBackground').remove();
		jQuery('#fmLightboxInside').remove();				
	}	
	
	// add the close function when the user hits the 'x'
	jQuery('#fmLightboxClose').live('click',function() {
		fm.comments.lightboxClose();
	});	
	
	// add the close function when the user hits the background of the lightbox
	jQuery('#fmLightboxBackground').live('click',function() {
		fm.comments.lightboxClose();
	});
	
}
*/
