function safelog(msg, level, source) {

   var lvl = level || "info";
   var src = source ||  "unknown"
   try {
	   if(window.console && window.console.log) { console.log(lvl + ": [" + src + "] " + msg); }
   } catch(e) { }
}

$(document).ready(function() {

	$('.edit_message').bind('ajax:success', editMessage);
	cmxform();
	$('.sticky').bind('ajax:success', changeSticky);	
	$(".blank").each(function() {
		$(this).attr("target", "_blank");
	});

	var count = 0;
	$('#topic_table tr').not('#topic_header').each(function(i) {
		topic_id = this.id.replace(/topic_/,'');
		cur_topic_list[count] = topic_id;
		count++;
	});
	
	$('.edit_message_open').click(function(e) {
		preventDefault(e);
		
		$('#post_' + $(this).attr('id').split('_')[1]).slideDown();
	});

	$('.login').click(function(e) {
		if(e) preventDefault(e);
		left_pos = getViewportWidth()-250;
		$('#inpage_login').css({'left':left_pos + 'px', 'top': '30px'}).fadeIn();
	});

	
	$('#newspost img').load(function(e) {
		$(this).css('width', '620px');
	});

	$('#inpage_login form').submit(function(e) {
		if(e) preventDefault(e);
		data = $(this).serialize();
		
		$.post($(this).attr('action'), data, function(d) {
			//for(prop in d) {
			
			//}

			$('#navigation').empty();

			var na = new NodeAssembly($('#navigation').get(0));

			na.createEl('a', {'href': '/topic/'}, 'Board');
			na.createEl('a', {'href': '/member/'}, 'Roster');
			na.createEl('a', {'href': '/photo/'}, 'Photos');
			na.createEl('a', {'href': '/apply/pending'}, 'Pending Applicants');
			na.createEl('a', {'href': '/member/logout'}, 'Logout');
			na.insertIn();

			$('#inpage_login').fadeOut();
		});
	});

});

function getViewportWidth() {
	var width = self.innerWidth;  // Safari
    var mode = document.compatMode;
    
    if (mode || $.browser.msie) { // IE, Gecko, Opera
        width = (mode == 'CSS1Compat') ?
        document.documentElement.clientWidth : // Standards
        document.body.clientWidth; // Quirks
    }
    return width;
};

function getViewportHeight() {
    var height = self.innerHeight; // Safari, Opera
    var mode = document.compatMode;

    if ( (mode || $.browser.msie) && !$.browser.opera ) { // IE, Gecko
        height = (mode == 'CSS1Compat') ?
                document.documentElement.clientHeight : // Standards
                document.body.clientHeight; // Quirks
    }
    return height;
};

function preventDefault(ev) {
	if (ev.preventDefault)
		ev.preventDefault();
	else
		ev.returnValue = false;
};

window.onload = resizeImages;
function resizeImages() {
	for (x=0; x <= document.images.length; x++) {
		if (document.images[x]) {
			if (document.images[x].width > 940) {
				document.images[x].width = 940;
				safelog("resizing image: " + x, "info", "resize images");
			}
		}
	}
}

function cmxform(){
	// Processing
	$('form.cmxform').find('li label').not('.nocmx').each(function(i){
		var labelContent = this.innerHTML;
		var labelWidth = document.defaultView.getComputedStyle(this,'').getPropertyValue('width');
		var labelSpan = document.createElement('span');
		labelSpan.style.display = 'block';
		labelSpan.style.width = labelWidth;
		labelSpan.innerHTML = labelContent;
		this.style.display = '-moz-inline-box';
		this.innerHTML = null;
		this.appendChild(labelSpan);
	});
}

function customAlert(txt) {
	$("#alert").css("left", (document.documentElement.scrollWidth - 500)/2 + "px");
	$("#alert").css("top", (document.documentElement.scrollTop + 200) + "px");
	$("#alert div").html(txt);
	$("#alert").show();

	$("#alert .button").css("cursor","pointer");
	$("#alert .button").click(hideAlert);
}

function hideAlert() {
	$("#alert div").html('');
	$("#alert").hide();
}

function changeSticky() {
	if($(".sticky").text() == 'sticky topic') {
		$(".sticky").html('unsticky topic');
	} else {
		$(".sticky").html('sticky topic');
	}
}

function removeTopic() {
	console.log('oh hai')
	document.location = '/topic';
}

function changeLock(status) {
	if($(".lock").text() == 'lock topic') {
		$(".lock").html('unlock topic');
	} else {
		$(".lock").html('lock topic');
	}
}

function changeProtect(status) {
	if($(".protect").text() == 'protect topic') {
		$(".protect").html('unprotect topic');
	} else {
		$(".protect").html('protect topic');
	}
}

function replyWithQuote(tag) {
	if(document.getElementById('topic_message_body').value.length) {
		document.getElementById('topic_message_body').value = document.getElementById('topic_message_body').value + '\r\n\r\n' + tag;
	} else {
		document.getElementById('topic_message_body').value = tag;
	}
}

function insert_smiley(smile) {
	document.getElementById('topic_message_body').value = document.getElementById('topic_message_body').value + ' ' + smile;
	return false;
}

function hideForm(id) {
	Effect.BlindUp('post_' + id, {duration: 1});
}

function switchPhoto(id) {
	$(".default").removeClass("default");
	$("#photo_"+id).addClass("default");
}

function deletePhoto(id) {
	$("#photo_"+id).css("display","none");
}

function closeEmailBox() {
	TB_remove();	
}

function clearChildNodes(atNode, nodeType) {
	try {
		if(nodeType != null && nodeType != 'undefined') {
			var remNodes = atNode.getElementsByTagName(nodeType);
		} else {
			var remNodes = atNode.childNodes;
		}
		var nodeLim = remNodes.length;
		for(var x = 0; x<nodeLim; x++) {
			atNode.removeChild(remNodes[0]);
		}
	} catch(e) { 
		safelog("Error, {" + atNode + ", " + nodeType + "} : " + e, "error", "clearChildNodes"); 
	}
}

function NodeAssembly(baseEl) {
	this.baseEl = baseEl || null;
	this.nodes = [];
	this.assemblies = []
}

NodeAssembly.prototype = {
	attrAliasMap: { 
		"class": "className", 
		"for"  : "htmlFor"
	},
	htmlDecode: function(entityString) {
		var tempEl = document.createElement("b");
		tempEl.innerHTML = entityString;
		var ret = getNodeText(tempEl);
		tempEl = null;
		return ret;
	},
	createAnonEl: function(elType, attributes, content) {
		var el = document.createElement(elType);
		if(attributes != null) {
			for(var attr in attributes) {
				if(typeof attributes[attr] != "function") {
					if(this.attrAliasMap[attr]) {
						el[this.attrAliasMap[attr]] = attributes[attr];
					} else { 
						el.setAttribute(attr, attributes[attr]); 
					}
				}
			}
		}
		if(content && content!=null){
			if(content.htmlStr) {
				el.innerHTML = content.htmlStr;		   	
   			} else if(typeof content == "string") {
   				el.appendChild(document.createTextNode(content));
			} else {
				el.appendChild(content);
  			}
   		}
   		
   		return el;
	},
	createEl: function(elType, attributes, content) {
		this.nodes.push(this.createAnonEl(elType, attributes, content));
	},
	createElWithReturn: function(elType, attributes, content) {
		var el = this.createAnonEl(elType, attributes, content);
		this.nodes.push(el);
		return el;
	},
	createTextEl: function(str) {
		this.nodes.push(document.createTextNode(str));
	},
	createElWithAssembly: function(elType, attributes) {
		var el = this.createElWithReturn(elType, attributes);
		var na = new NodeAssembly(el);
		this.assemblies.push(na);
		return na;
	},
	insertDocFrag: function() {
		var docFrag = document.createDocumentFragment();
		var nodesLim= this.nodes.length;
		for(var x=0; x<nodesLim; x++) {
			docFrag.appendChild(this.nodes[x]);
		}
		this.insertAssemblies();
		return docFrag;
	},
	insertIn: function(el) {
		var insertion = (el) ? el : this.baseEl;
		if(insertion && insertion.appendChild) {
			var docFrag = this.insertDocFrag();
			insertion.appendChild(docFrag);
		}
	},
	insertAssemblies: function() {
		var assLim = this.assemblies.length;
		for(var x=0; x<assLim; x++) {
			this.assemblies[x].insertIn()
		}
	}
}

function getTag(docObj, tag, inst) {
	var instance = inst || 0;
	var ret = '';
	try {
		var atNode;
		try { 
			atNode = docObj.getElementsByTagName(tag)[instance]; 
		} catch(e) { 
			safelog("Error getting tag '" + tag + "': " + e, "error", "getTag"); 
		}
		if(atNode) { ret = getNodeText(atNode); }
			ret = (ret) ? ret : "";
	} catch(e) { 
		safelog(e, "error", "getTag");
	}
	return ret;
}

function getNodeText(docNode) {
   try {
	   var retText = null;
	   var retNode	= docNode.childNodes[0];
	   if(retNode != null){ retText = retNode.nodeValue; }
	   return retText;
   } catch(e) {
	   return false;
   }
}

function getTopics() {	
	$.ajax({
		type: "GET",
		url: "/topic.xml",
		dataType: "xml",
		success: writeTopics,
		failure: function() {
			safelog("failed to get topics", "error", "getTopics");
		}
	});
}

var ThreadManager = {
	moveTopic: function(o, old_topic, new_topic) {
		this.deleteTopic(old_topic);
		this.addTopic(o, new_topic);
	},
	addTopic: function(o, row_num) {
		topic_table = $('#topic_table').get(0);
		tr = topic_table.insertRow(row_num);
		
		is_unread = getTag(o, 'is-unread');
		td = tr.insertCell(tr.cells.length);
		td.innerHTML = '<a href="/topic/view/' + getTag(o,'id') + '/' + getTag(o,'stripped-title') + '">' + getTag(o,'subject') + '</a>';
		if(parseInt(getTag(o,'pages')) > 1) {
			td.innerHTML += ' [<a href="/topic/view/' + getTag(o,'id') + '/' + getTag(o, 'stripped-title') + '/?page=' + getTag(o,'pages') + '">' + getTag(o, 'pages') + '</a>]';
		}
		if(is_unread) td.className = 'unread';
		
		td = tr.insertCell(tr.cells.length);
		td.innerHTML = getTag(o,'num-replies');

		td = tr.insertCell(tr.cells.length);
		td.innerHTML = '<a class="thickbox" href="/member/profile/' + getTag(o,'member-login') + '?width=700&height=500">' + getTag(o,'member-display-name') + '</a>';
		
		td = tr.insertCell(tr.cells.length);
		td.innerHTML = getTag(o, 'updated-at');

		td = tr.insertCell(tr.cells.length);
		td.innerHTML = '<a class="thickbox" href="/member/profile/'+getTag(o, 'last-member-login') + '?width=700&height=500">'+getTag(o, 'last-member-display-name')+'</a>';

		new Effect.Opacity(tr, {duration: 2.0, from: 0.0, to: 1.0});
	}
}

cur_topic_list = new Array();
function writeTopics(o) {
	var topic_table = $('#topic_table').get(0);
	if(topic_table) {
		xml = o.responseXML;
		var topics = xml.getElementsByTagName('topic');
		var topicLim = topics.length;
		var topic_list = new Array();
		var row_count = 1;
		for(i = 0; i < topicLim; i++) {
			topic_id = getTag(topics[i],"id");
			topic_list[i] = topic_id;
			for(j = 0; j < cur_topic_list.length; j++) {
				if(cur_topic_list[j] == topic_id) {
					cur_topic_list.splice(j,1);
					topic_table.deleteRow(j+(row_count));
					break;
				}
			}
			ThreadManager.addTopic(topics[i],row_count);
			row_count++;
			if(document.title.match(/^\(\*\)/) != '(*)') {
				document.title = '(*) '+ document.title;
			}
		}

		if(!topicLim) document.title = document.title.replace(/\(\*\)/,'');
	
		var total_rows = topic_table.rows.length - 1;
		for (i = 0; i < (total_rows - 50); i++) {
			topic_table.deleteRow(topic_table.rows.length - 1);
			cur_topic_list.pop();
		}
		cur_topic_list = topic_list.concat(cur_topic_list);
		
	}

	
}

function editMessage(e, d) {
	$('#message_' + d.message_cache.message_id).html(d.message_cache.message_body);
	$('#post_' + d.message_cache.message_id).slideUp();
};

