/*
 * selects the active navigation main and sub category
 */

function setNav(main_el, sub_el) {
	$$('.navigator .items .item').each (function(el) {
		el.removeClassName('active_item');
	})
	$(main_el).addClassName('active_item');
	$$('.sub_navigator').each (function(el) {
		el.removeClassName('active_sub_navigator');
	});
	$(main_el + '_subnav').addClassName('active_sub_navigator');
	$$('.sub_navigator .items .item').each (function(el) {
		el.removeClassName('active_item');
	});
	if ($(sub_el)) {
		$(sub_el).addClassName('active_item');
	}
}


/* 
 * dynamic javascript list 
 */

var jsListLists = {};

function jsList(ident, cols, data) {
	jsListLists[ident] = {
		'cols' : cols,
		'data' : data
	};
	prefix = 'jsList_' + ident;
	
	document.writeln('<ul class="table">');
		document.writeln('<li class="table_row">');
			cols.forEach(function(col) {
				document.writeln('<div style="width: ' + col.width + 'px;">');
					if (col.action) {
					} else {
						if (col.sort) {
							document.writeln('<a href="#" onclick="jsListDoSortListBy(\'' + ident + '\', \'' + col.sort + '\', false)">' + col.label + '</a>');
						}	else {
							document.writeln(col.label);
						}
				}
				document.writeln('</div>');
			});
		document.writeln('</li>');
	document.writeln('</ul>');
	document.writeln('<ul id="' + prefix + '" class="table">');
		data.sort(jsListSortHashListBy('id')).forEach(function (row) {
			document.writeln('<li class="table_row" id="' + prefix + '_' + row['id'] + '">');
				cols.forEach(function(col) {
					document.writeln('<div style="width: ' + col.width + 'px; ' + (col.align ? 'text-align: ' + col.align + ';' : '')  + '">');
						if (col.action) {
							document.writeln('<a href="' + col.action + row.id + '">' + col.label + '</a>');
						} else {
							document.writeln(row[col.field]);
						}
					document.writeln('</div>');
				});
			document.writeln('</li>');
		});
	document.writeln('</ul>');
}
	

function jsListDoSortListBy(ident, field, reverse) {
 	prefix = 'jsList_' + ident;
	list = document.getElementById(prefix);
	sorted_data = jsListLists[ident]['data'].sort(jsListSortHashListBy(field));
	if (reverse) {
		sorted_data = sorted_data.reverse(); 
	}
	sorted_data.forEach(function (row) {
		list.appendChild(document.getElementById(prefix + '_' + row['id']));
	});
}	

function jsListSortHashListBy(field) {
	return function (a, b) {
		if (a[field] < b[field]) return -1;
		if (a[field] > b[field]) return 1;
		return 0;
	}
}