/* Copyright (c) 2006 by Apple Computer, Inc.  All Rights Reserved. */

var commentJavascriptVersion = "$Revision: 1.39 $";
var commentWindow;

// global strings
var commentsAppURL = 'http://www.mac.com/WebObjects/Comments.woa/wa/comment';
var manageCommentsAppURL = 'http://www.mac.com/WebObjects/Comments.woa/wa/manage';
var windowRules = 'menubar=no,resizable=no,height=580,width=435';
var commentsURL = location.pathname + '?wsc=entry.js&ts=' + new Date().getTime();

function data(o)
{
	// there are comments
	comments.read = true;
	comments.update(o);
}

// Load localization
document.write('<script src="http://www.mac.com/1/up/comments/scripts/loc.js" type="text/javascript" charset="utf-8"></script>');

// Load utility objects
document.write('<script src="http://www.mac.com/1/up/comments/scripts/utility.js" type="text/javascript" charset="utf-8"></script>');

// Called from the window.onload method
function initComments()
{
	browser.detect();
	setLocale();
	decorations.init();
	if (commentsActivated) {
		comments.fetch();
	} 
	else {
		decorations.hide('comment_layer'); // commenting never turned on
	}
}

var comments = {

	read: false,
	count: 0,
	canComment: false,
	hasComments: false,
	itemOrder: ['authorblock','commenttext','dateblock','attachments','separator'],
	view : 0,
	
	// fetch comments from iDisk
	fetch: function()
	{
		var c = comments;
		
		// Find and remove JSON loading script element
		var JSONScript = document.getElementById('view_' + c.view);
		var head = document.getElementsByTagName('head')[0];
		if (JSONScript !== null) {
			head.removeChild(JSONScript);
			c.view = c.view + 1;
		}
		
		JSONScript = document.createElement('script');
		
		// Create new JSON script element, new script element will call comments.update()
		JSONScript.setAttribute('id','view_' + c.view);
		JSONScript.setAttribute('src',location.pathname + '?wsc=entry.js&ts=' + new Date().getTime());
		JSONScript.setAttribute('type','text/javascript');
		JSONScript.setAttribute('charset','utf-8');
		head.appendChild(JSONScript);
	},
	
	// Callback from JSON result
	update: function(JSONResult)
	{
		var c = comments;
		
		// Update Flags and Counts
	
		// canComment
		if (JSONResult.commentsEnabled == 'true') {
			c.canComment = true;
		} 
		else {
			c.canComment = false;
		}		
		
		// hasComments
		if (JSONResult.items !== null && JSONResult.items.length > 0) {
			c.hasComments = true;
		}
		else {
			c.hasComments = false;
		}
		
		// count
		if (JSONResult.items !== null) {
			c.count = JSONResult.items.length;
		}
		else {
			c.count = 0;
		}
		
		if (!c.canComment && c.count == 0) {
			decorations.hide('comment_layer'); // entries w/o comments created when the blog allowed commenting
		}	
		else if (c.count > 0) {
			c.load(JSONResult.items);
			if (!c.canComment) {
				decorations.hide('comment_footer'); // entries w/comments while the blog allowed commenting
			}
		}
		else {
			decorations.hide('comment_title'); // entry w/o comments, but blog allows commenting
		}
		
		// update page decorations
		decorations.update_count();
		decorations.update_manage_comments();
		decorations.update_post_link();
		
		pngs.fix();
		
	},
	
	// insert comments into page
	load: function(items)
	{
		
		var c = comments;
		var commentlist;
		
		commentlist = document.getElementById('comment_list');

		if (commentlist === null) { return; }
			
		var comment;	
		var id;
		
		for (var i = 0; i < items.length; i ++) {
	
			// remember to replace '-' with '_' and prefix the UUID of the comment so that it's a valid element id.
			id = 'comment_' + items[i].commentID.replace(/\-/g,'_');
		
			// don't reinsert already existing comments
			if(document.getElementById(id) === null) {
		
				comment = document.createElement('div');
				comment.className = 'commentblock';
	
				
				var anchor = document.createElement('a');
				if (anchor != null) { 
					anchor.setAttribute('name',id);
					anchor.setAttribute('id',id);
					comment.appendChild(anchor);
				}
				
				// loop over properties in comment, if a property has a callback function defined, then call it
				for (var j = 0; j < c.itemOrder.length; j++) {
					if (render[c.itemOrder[j]] !== undefined) {
						render[c.itemOrder[j]](comment,items[i]);
					}			
				}
						
				commentlist.appendChild(comment);
				comment = null;
			
			}
			
		}
	
	}
}

var decorations = {
	list: ['count','manage_comments','post_link','comment_layer','comment_footer','comment_title'],
	init: function ()
	{
		var d = decorations;
		
		// loop over properties in decorations
		for (var i = 0; i < d.list.length; i++) {
			d[d.list[i]] = d.collect(d.list[i]);
		}	
	},

	// collect gathers all the placeholders for a placeholder of type name and returns them in the array collection
	collect: function(name)
	{
		var collection = [];
		var e, i = 0;
		
		// look for the base version of the item name # to remove
		e = document.getElementById(name);
		if (e !== null) { collection.push(e); }
		
		// loop over name_N until you cannot find
		e = document.getElementById(name + '_' + i);		
		while (e !== null) {
			collection.push(e);
			i ++;
			e = document.getElementById(name + '_' + i);
		}
		return collection;
	},
	
	update_count: function()
	{
		var d = decorations;
		
		for (var i = 0; i < d.count.length; i ++) {
			if (comments.hasComments) {
			
				d.show('comment_title');
				
				var s = document.createTextNode(commentCountString(comments.count));
				var r = d.count[i].firstChild;
				
				if (d.count[i].hasChildNodes && r != null) {
					d.count[i].replaceChild(s,r);
				}
				else {
					d.count[i].appendChild(s);
				}
				
			} 
		}	
	},
	
	update_manage_comments: function()
	{
		var d = decorations;
		
		for (var i = 0; i < d.manage_comments.length; i ++) {
		
			var r = d.manage_comments[i].firstChild;

			// insert control if none found
			if (comments.hasComments && r == null) {
				var managelink = document.createElement('a');
				var commentcontrolGlyph = document.createElement('img');
				
				// use element's class name to determine which image to use
				switch (d.manage_comments[i].className) {
					case 'light':
						commentcontrolGlyph.src = 'http://www.mac.com/1/up/comments/images/lockIcon_dark.png';
						break;
					case 'dark':
					default:
						commentcontrolGlyph.src = 'http://www.mac.com/1/up/comments/images/lockIcon_light.png';				
				}
				
				commentcontrolGlyph.alt = localeStringForKey('managecomments');
				commentcontrolGlyph.title = localeStringForKey('managecomments');
				commentcontrolGlyph.id = 'manage_comments_icon_' + i;
				managelink.appendChild(commentcontrolGlyph);
				managelink.href = manageCommentsAppURL + '?url=' + encodeURIComponent(decodeURIComponent(location.pathname)); // prevent double encoding

				d.manage_comments[i].appendChild(managelink);
				
				pngs.add('manage_comments_icon_' + i);
				
				managelink = null;				
				commentcontrolGlyph = null;
			}
		}
	},
	
	update_post_link: function()
	{
		var d = decorations;
		
		for (var i = 0; i < d.post_link.length; i ++) {
			
			var r = d.post_link[i].firstChild;
		
			if (comments.canComment && r == null) {
				var commentlink = document.createElement('a');
				var s = document.createTextNode(localeStringForKey('addcomment'));
				commentlink.appendChild(s);
				commentlink.href = '#';
				commentlink.onclick = function() 
				{
					var name;
					
					// compute window name from blog entry ID
					var path = location.pathname.split('/');
					if (path.length > 0) {
						name = path[path.length - 1];
					}
					else {
						name = 'entry.html';
					}
					name = name.replace('.html','');
					name = 'comment_' + name.replace(/\-/g,'_');
					commentWindow = window.open(commentsAppURL + '?url=' + encodeURIComponent(decodeURIComponent(location.pathname)),name,windowRules); // prevent double encoding & clean up window name
					listenForChildWindow(); // start listener
					return false;	
				}
				commentlink.style.fontWeight = 'bold';
				commentlink.title = localeStringForKey('addcommentcaption');
				d.post_link[i].appendChild(commentlink);	
				commentlink = null;
			}
		}
	},
		
	hide: function(name)
	{	
		var d = decorations;
		var set = d[name];
		for (var i = 0; i < set.length; i++) {
			if (set[i] !== null) { set[i].style.display = 'none'; }
		}
	},
	
	show: function(name)
	{
		var d = decorations;
		var set = d[name];
		for (var i = 0; i < set.length; i++) {
			if (set[i] !== null) { set[i].style.display = 'block'; }
		}
	}

};

// Callback Functions For Rendering Comments
var render = {
	commenttext: function(comment,data) 
	{
		var	body = document.createElement('div');
		body.className = 'commenttext';
		body.style.overflow = 'auto';
		body.innerHTML = data.body.replace(/\r\n/g,'<br />');
		comment.appendChild(body);
		body = null;	
	},
	authorblock: function(comment,data)
	{
		if (data.authorID !== '') {
			var author = document.createElement('div');
			var authorID = document.createTextNode(data.authorID);
			var fn = null;
			author.className = 'authorblock vcard';
			var url = this.authorurl(data);
			if (url != null) {
				url.appendChild(authorID);
				author.appendChild(url);
			} 
			else {
				fn = document.createElement('span');
				fn.className = 'fn';
				fn.appendChild(authorID);
				author.appendChild(fn);
			}
			comment.appendChild(author);
			author = null;
		} 
		else {
			return;
		}
	},
	authorurl: function(data)
	{
		var author = null;
		
		if (data.authorURL !== undefined && data.authorURL !== '') {
			author = document.createElement('a');
			author.setAttribute('href', data.authorURL);
		} 
		else {
			return null;
		}
		
		if (data.authorURL.indexOf('mailto:') > -1) {
			author.className = 'email fn';
		}			
		else if (data.authorURL.indexOf('http://') > -1) {
			author.className = 'url fn';
		}
		else {
			author.className = 'fn';
		}
		
		return author;
	},
	dateblock: function(comment,data)
	{
		var date = document.createElement('div');
		date.className = 'dateblock';
		date.innerHTML = data.createDate;
		comment.appendChild(date);
		date = null;	
	},
	attachments: function(comment,data)
	{
		
		var attachment;
		var preview;
		var link;
		var desc;
		
		if (data.attachments === undefined) { return; }
		
		for (var i = 0; i < data.attachments.length; i++) {
		
			// container
			attachment = document.createElement('div');
			
			// thumbnail w/link
			link = document.createElement('a');
			link.title = data.attachments[i].mimetype;
			link.href = location.pathname + data.attachments[i].urlDownload;
			
			preview = document.createElement('img');
			preview.id = 'attachment_' + data.commentID.replace(/\-/g,'_') + '_' + i;
			
			// deal with multiple definitions of thumbnail here
			if (data.attachments[i].urlPreview !== undefined) {
				preview.src = data.attachments[i].urlPreview;
			} 
			else if (data.attachments[i].previewUrl !== undefined) {
				preview.src = data.attachments[i].previewUrl;			
			}
			else {
				preview.src = 'http://www.mac.com/1/up/comments/images/attach_generic_big.png';
			}
			link.appendChild(preview);
			attachment.appendChild(link);
		
			// handle image v. other attachment
			if (!this.isImage(data.attachments[i].mimetype)) {
			
				var space = document.createTextNode('\xA0');
				attachment.appendChild(space);
				space = null;
			
				desc = document.createElement('a');
				desc.className = 'description';
				desc.href = location.pathname + data.attachments[i].urlDownload;

				if (data.attachments[i].displayname !== undefined) {
					desc.innerHTML = this.formatDisplayName(data.attachments[i].displayname,data.attachments[i].size);
				} 
				else {
					desc.innerHTML = this.formatDisplayName(data.attachments[i].filename,data.attachments[i].size);				
				}
				attachment.className = 'fileattachment';
				pngs.add(preview.id);				
				attachment.appendChild(desc);
			}
			else {
				attachment.className = 'imageblock';			
			}

			comment.appendChild(attachment);
			
			// cleanup 
			attachment = null;
			preview = null;
			link = null;
			desc = null;
		}
	},
	separator: function(comment)
	{
		var separator = document.createElement('div');
		separator.className = 'separator';
		separator.innerHTML = '&nbsp;';
		comment.appendChild(separator);
		separator = null;	
	},
	
	bytesToString: function(str)
	{
		var bytes = Number(str);
		
		if (bytes < 1024) {
			return localeStringForKey('bytes', bytes.toLocaleString());
		}
		else if (bytes < 1048756) {
			var kb = bytes / 1024.0;
			return localeStringForKey('KB', Number(kb.toFixed(1)).toLocaleString());
		}
		else if (bytes < 1073741824) {
			var mb = bytes / 1048756.0
			return localeStringForKey('MB', Number(mb.toFixed(1)).toLocaleString());
		}
		else {
			var gb = bytes / 1073741824.0;
			return localeStringForKey('GB', Number(gb.toFixed(1)).toLocaleString());
		}	
	},
	
	isImage: function(mimetype)
	{
		switch (mimetype.toLowerCase()) {
			case 'image/gif' :
			case 'image/jpg' :
			case 'image/jpeg':
			case 'image/pjpeg':
				return true;
			default:
				return false;
		}
	},
	
	formatDisplayName: function(displayname,size)
	{
		return displayname + '&#160;&#160;&#160;' + this.bytesToString(size);
	}
};

// Listen for the child comment entry window to close, then reload yourself.
function listenForChildWindow()
{
	if (!browser.safari && commentWindow.closed) {
		comments.fetch();
		commentWindow = null; // gc
	} 
	else if (browser.safari && commentWindow.name == 'canreload') {
		comments.fetch();
	} 
	else {
		setTimeout(listenForChildWindow,500);
	}
}
