// Field
function getElement(id) {
	return (typeof id == 'string' ? $(id) : id);
}

function showMessage(message, type) {
	if($('message')) {
		if(type == 'warn') $('message').addClassName('error');
		else $('message').removeClassName('error');
		
		$('message').update('<h2>' + message + '</h2>');
		$('message').show();
	} else {
		alert(message);
	}	
}

function focusField(id) {
	var oField = getElement(id);
	Element.addClassName(oField, 'error');
	oField.focus();
}

function blurField(id) {
	var oField = getElement(id);
	Element.removeClassName(oField, 'error');
}

function isUpdate(form) {
	return (form._method && form._method.value == 'put');
}

function showAjaxWaiting() {
	if($('ajax_waiting'))
		$('ajax_waiting').show();
}

function hideAjaxWaiting() {
	if($('ajax_waiting'))
		$('ajax_waiting').hide();
}

// Add a attachment.
function addAttachment(container, type) {
	if(typeof container == 'undefined') container = 'attachments';
	if(typeof type == 'undefined') type = 1;
	
	var html = $('attachment').innerHTML;
	html = html.gsub(/#\{NO\}/, countAttachment() + 1);
	html = html.gsub(/#\{ATTACH_TYPE\}/, type);
	new Insertion.Bottom(container, html);
} 

function countAttachment() {
	var attachments = $$('div.board div.attachment');
	return attachments.length;
}

// Checked value.
function _getCheckedValue(name) {
	var elements = document.getElementsByName(name);
	var value = null;
	
	for(var i = 0; i < elements.length; i++) {
		if(elements[i].checked) {
			value = elements[i].value;
			break;
		}
	}
	
	return value;
}

// Checkbox
function checkAll(name) {
	if(typeof name == 'undefined') name = 'checks[]';
	
	var checks = document.getElementsByName(name);
	$A(checks).each(function(el) {
		el.checked = !el.checked;
	});
}

function getChecked(name) {
	if(typeof name == 'undefined') name = 'checks[]';
	var sChecked = ''	// ex. 1,2,3
	
	var checks = document.getElementsByName(name);
	$A(checks).each(function(el) {
		if(el.checked) {
			if(sChecked != '') sChecked += ','
			sChecked += el.value;
		}
	});
	
	return (sChecked == '' ? null : sChecked);
}

function IE_HtmlRewrite(objParent) {
	if (window.ActiveXObject && objParent) {
		objParent.innerHTML = objParent.innerHTML;
	}
}

function openPlanner() {
	window.open('/planners/new/intro', 'planner', 'width=950px, height=650px');
}